text: from ytmusicapi import YTMusic
  import json
  import random
  import sys
  import getopt
  
  air1songs = {}
  
  
  def load(filename='songcache.json'):
      try:
          with open(filename, 'r') as fp:
              return json.load(fp)
      except json.decoder.JSONDecodeError:
          return {}
  
  def save(data, filename='songcache.json'):
      with open('songcache.json', 'w') as fp:
          json.dump(data, fp)
  
  def main(argv):
      playlistName = 'Worship 2021'
      headerfile = 'headers_auth.json'
      onlyunique = False
      songsfile = 'air1songlist.json'
      cachefile = 'songcache.json'
      filterFrom = 0
      divby = 1
      init = False
      try:
          opts, args = getopt.getopt(argv, "hius:c:l:r:f:d", ["help", "init", "onlyunique", "songsfile=", "cachefile=", "listname=", "headerfile=", "filterfrom=", "divby="])
      except getopt.GetoptError:
          print('upload.py Invaild option: see --help for usage')
          sys.exit(2)
      for opt, arg in opts:
          if opt in ('-h', "--help"):
              print('upload.py usage:')
              print('  -h for help')
              print('  -i or --init to paste the header content')
              print('  -u or --onlyunique to only add unique songs')
              print('  -s or --songsfile= the path to the file generated by the scrapper')
              print('  -c or --cachefile= the path to the file where to cache the song ids')
              print('  -l or --listname= the name of the playlist')
              print('  -r or --headerfile= the path to the credentials (or where to put them if running with --init)')
              print('  -f or --filterfrom= only keep items that have been played after it (the format is milliseconds from unix epoch (the JS date number))')
              print('  -d or --divby= divide all the counts by it and round the answer (sets zero to one)')
              sys.exit()
          elif opt in ("-u", "--onlyunique"):
              onlyunique = True
          elif opt in ("-s", "--songsfile"):
              songsfile = arg
          elif opt in ("-c", "--cachefile"):
              cachefile = arg
          elif opt in ("-l", "--listname"):
              playlistName = arg
          elif opt in ("-r", "--headerfile"):
              headerfile = arg
          elif opt in ("-i", "--init"):
              init = True
          elif opt in ("-f", "--filterfrom"):
              try:
                  filterFrom = int(arg.strip())
              except ValueError:
                  print('upload.py Invaild option: \'--filterfrom\' see --help for usage')
                  sys.exit(2)
          elif opt in ("-d", "--divby"):
              try:
                  print(arg.strip())
                  divby = int(arg.strip())
              except ValueError:
                  print('upload.py Invaild option: \'--divby\' see --help for usage')
                  sys.exit(2)
      if init:
          YTMusic.setup(headerfile)
      else:
          ytmusic = YTMusic(headerfile)
          playlists = ytmusic.get_library_playlists(25)
  
          playlistId = None
          playlist = None
  
          for item in playlists:
              if item['title'] == playlistName:
                  playlistId = item['playlistId']
                  playlist = ytmusic.get_playlist(playlistId, limit=2000)
  
          if playlistId is None:
              playlistId = ytmusic.create_playlist(playlistName, "")
          elif len(playlist['tracks']) > 0:
              ytmusic.remove_playlist_items(playlistId, playlist['tracks'])
  
          # oldestTime = 1614712800000
  
          cache = load(cachefile)
          air1songs = load(songsfile)
  
          songsToAdd = []
  
          for song in air1songs['songs']:
              recentPlayedAts = [x for x in song['playedAt'] if x > filterFrom]
              query = song['name'] + " by " + song['artist']
              query = query.replace('&amp;', '&')
  
              item = None
              if query in cache:
                  item = cache[query]
              else:
                  search_results = ytmusic.search(query)
                  try:
                      cache[query] = search_results[0]['videoId']
                  except KeyError:
                      try:
                          cache[query] = search_results[1]['videoId']
                      except KeyError:
                          cache[query] = "none existent"
                  item = cache[query]
              if item != "none existent":
                  print('Adding song', song['name'], len(recentPlayedAts), 'times')
                  if not onlyunique:
                      count = max(round(len(recentPlayedAts) / divby), 1)
                      for time in range(count):
                          songsToAdd.append(item)
                          # print(time)
                  else:
                      songsToAdd.append(item)
              else:
                  print('Can not find', song['name'], 'by', song['artist'])
  
  
          save(cache, cachefile)
  
          random.shuffle(songsToAdd)
  
          ytmusic.add_playlist_items(
              playlistId, songsToAdd, duplicates=True)
  
  
  
  
  if __name__ == "__main__":
      main(sys.argv[1:])
  