Skip to content

Instantly share code, notes, and snippets.

@mathewthe2
Last active February 25, 2022 04:36
Show Gist options
  • Save mathewthe2/f1db5207e7a90bcae16acc4d4a51adb9 to your computer and use it in GitHub Desktop.
Save mathewthe2/f1db5207e7a90bcae16acc4d4a51adb9 to your computer and use it in GitHub Desktop.
Regenerate snapshots for subs2srs decks
import os
import re
import json
import subprocess
from distutils.spawn import find_executable
adjustment = 0
if '/usr/local/bin'not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/usr/local/bin:" + os.environ['PATH']
if '/opt/homebrew/bin' not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/opt/homebrew/bin:" + os.environ['PATH']
ffprobe_executable = find_executable("ffprobe")
ffmpeg_executable = find_executable("ffmpeg")
def processed_to_ffmpeg_time(time):
h, m, s, ss = re.split(r'[,\.]', time)
total_s = int(h)*3600 + int(m)*60 + int(s) + int(ss)/1000
total_s += adjustment
return seconds_to_ffmpeg_time(total_s)
def get_time_parts(time):
millisecs = str(time).split(".")[1][:3]
if len(millisecs) != 3:
millisecs = millisecs + ('0' * (3 - len(millisecs)))
millisecs = int(millisecs)
mins, secs = divmod(time, 60)
hours, mins = divmod(mins, 60)
return (hours, mins, secs, millisecs)
def seconds_to_ffmpeg_time(time):
return '%02d:%02d:%02d.%03d' % get_time_parts(time)
def get_snapshot(video_name, raw_episode, raw_time):
video_file = '{}.mkv'.format(int(raw_episode))
video_height = 360
snapshot_filename = video_name + '_' + raw_episode + '_' + raw_time + '.jpg'
snapshot_time = processed_to_ffmpeg_time(raw_time) #'00:10:12'
print('time', snapshot_time)
cmd = [ffmpeg_executable, "-y", "-ss", snapshot_time, "-i", video_file, "-loglevel", "quiet", "-vf", "scale={}:{}".format(-2, video_height), "-vframes", "1", "-q:v", "2", snapshot_filename]
print(cmd)
subprocess.run(cmd)
def main(image_column, testing=False):
with open('deck.json', encoding='utf-8') as f:
data = json.load(f)
notes = data['notes']
video_name = data['name'].replace(' ', '_')
if testing:
notes = notes[:3]
for note in notes:
s = note['fields'][image_column]
episode = s.split(video_name + "_")[1].split("_")[0]
timestamp = s.split(video_name + "_" + episode + '_')[1].split(".jpg")[0]
get_snapshot(video_name, episode, timestamp)
main(2)
@mathewthe2
Copy link
Author

Target Episode:

import os
import re
import json
import subprocess
from distutils.spawn import find_executable

adjustment = 90
target_episode = 2

if '/usr/local/bin'not in os.environ['PATH'].split(':'):
    # https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
    os.environ['PATH'] = "/usr/local/bin:" + os.environ['PATH']

if '/opt/homebrew/bin' not in os.environ['PATH'].split(':'):
    # https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
    os.environ['PATH'] = "/opt/homebrew/bin:" + os.environ['PATH']

ffprobe_executable = find_executable("ffprobe")
ffmpeg_executable = find_executable("ffmpeg")

def add_delay(time):
    h, m, s, ss = re.split(r'[,\.]', time)
    total_s = int(h)*3600 + int(m)*60 + int(s) + int(ss)/1000
    total_s += adjustment
    return seconds_to_ffmpeg_time(total_s)

def get_time_parts(time):
    millisecs = str(time).split(".")[1][:3]
    if len(millisecs) != 3:
        millisecs = millisecs + ('0' * (3 - len(millisecs)))
    millisecs = int(millisecs)
    mins, secs = divmod(time, 60)
    hours, mins = divmod(mins, 60)

    return (hours, mins, secs, millisecs)

def seconds_to_ffmpeg_time(time):
    return '%02d:%02d:%02d.%03d' % get_time_parts(time)

def processed_to_ffmpeg_time(time):
    h, m, s, ss = re.split(r'[,\.]', time)
    t = '{}:{}:{}.{}'.format(h, m, s, ss)
    return t

def get_snapshot(video_name, raw_episode, raw_time):
    video_file = '{}.mkv'.format(int(raw_episode))
    video_height = 360
    path = os.path.dirname(__file__) + '/' + str(int(target_episode)) + '/'
    if not os.path.exists(path):
        os.makedirs(path)
    snapshot_filename = path + video_name + '_' + raw_episode + '_' + raw_time + '.jpg'
    snapshot_time = processed_to_ffmpeg_time(raw_time) if adjustment == 0 else add_delay(raw_time) #'00:10:12'
    print('time', snapshot_time)
    cmd = [ffmpeg_executable, "-y", "-ss", snapshot_time, "-i", video_file, "-loglevel", "quiet", "-vf", "scale={}:{}".format(-2, video_height), "-vframes", "1", "-q:v", "2", snapshot_filename]
    print(cmd)
    subprocess.run(cmd)

def main(image_column, testing=False):
    with open('deck.json', encoding='utf-8') as f:
        data = json.load(f)
        notes = data['notes']
        video_name = data['name'].replace(' ', '_')
        total = 0
        for note in notes:
            s = note['fields'][image_column]
            episode = s.split(video_name + "_")[1].split("_")[0]
            if int(episode) == target_episode:
                timestamp = s.split(video_name + "_" + episode + '_')[1].split(".jpg")[0]
                get_snapshot(video_name, episode, timestamp)
                total += 1
                if testing and total > 5:
                    break

main(2)

@mathewthe2
Copy link
Author

mathewthe2 commented Feb 25, 2022

import os
import re
import json

image_column = 2

def sort_deck():
    with open('deck.json', encoding='utf-8') as f:
        data = json.load(f)
        notes = data['notes']
        media_files = data['media_files']
        video_name = data['name'].replace(' ', '_')
        total = 0
        new_notes = []
        episode_map = {}
        for note in notes:
            s = note['fields'][image_column]
            episode = s.split(video_name + "_")[1].split("_")[0]
            if int(episode) not in episode_map:
                episode_map[int(episode)] = [note]
            else:
                 episode_map[int(episode)].append(note)
        i = 1
        while i in episode_map:
            new_notes += episode_map[i]
            i += 1
        data['notes'] = new_notes

    with open('out.json', 'w+', encoding='utf8') as outfile:
        json.dump(data, outfile, indent=4, ensure_ascii=False)

def switch_episode(episode1, episode2):
    with open('deck.json', encoding='utf-8') as f:
        data = json.load(f)
        notes = data['notes']
        media_files = data['media_files']
        video_name = data['name'].replace(' ', '_')
        total = 0
        new_notes = []
        for note in notes:
            s = note['fields'][image_column]
            episode = s.split(video_name + "_")[1].split("_")[0]
            if int(episode) == episode1 or int(episode) == episode2:
                ep = str(episode1) if int(episode) == episode1 else str(episode2)
                ep_target = str(episode2) if int(episode) == episode1 else str(episode1)
                note['fields'][0] = note['fields'][0].replace('0' + ep + '_', '0' + ep_target + '_')
                note['fields'][1] = note['fields'][1].replace('_0' + ep + '_', '_0' + ep_target + '_')
                note['fields'][2] = note['fields'][2].replace('_0' + ep + '_', '_0' + ep_target + '_')

            new_notes.append(note)
        for index, file in enumerate(media_files):
            if ('_0' + str(episode1)) in file or ('_0' + str(episode2)) in file:
                ep = str(episode1) if '_0' + str(episode1) in file else str(episode2)
                ep_target = str(episode2) if '_0' + str(episode1) in file else str(episode1)
                media_files[index] = file.replace('_0' + ep, '_0' + ep_target)
        data['media_files'] = sorted(media_files)
        data['notes'] = new_notes

    with open('out.json', 'w+', encoding='utf8') as outfile:
        json.dump(data, outfile, indent=4, ensure_ascii=False)

def switch_rename_files(episode1, episode2):
    folder = "media"
    for count, filename in enumerate(os.listdir(folder)):
        if ('_0' + str(episode1) + '_') in filename or ('_0' + str(episode2) + '_') in filename:
            print(filename)
            ep = str(episode1) if ('_0' + str(episode1) + '_') in filename else str(episode2)
            ep_target = str(episode2) if ('_0' + str(episode1) + '_') in filename else str(episode1)
            new_file_name = filename.replace('_0' + ep, '_0' + ep_target)
            os.rename(folder + '/' + filename, folder + '/' + new_file_name)


# switch_episode(8, 9)
# sort_deck()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment