Proper runtime, docs, etc..
This commit is contained in:
parent
aad6fdf150
commit
ee70fb296e
7 changed files with 396 additions and 81 deletions
24
LICENSE.md
Normal file
24
LICENSE.md
Normal file
|
|
@ -0,0 +1,24 @@
|
||||||
|
# The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright © `2025` `Jose Stovall`
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person
|
||||||
|
obtaining a copy of this software and associated documentation
|
||||||
|
files (the “Software”), to deal in the Software without
|
||||||
|
restriction, including without limitation the rights to use,
|
||||||
|
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the
|
||||||
|
Software is furnished to do so, subject to the following
|
||||||
|
conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be
|
||||||
|
included in all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||||
|
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||||
|
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||||
|
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||||
|
OTHER DEALINGS IN THE SOFTWARE.
|
||||||
33
README.md
Normal file
33
README.md
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
# YTMusic to Spotify Migrator
|
||||||
|
|
||||||
|
This is an Free and Fully Open-Source piece of software that allows you to collect a list of all Songs (Name, Artist(s) and Album) from your YouTube Music library. In addition, you can also add any list of songs -- though it's expected they'll come from this tool -- to your Spotify Saved Music playlist!
|
||||||
|
|
||||||
|
## Running:
|
||||||
|
|
||||||
|
Run all python files as a module, i.e. `python -m src.spotify` or `python -m src.ytmusic`. This is because of relative import oddness, and is generally better practice. Both modules have a `-h` flag you can provide for help on the optional and required parameters. See the Environment Variables section below for info that you'll need to actually succeed:
|
||||||
|
|
||||||
|
## Environment Variables:
|
||||||
|
|
||||||
|
### Google Cloud SDK
|
||||||
|
|
||||||
|
Both **`GOOGLE_CLIENT_ID`** and **`GOOGLE_CLIENT_SECRET`** are required as per the original YTMusic documentation found [here](https://ytmusicapi.readthedocs.io/en/stable/setup/oauth.html)
|
||||||
|
|
||||||
|
### Spotify SDK
|
||||||
|
|
||||||
|
This project uses Spotipy, as such you'll need **`SPOTIPY_CLIENT_ID`**, **`SPOTIPY_CLIENT_SECRET`** and **`SPOTIPY_REDIRECT_URI`** to be defined in your environment.
|
||||||
|
|
||||||
|
To get these values, start by creating an App on the [Spotify Developers Dashboard](https://developer.spotify.com/dashboard).
|
||||||
|
|
||||||
|
When asked for a _Redirect URI_, use `http://127.0.0.1:9000` as the value. **Set `SPOTIPY_REDIRECT_URI` to this same value**.
|
||||||
|
|
||||||
|
The other two values will be provided to you in the dashboard.
|
||||||
|
|
||||||
|
### YouTube Music
|
||||||
|
|
||||||
|
This is the entrypoint of this program, since it's assumed you're going from YTMusic -> Spotify, so you'll have to get the
|
||||||
|
|
||||||
|
Since there's a bug in the YTMusic API (as there is no public facing one...), the best route is to get the COOKIES and Authorization headers from your browser after going to https://music.youtube.com and browsing. Most requests to the `/browse` endpoint will have what you need, and they'll need to be set as environment variable through whatever means you prever. See the `.envrc.example` file for an idea of what things you'll need. The environment variables are:
|
||||||
|
|
||||||
|
**`YT_MUSIC_AUTH`**: This can be found in the Request Header, as mentioned. The key in the Request Header should be `Authorization`, and it will have a pattern somewhat like this: `SAPISIDHASH 0123456789_0123456789ABCDEF000000000000000000000000_u SAPISID1PHASH 0123456789_0123456789ABCDEF000000000000000000000000_u SAPISID3PHASH 0123456789_0123456789ABCDEF000000000000000000000000_u`
|
||||||
|
|
||||||
|
**`YT_MUSIC_COOKIE`**: This can also be found in the Request Header. The key in the Request Header should be `Cookie`, and it will have a pattern that _starts_ out like this, but it's a very long string value: `Cookie: VISITOR_INFO1_LIVE=xxxxxxxxxxx; VISITOR_PRIVACY_METADATA=xxxxxxxxxxxxxx%3D%3D; ...`
|
||||||
|
|
@ -1,2 +1,2 @@
|
||||||
spotipy==2.25.1
|
spotipy==2.25.1
|
||||||
ytmusicapi @ git+https://github.com/Goldenfreddy0703/ytmusicapi.git@43971eb7d5609eef0ca0cc0350f44d645eb9242f
|
ytmusicapi @ git+https://git.oitsjustjose.com/oitsjustjose/ytmusicapi.git@99d8ee53ad2e205262c195ab84250943036a8f21
|
||||||
|
|
|
||||||
117
src/__init__.py
117
src/__init__.py
|
|
@ -1,5 +1,47 @@
|
||||||
|
"""
|
||||||
|
@author: Jose Stovall | stovallj1995@gmail.com | github.com/oitsjustjose | git.oitsjustjose.com/oitsjustjose
|
||||||
|
Miscellanious common utilities / classes / etc.
|
||||||
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Union, List
|
from pathlib import Path
|
||||||
|
from typing import Any, Callable, List, Union
|
||||||
|
|
||||||
|
__UNK = "Unknown"
|
||||||
|
|
||||||
|
|
||||||
|
def ask(prompt: str) -> bool:
|
||||||
|
"""Asks the user a question, returning True if the response starts with 'y', False otherwise
|
||||||
|
|
||||||
|
Args:
|
||||||
|
prompt (str): The question to ask the user
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the response starts with 'y', False otherwise
|
||||||
|
"""
|
||||||
|
print(prompt)
|
||||||
|
inp = input("> [y/n]: ").lower()
|
||||||
|
return inp.startswith("y")
|
||||||
|
|
||||||
|
|
||||||
|
class Logger:
|
||||||
|
def __init__(self, output_path: Union[str, None] = None):
|
||||||
|
self.__handler: Callable = self.__get_handler(output_path)
|
||||||
|
|
||||||
|
def __get_handler(self, output_path: Union[str, None]) -> Callable:
|
||||||
|
if not output_path:
|
||||||
|
return print
|
||||||
|
|
||||||
|
write_path = Path.cwd().joinpath(output_path).resolve()
|
||||||
|
if write_path.exists():
|
||||||
|
print(f"⚠️ Warning: write path {write_path} already exists. It will be overwritten.")
|
||||||
|
write_path.unlink()
|
||||||
|
|
||||||
|
self._fh = open(write_path, "w", encoding="utf-8")
|
||||||
|
return self._fh.write
|
||||||
|
|
||||||
|
def write(self, obj: Any) -> None:
|
||||||
|
self.__handler(obj)
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|
@ -7,3 +49,76 @@ class Song:
|
||||||
name: str
|
name: str
|
||||||
artist: Union[str, List[str]]
|
artist: Union[str, List[str]]
|
||||||
album: str
|
album: str
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def deserialize(obj: dict): # Can't do a return-type since Song isn't defined in this scope yet
|
||||||
|
"""
|
||||||
|
Deserializes an Dictionary representation of a song into a Song instance
|
||||||
|
Args:
|
||||||
|
obj (dict): The Dictionary representation of this Song
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Song: The song parsed from the data in the dictionary
|
||||||
|
"""
|
||||||
|
if isinstance(obj["album"], dict):
|
||||||
|
album = obj["album"]["name"]
|
||||||
|
else:
|
||||||
|
album = obj["album"]
|
||||||
|
return Song(name=obj["title"], album=album, artist=obj["artist"])
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_ytmusic(obj: dict): # Can't do a return-type since Song isn't defined in this scope yet
|
||||||
|
"""Converts a single raw track from the YTMusic API into our dataclass form
|
||||||
|
Performs parsing and fallback logic to use "Unknown" for any unparsed /
|
||||||
|
empty fields
|
||||||
|
|
||||||
|
Args:
|
||||||
|
raw (dict): The dictionary object for the individual track
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Song: A Song dataclass instance with the fields parsed properly
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __get_field_safe(field: str) -> str:
|
||||||
|
"""Gets a field from the raw dictionary object, returning "Unknown" if
|
||||||
|
the field isn't found in the object or if the field exists but is None
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (str): The field to lookup and validate
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: The field or "Unknown" as a fallback
|
||||||
|
"""
|
||||||
|
if field not in obj:
|
||||||
|
return __UNK
|
||||||
|
return obj[field] or __UNK
|
||||||
|
|
||||||
|
def __get_artists_safe(field: str) -> Union[List[str], str]:
|
||||||
|
"""Parses the artists in a relatively safe way, slightly different process
|
||||||
|
than that of the other two fields because a track may have multiple
|
||||||
|
artists and we want to parse that. If there are multiple, a list of
|
||||||
|
strings are returned, otherwise just a string is returned.
|
||||||
|
|
||||||
|
Like the standard safe field lookup, will return "Unknown" if the field
|
||||||
|
doesn't exist in the object or if the field exists but is None
|
||||||
|
|
||||||
|
Args:
|
||||||
|
field (str): The field to lookup and validate
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Union[List[str], str]:
|
||||||
|
- List[str] if multiple artists are present
|
||||||
|
- str if only a single artist is present, or if the field cannot be found
|
||||||
|
or the field is None (in which case "Unknown" is returned)
|
||||||
|
"""
|
||||||
|
if field not in obj:
|
||||||
|
return __UNK
|
||||||
|
if not obj[field]:
|
||||||
|
return __UNK
|
||||||
|
val = [x["name"] for x in obj[field]]
|
||||||
|
return val[0] if len(val) == 1 else val
|
||||||
|
|
||||||
|
title = __get_field_safe("title")
|
||||||
|
artists = __get_artists_safe("artists")
|
||||||
|
album = __get_field_safe("album")
|
||||||
|
return Song(title, artists, album)
|
||||||
|
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
from src.ytmusic import get_all_songs_from_library
|
|
||||||
import json
|
|
||||||
|
|
||||||
all_songs = get_all_songs_from_library()
|
|
||||||
with open("out.json", "w") as fh:
|
|
||||||
fh.write(json.dumps([{"title": x.name, "album": x.album, "artist": x.artist} for x in all_songs], indent=2))
|
|
||||||
168
src/spotify.py
168
src/spotify.py
|
|
@ -1,19 +1,167 @@
|
||||||
|
"""
|
||||||
|
@author: Jose Stovall | stovallj1995@gmail.com | github.com/oitsjustjose | git.oitsjustjose.com/oitsjustjose
|
||||||
|
A program for adding songs saved from, realistically any, library to your Spotify Saved Songs list
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from os import environ, get_terminal_size
|
||||||
|
from typing import Any, List, Union
|
||||||
|
|
||||||
from spotipy import Spotify
|
from spotipy import Spotify
|
||||||
from spotipy.oauth2 import SpotifyClientCredentials
|
from spotipy.oauth2 import SpotifyOAuth
|
||||||
from typing import List, Union
|
|
||||||
|
from src import Logger, Song, ask
|
||||||
|
|
||||||
|
|
||||||
_INSTANCE: Union[Spotify, None]
|
def __warn(songs: List[Song], user: dict) -> bool:
|
||||||
|
term_size = get_terminal_size()
|
||||||
|
print("#" * term_size.columns)
|
||||||
|
print(f"Warning: You are about to add {len(songs)} songs to {user['display_name']}'s account. Proceed?")
|
||||||
|
print("#" * term_size.columns)
|
||||||
|
return ask("Proceed?")
|
||||||
|
|
||||||
|
|
||||||
def get_instance():
|
def __query_str(song) -> List[str]:
|
||||||
global _INSTANCE
|
"""Creates the godforsaken Query String format that Spotify requires
|
||||||
|
(https://developer.spotify.com/documentation/web-api/reference/search)
|
||||||
|
in order to search for a song with the provided params. If the Song
|
||||||
|
has multiple artists, then multiple queries are produced: 1 query of
|
||||||
|
the same album and song, but for each artist in the list (with just
|
||||||
|
the one artist), and another with all artists concatenated with a ', '
|
||||||
|
|
||||||
if not _INSTANCE:
|
Args:
|
||||||
auth_manager = SpotifyClientCredentials()
|
song (Song): the song to create multiple
|
||||||
_INSTANCE = Spotify(auth_manager=auth_manager)
|
|
||||||
|
|
||||||
return _INSTANCE
|
Returns:
|
||||||
|
List[str]: A list of the Query Strings generated as described above
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Don't query for the album if we don't know what it is
|
||||||
|
album_q = "" if song.album == "Unknown" else f"album:{song.album}"
|
||||||
|
# If there's only one artist, then joining will do nothing, leaving it as a single string.
|
||||||
|
# If there are multiple we still want to join all of them together as a query option
|
||||||
|
artists_to_use = [", ".join(song.artist)]
|
||||||
|
if isinstance(song.artist, list):
|
||||||
|
for artist in song.artist:
|
||||||
|
artists_to_use.append(artist)
|
||||||
|
|
||||||
|
return [f"track:{song.name} artist:{x} {album_q}".strip() for x in artists_to_use]
|
||||||
|
|
||||||
|
|
||||||
get_instance().user
|
def __search(song: Song, sp: Spotify) -> List[str]:
|
||||||
|
"""Attempts to find a song using the provided information
|
||||||
|
If none can be found, None is returned.
|
||||||
|
|
||||||
|
If multiple are found, all are added and logging is provided to clarify
|
||||||
|
that there was ... an issue.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
song (Song): The song to use as a search parameter
|
||||||
|
sp (Spotify): The current Spotipy instance
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Union[str | None]: The Spotify Song ID to be added straight into the library,
|
||||||
|
or None if no song is found with the given parameters in Spotify's lib
|
||||||
|
"""
|
||||||
|
# Search every possible query permutation we generate
|
||||||
|
results = [sp.search(x) for x in __query_str(song)]
|
||||||
|
# The list above can return None or Any, so remove all None from the list:
|
||||||
|
results: List[Any] = list(filter(lambda x: x, results))
|
||||||
|
# We only want the .tracks.items sub-object from each result, so select just that:
|
||||||
|
results = list(map(lambda x: x["tracks"]["items"], results))
|
||||||
|
# The above result will leave you with a 2D array, so let's flatten that for ease of use:
|
||||||
|
results = [y for x in results for y in x]
|
||||||
|
# Finally, all we _really_ need is item.uri for item in .tracks.items:
|
||||||
|
results = [x["uri"] for x in results]
|
||||||
|
# Lastly, cast to set then back to list to deduplicate the URIs:
|
||||||
|
return list(set(results))
|
||||||
|
|
||||||
|
|
||||||
|
def process(songs: List[Song], output: Union[str, None] = None):
|
||||||
|
"""For each song in the list of provided songs:
|
||||||
|
1. Attempts to find the song in Spotify's Library,
|
||||||
|
logging if it can't or if multiple are found
|
||||||
|
2. Adds the song(s) to the OAuth User's Saved Tracks
|
||||||
|
|
||||||
|
Args:
|
||||||
|
songs (List[Song]): A list of songs brought over from some other platform.
|
||||||
|
output (str | None): The path to write out logs to (Optional)
|
||||||
|
"""
|
||||||
|
|
||||||
|
if output:
|
||||||
|
print(f"ℹ️ stdout will now be written to {output} until the end of program execution")
|
||||||
|
logger = Logger(output_path=output)
|
||||||
|
|
||||||
|
client_id = environ.get("SPOTIPY_CLIENT_ID", "")
|
||||||
|
if not client_id:
|
||||||
|
raise Exception("SPOTIPY_CLIENT_ID environment variable cannot be empty!")
|
||||||
|
|
||||||
|
client_secret = environ.get("SPOTIPY_CLIENT_SECRET", "")
|
||||||
|
if not client_secret:
|
||||||
|
raise Exception("SPOTIPY_CLIENT_SECRET environment variable cannot be empty!")
|
||||||
|
|
||||||
|
redirect_uri = environ.get("SPOTIPY_REDIRECT_URI", "")
|
||||||
|
if not redirect_uri:
|
||||||
|
raise Exception("SPOTIPY_REDIRECT_URI environment variable cannot be empty!")
|
||||||
|
|
||||||
|
sp = Spotify(
|
||||||
|
auth_manager=SpotifyOAuth(
|
||||||
|
client_id=client_id,
|
||||||
|
client_secret=client_secret,
|
||||||
|
redirect_uri=redirect_uri,
|
||||||
|
scope="user-library-modify",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
user = sp.current_user() # Called to initiate the OAuth callback
|
||||||
|
if not user:
|
||||||
|
logger.write("Failed to log in! Aborting")
|
||||||
|
return
|
||||||
|
|
||||||
|
if not __warn(songs, user):
|
||||||
|
return
|
||||||
|
|
||||||
|
for song in songs:
|
||||||
|
results = __search(song, sp)
|
||||||
|
if not results:
|
||||||
|
logger.write(f"🚨 Failed to find any match for {song.name} by {song.artist} (Album: {song.album})")
|
||||||
|
continue
|
||||||
|
|
||||||
|
if len(results) > 1:
|
||||||
|
logger.write(f"⚠️ FYI we found {len(results)} results for {song.name} by {song.artist} (Album: {song.album})")
|
||||||
|
|
||||||
|
sp.current_user_saved_tracks_add(results)
|
||||||
|
|
||||||
|
|
||||||
|
def __main__(songs_file: str, output: Union[str, None]) -> None:
|
||||||
|
"""Parses the songs from the provided input file before doing the standard call to `process`
|
||||||
|
|
||||||
|
Args:
|
||||||
|
songs_file (str): The path to the list of Songs as exported by the YTMusic script
|
||||||
|
output (str | None): The path to write out logs to (Optional)
|
||||||
|
"""
|
||||||
|
with open(songs_file, "r", encoding="utf-8") as fh:
|
||||||
|
data = json.loads(fh.read())
|
||||||
|
|
||||||
|
songs = list(map(lambda x: Song.deserialize(x), data))
|
||||||
|
process(songs, output)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser("Spotify track uploader from YouTube Music")
|
||||||
|
parser.add_argument(
|
||||||
|
"-i",
|
||||||
|
"--input",
|
||||||
|
help="The location of the .json file containing all songs exported from your YouTube Music Library",
|
||||||
|
required=True,
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-o",
|
||||||
|
"--output",
|
||||||
|
description="The location to write out logs from this script. If not provided, logs will be written to STDOUT",
|
||||||
|
required=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
__main__(args.input, args.output)
|
||||||
|
|
|
||||||
127
src/ytmusic.py
127
src/ytmusic.py
|
|
@ -1,12 +1,20 @@
|
||||||
|
"""
|
||||||
|
@author: Jose Stovall | stovallj1995@gmail.com | github.com/oitsjustjose | git.oitsjustjose.com/oitsjustjose
|
||||||
|
Entrypoint for the entire flow of this project, since this is the *source* of the music tracks to grab.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
from os import environ
|
from os import environ
|
||||||
from typing import List, Union
|
from typing import List, Union
|
||||||
|
|
||||||
from ytmusicapi import OAuthCredentials, YTMusic
|
from ytmusicapi import OAuthCredentials, YTMusic
|
||||||
|
|
||||||
from src import Song
|
from src import Song, ask
|
||||||
|
from src.spotify import process as AddToSpotify
|
||||||
|
|
||||||
_INSTANCE: Union[YTMusic, None] = None
|
_INSTANCE: Union[YTMusic, None] = None
|
||||||
UNK = "Unknown"
|
|
||||||
|
|
||||||
|
|
||||||
def get_instance() -> YTMusic:
|
def get_instance() -> YTMusic:
|
||||||
|
|
@ -30,70 +38,16 @@ def get_instance() -> YTMusic:
|
||||||
|
|
||||||
if not _INSTANCE:
|
if not _INSTANCE:
|
||||||
_INSTANCE = YTMusic(
|
_INSTANCE = YTMusic(
|
||||||
"oauth.json", # TODO: Get abspath?
|
"oauth.json",
|
||||||
oauth_credentials=OAuthCredentials(client_id=client_id, client_secret=client_secret),
|
oauth_credentials=OAuthCredentials(
|
||||||
|
client_id=client_id,
|
||||||
|
client_secret=client_secret,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
return _INSTANCE
|
return _INSTANCE
|
||||||
|
|
||||||
|
|
||||||
def to_song(raw: dict) -> Song:
|
|
||||||
"""Converts a single raw track from the YTMusic API into our dataclass form
|
|
||||||
Performs parsing and fallback logic to use "Unknown" for any unparsed /
|
|
||||||
empty fields
|
|
||||||
|
|
||||||
Args:
|
|
||||||
raw (dict): The dictionary object for the individual track
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Song: A Song dataclass instance with the fields parsed properly
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __get_field_safe(field: str) -> str:
|
|
||||||
"""Gets a field from the raw dictionary object, returning "Unknown" if
|
|
||||||
the field isn't found in the object or if the field exists but is None
|
|
||||||
|
|
||||||
Args:
|
|
||||||
field (str): The field to lookup and validate
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
str: The field or "Unknown" as a fallback
|
|
||||||
"""
|
|
||||||
if field not in raw:
|
|
||||||
return UNK
|
|
||||||
return raw[field] or UNK
|
|
||||||
|
|
||||||
def __get_artists_safe(field: str) -> Union[List[str], str]:
|
|
||||||
"""Parses the artists in a relatively safe way, slightly different process
|
|
||||||
than that of the other two fields because a track may have multiple
|
|
||||||
artists and we want to parse that. If there are multiple, a list of
|
|
||||||
strings are returned, otherwise just a string is returned.
|
|
||||||
|
|
||||||
Like the standard safe field lookup, will return "Unknown" if the field
|
|
||||||
doesn't exist in the object or if the field exists but is None
|
|
||||||
|
|
||||||
Args:
|
|
||||||
field (str): The field to lookup and validate
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Union[List[str], str]:
|
|
||||||
- List[str] if multiple artists are present
|
|
||||||
- str if only a single artist is present, or if the field cannot be found
|
|
||||||
or the field is None (in which case "Unknown" is returned)
|
|
||||||
"""
|
|
||||||
if field not in raw:
|
|
||||||
return UNK
|
|
||||||
if not raw[field]:
|
|
||||||
return UNK
|
|
||||||
val = [x["name"] for x in raw[field]]
|
|
||||||
return val[0] if len(val) == 1 else val
|
|
||||||
|
|
||||||
title = __get_field_safe("title")
|
|
||||||
artists = __get_artists_safe("artists")
|
|
||||||
album = __get_field_safe("album")
|
|
||||||
return Song(title, artists, album)
|
|
||||||
|
|
||||||
|
|
||||||
def get_all_songs_from_library() -> List[Song]:
|
def get_all_songs_from_library() -> List[Song]:
|
||||||
"""Gets all songs from the Liked Songs 'playlist' in YTMusic for the
|
"""Gets all songs from the Liked Songs 'playlist' in YTMusic for the
|
||||||
currently authed user.
|
currently authed user.
|
||||||
|
|
@ -118,7 +72,54 @@ def get_all_songs_from_library() -> List[Song]:
|
||||||
ytmusic.headers["Cookie"] = cookie
|
ytmusic.headers["Cookie"] = cookie
|
||||||
ytmusic.headers["authorization"] = auth
|
ytmusic.headers["authorization"] = auth
|
||||||
|
|
||||||
songs = ytmusic.get_liked_songs(limit=None) # type: ignore -- limit=None works and gets _all_ songs, and there's no pagination method
|
songs = ytmusic.get_liked_songs(limit=None) # type: ignore -- limit=None works and gets _all_ songs, and there's no pagination method implemented
|
||||||
songs = songs["tracks"]
|
songs = songs["tracks"]
|
||||||
|
|
||||||
return [to_song(x) for x in songs]
|
return [Song.from_ytmusic(x) for x in songs]
|
||||||
|
|
||||||
|
|
||||||
|
def main(songs_output: Union[str, None], output: Union[str, None]) -> None:
|
||||||
|
"""Grabs all songs from YouTube Music, and either writes them out to
|
||||||
|
the path described (songs_output) or directly uploads them to Spotify
|
||||||
|
|
||||||
|
Args:
|
||||||
|
songs_output (Union[str, None]): Where to write the songs to. If not provided,
|
||||||
|
songs are uploaded directly to spotify
|
||||||
|
output (Union[str, None]): _description_
|
||||||
|
"""
|
||||||
|
all_songs = get_all_songs_from_library()
|
||||||
|
|
||||||
|
if not songs_output:
|
||||||
|
AddToSpotify(all_songs, output)
|
||||||
|
return
|
||||||
|
|
||||||
|
write_path = Path.cwd().joinpath(songs_output).resolve()
|
||||||
|
if write_path.exists():
|
||||||
|
if not ask(f"⚠️ Warning: song path {write_path} already exists. Overwrite?"):
|
||||||
|
return
|
||||||
|
|
||||||
|
write_path.unlink()
|
||||||
|
|
||||||
|
with open(write_path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(json.dumps(all_songs, indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser("YouTube Music song list scraper")
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-o",
|
||||||
|
"--output",
|
||||||
|
description="The location to write out logs from this script. If not provided, logs will be written to STDOUT",
|
||||||
|
required=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-s",
|
||||||
|
"--song-output",
|
||||||
|
description="Where to write out the list of songs. If not provided, skips straight to uploading to Spotify (see Spotify.py)",
|
||||||
|
required=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
main(args.song_output, args.output)
|
||||||
Loading…
Reference in a new issue