#!/usr/bin/env python3 # sortashuffle.py # Shuffles shows but keeps episodes in order. # USAGE # 0. Copy this script to the playlist folder # 1. Modify the TARGET variable below # 2. Modify the SOURCES variable below # 3. Run the script as administrator # # To add/remove shows or regenerate playlist, # delete everything in TARGET (except this script) # and re-run the script. import os import random # Must be in format "C://Dir1//Dir2" TARGET = "" SOURCES = ["", ""] def collect_showlist(sources): """Returns a list of lists. Each sub-list represents a show, and elements represent episodes.""" return [[f for f in os.listdir(source)] for source in sources] def calculate_weights(showlist): """Calculate the weights for each show; # of remaining episodes""" return [len(show) for show in showlist] def select_show(showlist, weightlist): """Select a show, accounting weight.""" return random.choices(range(len(showlist)), weights=weightlist, k=1)[0] def shuffle(showlist, weightlist): """Shuffle the playlist.""" shuffled = [] while any(showlist): selection = select_show(showlist, weightlist, previous) shuffled.append(SOURCES[selection] + "//" + showlist[selection].pop(0)) weightlist[selection] = len(showlist[selection]) return shuffled def deploy_symlinks(shuffled): """Deploy episode symlinks.""" count = 0 for episode in shuffled: os.symlink(episode, TARGET + "//" + str(count)) count += 1 return count def deploy_index(shuffled): """Deploy playlist index.""" index = open(TARGET + "//" + "_PLAYLIST_INDEX.txt", 'w', encoding='utf-8') index.write("\n".join(shuffled)) index.close() return INDEX def main(): SHOWLIST = collect_showlist(SOURCES) WEIGHTLIST = calculate_weights(SHOWLIST) SHUFFLED = shuffle(SHOWLIST, WEIGHTLIST) deploy_symlinks(SHUFFLED) deploy_index(SHUFFLED) return 0 if __name__=="__main__": main()