Created
December 29, 2020 17:03
-
-
Save lambdan/03e86c17673eb3b1564fe916d04d7a5d to your computer and use it in GitHub Desktop.
extract highlights from video using list of timestamps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os, subprocess, sys | |
# usage: extract_highlights.py <path-to-video> <path-to-timestamps> | |
# timestamps file format: | |
# hh:mm:ss bla bla bla | |
before_secs = 5 # secs to include before clip timestamp | |
after_secs = 25 # -"- after -" ... 5+25 = 30 sec clip | |
safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -0123456789." | |
def hhmmss_to_sec(hhmmss): | |
hours = int(hhmmss.split(":")[0]) | |
mins = int(hhmmss.split(":")[1]) | |
secs = int(hhmmss.split(":")[2]) | |
hours_to_secs = hours*60*60 | |
mins_to_secs = mins*60 | |
total = hours_to_secs + mins_to_secs + secs | |
return total | |
def safe_filename(text): | |
string = [] | |
for c in text: | |
if c in safe_chars: | |
string.append(c) | |
return "".join(string) | |
def extract_video(videofile, timestamp, before, after, outfile): | |
timestamp = str(hhmmss_to_sec(timestamp) - before) | |
duration = str(before+after) | |
command = ["ffmpeg", "-loglevel", "error", "-ss", str(timestamp), "-i", videofile, "-t", duration, "-crf", "17", "-b:a", "320k", "-pix_fmt", "yuv420p", outfile] | |
print("Extracting", outfile) | |
subprocess.call(command) | |
video = sys.argv[1] | |
text = sys.argv[2] | |
folder_name = os.path.splitext(text)[0] | |
if not os.path.isfile(video): | |
print("is not video file:", video) | |
if not os.path.isfile(text): | |
print("is not text file:", text) | |
if not os.path.isdir(folder_name): | |
os.makedirs(folder_name) | |
with open(text, encoding="utf8") as f: | |
lines = f.readlines() | |
for line in lines: | |
print() | |
time = line.split(" ")[0] | |
filename = folder_name + "/" + safe_filename(folder_name + "-" + line) + ".mp4" | |
extract_video(video, time, before_secs, after_secs, filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment