Move lyrics retrieval to get_watch_playlist (closes #114)

Add get_lyrics to docs
Remove video and browseId from get_lyrics return Dict
This commit is contained in:
sigma67 2020-12-14 14:04:17 +01:00
commit fee86377a8
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
4 changed files with 85 additions and 74 deletions

View file

@ -28,6 +28,7 @@ Browsing
.. automethod:: YTMusic.get_album
.. automethod:: YTMusic.get_song
.. automethod:: YTMusic.get_streaming_data
.. automethod:: YTMusic.get_lyrics
Watch
--------

View file

@ -93,15 +93,15 @@ class TestYTMusic(unittest.TestCase):
self.assertEqual(len(streaming_data), 3)
def test_get_lyrics(self):
lyrics_song = youtube.get_lyrics("ZrOKjDZOtkA")
playlist = youtube.get_watch_playlist("ZrOKjDZOtkA")
lyrics_song = youtube.get_lyrics(playlist["lyrics"])
self.assertTrue(lyrics_song["lyricsFound"])
self.assertIsNotNone(lyrics_song["browseId"])
self.assertIsNotNone(lyrics_song["lyrics"])
self.assertIsNotNone(lyrics_song["source"])
no_lyrics_song = youtube.get_lyrics("9TnpB8WgW4s")
self.assertFalse(lyrics_song["lyricsFound"])
self.assertIsNotNone(no_lyrics_song["browseId"])
playlist = youtube.get_watch_playlist("9TnpB8WgW4s")
no_lyrics_song = youtube.get_lyrics(playlist["lyrics"])
self.assertFalse(no_lyrics_song["lyricsFound"])
self.assertIsNotNone(no_lyrics_song["lyrics"])
self.assertIsNotNone(no_lyrics_song["source"])
@ -111,17 +111,17 @@ class TestYTMusic(unittest.TestCase):
def test_get_watch_playlist(self):
playlist = youtube.get_watch_playlist("4y33h81phKU", limit=50)
self.assertGreater(len(playlist), 50)
self.assertGreater(len(playlist['tracks']), 50)
def test_get_watch_playlist_shuffle(self):
playlist = youtube.get_watch_playlist_shuffle(
playlistId="OLAK5uy_lKgoGvlrWhX0EIPavQUXxyPed8Cj38AWc")
self.assertEqual(len(playlist), 12)
self.assertEqual(len(playlist['tracks']), 12)
def test_get_watch_playlist_shuffle_playlist(self):
playlist = youtube.get_watch_playlist_shuffle(
playlistId="PL528pVfw3ao0x8jlW3kwdIx1FEMMeeghb", limit=99)
self.assertGreaterEqual(len(playlist), 99)
self.assertGreaterEqual(len(playlist['tracks']), 99)
###############
# LIBRARY
@ -136,12 +136,12 @@ class TestYTMusic(unittest.TestCase):
self.assertGreaterEqual(len(songs), 100)
songs = youtube_auth.get_library_songs(200, validate_responses=True)
self.assertGreaterEqual(len(songs), 200)
songs = youtube_auth.get_library_songs(100, order='a_to_z')
self.assertGreaterEqual(len(songs), 100)
songs = youtube_auth.get_library_songs(100, order='z_to_a')
self.assertGreaterEqual(len(songs), 100)
songs = youtube_auth.get_library_songs(100, order='recently_added')
self.assertGreaterEqual(len(songs), 100)
songs = youtube_auth.get_library_songs(order='a_to_z')
self.assertGreaterEqual(len(songs), 25)
songs = youtube_auth.get_library_songs(order='z_to_a')
self.assertGreaterEqual(len(songs), 25)
songs = youtube_auth.get_library_songs(order='recently_added')
self.assertGreaterEqual(len(songs), 25)
def test_get_library_albums(self):
albums = youtube_brand.get_library_albums(100)
@ -156,21 +156,21 @@ class TestYTMusic(unittest.TestCase):
def test_get_library_artists(self):
artists = youtube_brand.get_library_artists(100)
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_artists(100, order='a_to_z')
artists = youtube_brand.get_library_artists(order='a_to_z')
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_artists(100, order='z_to_a')
artists = youtube_brand.get_library_artists(order='z_to_a')
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_artists(100, order='recently_added')
artists = youtube_brand.get_library_artists(order='recently_added')
self.assertGreater(len(artists), 0)
def test_get_library_subscriptions(self):
artists = youtube_brand.get_library_subscriptions(50)
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_subscriptions(50, order='a_to_z')
artists = youtube_brand.get_library_subscriptions(order='a_to_z')
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_subscriptions(50, order='z_to_a')
artists = youtube_brand.get_library_subscriptions(order='z_to_a')
self.assertGreater(len(artists), 0)
artists = youtube_brand.get_library_subscriptions(50, order='recently_added')
artists = youtube_brand.get_library_subscriptions(order='recently_added')
self.assertGreater(len(artists), 0)
def test_get_liked_songs(self):

View file

@ -8,7 +8,11 @@ from ytmusicapi.parsers.playlists import *
class BrowsingMixin:
def search(self, query: str, filter: str = None, limit: int = 20, ignore_spelling: bool = False) -> List[Dict]:
def search(self,
query: str,
filter: str = None,
limit: int = 20,
ignore_spelling: bool = False) -> List[Dict]:
"""
Search YouTube music
Returns results within the provided category.
@ -122,7 +126,7 @@ class BrowsingMixin:
search_results.extend(
get_continuations(res['musicShelfRenderer'], 'musicShelfContinuation',
limit - len(search_results), request_func, parse_func))
limit - len(search_results), request_func, parse_func))
return search_results
@ -520,7 +524,8 @@ class BrowsingMixin:
return text
player_response = json.loads(text['player_response'][0])
song_meta = player_response['videoDetails']
song_meta['category'] = player_response['microformat']['playerMicroformatRenderer']['category']
song_meta['category'] = player_response['microformat']['playerMicroformatRenderer'][
'category']
if song_meta['shortDescription'].endswith("Auto-generated by YouTube."):
try:
description = song_meta['shortDescription'].split('\n\n')
@ -627,7 +632,13 @@ class BrowsingMixin:
"""
endpoint = "https://www.youtube.com/get_video_info"
params = {"video_id": videoId, "hl": self.language, "el": "detailpage", "c": "WEB_REMIX", "cver": "0.1"}
params = {
"video_id": videoId,
"hl": self.language,
"el": "detailpage",
"c": "WEB_REMIX",
"cver": "0.1"
}
response = requests.get(endpoint, params, headers=self.headers, proxies=self.proxies)
text = parse_qs(response.text)
if 'player_response' not in text:
@ -639,45 +650,33 @@ class BrowsingMixin:
return player_response['streamingData']
def get_lyrics(self, videoId: str) -> Dict:
def get_lyrics(self, browseId: str) -> Dict:
"""
Returns lyrics of a song or video.
:param videoId: Video id
:param browseId: Lyrics browse id obtained from `get_watch_playlist`
:return: Dictionary with song lyrics.
Example::
{
"videoId": "ZrOKjDZOtkA",
"browseId": "MPLYt_9nqEki4ZDpp-3",
"lyricsFound": true,
"lyrics": "Today is gonna be the day\nThat they're gonna throw it back to you\nBy now you should've somehow\nRealized what you gotta do\nI don't believe that anybody\nFeels the way I do, about you now\n\nBackbeat, the word was on the street\nThat the fire in your heart is out\nI'm sure you've heard it all before\nBut you never really had a doubt\nI don't believe that anybody\nFeels the way I do about you now\n\nAnd all the roads we have to walk are winding\nAnd all the lights that lead us there are blinding\nThere are many things that I\nWould like to say to you but I don't know how\n\nBecause maybe, you're gonna be the one that saves me\nAnd after all, you're my wonderwall\n\nToday was gonna be the day\nBut they'll never throw it back to you\nBy now you should've somehow\nRealized what you're not to do\nI don't believe that anybody\nFeels the way I do, about you now\n\nAnd all the roads that lead you there are winding\nAnd all the lights that light the way are blinding\nThere are many things that I\nWould like to say to you but I don't know how\n\nI said maybe, you're gonna be the one that saves me\nAnd after all, you're my wonderwall\n\nI said maybe, you're gonna be the one that saves me\nAnd after all, you're my wonderwall\n\nI said maybe, you're gonna be the one that saves me\nyou're gonna be the one that saves me\nyou're gonna be the one that saves me"
"lyricsFound": True,
"lyrics": "Today is gonna be the day\\nThat they're gonna throw it back to you\\n",
"source": "Source: LyricFind"
}
"""
body = {
'videoId': videoId,
'browseId': None,
'lyricsFound': None,
'lyrics': None,
'source': None,
}
browseIdResponse = self._send_request('next', body)
for tab in browseIdResponse['contents']['singleColumnMusicWatchNextResultsRenderer']['tabbedRenderer']['watchNextTabbedResultsRenderer']['tabs']:
if tab['tabRenderer']['title'] == 'Lyrics':
body['browseId'] = tab['tabRenderer']['endpoint']['browseEndpoint']['browseId']
break
if body['browseId'] != None:
response = self._send_request('browse', body)
if 'sectionListRenderer' in response['contents'].keys():
body['lyricsFound'] = True
body['lyrics'] = response['contents']['sectionListRenderer']['contents'][0]['musicDescriptionShelfRenderer']['description']['runs'][0]['text']
body['source'] = response['contents']['sectionListRenderer']['contents'][0]['musicDescriptionShelfRenderer']['footer']['runs'][0]['text']
else:
body['lyricsFound'] = False
body['lyrics'] = response['contents']['messageRenderer']['subtext']['messageSubtextRenderer']['text']['runs'][0]['text']
body['source'] = response['contents']['messageRenderer']['text']['runs'][0]['text']
body.pop('context', None)
return body
lyrics = {}
response = self._send_request('browse', {'browseId': browseId})
if 'sectionListRenderer' in response['contents'].keys():
lyrics['lyricsFound'] = True
lyrics['lyrics'] = response['contents']['sectionListRenderer']['contents'][0][
'musicDescriptionShelfRenderer']['description']['runs'][0]['text']
lyrics['source'] = response['contents']['sectionListRenderer']['contents'][0][
'musicDescriptionShelfRenderer']['footer']['runs'][0]['text']
else:
lyrics['lyricsFound'] = False
lyrics['lyrics'] = response['contents']['messageRenderer']['subtext'][
'messageSubtextRenderer']['text']['runs'][0]['text']
lyrics['source'] = response['contents']['messageRenderer']['text']['runs'][0]['text']
return lyrics

View file

@ -7,7 +7,7 @@ class WatchMixin:
videoId: str = None,
playlistId: str = None,
limit=25,
params: str = None) -> List[Dict]:
params: str = None) -> Dict[List[Dict], str]:
"""
Get a watch list of tracks. This watch playlist appears when you press
play on a track in YouTube Music.
@ -20,22 +20,25 @@ class WatchMixin:
Example::
[
{
"title": "Interstellar (Main Theme) - Piano Version",
"byline": "Patrik Pietschmann • 47M views",
"length": "4:47",
"videoId": "4y33h81phKU",
"playlistId": "RDAMVM4y33h81phKU",
"thumbnail": [
{
"tracks": [
{
"url": "https://i.ytimg.com/vi/4y...",
"width": 400,
"height": 225
}
]
},...
]
"title": "Interstellar (Main Theme) - Piano Version",
"byline": "Patrik Pietschmann • 47M views",
"length": "4:47",
"videoId": "4y33h81phKU",
"playlistId": "RDAMVM4y33h81phKU",
"thumbnail": [
{
"url": "https://i.ytimg.com/vi/4y...",
"width": 400,
"height": 225
}
]
},...
],
"lyrics": "MPLYt_HNNclO0Ddoc-17"
}
"""
body = {'enablePersistentPlaylistPanel': True, 'isAudioOnly': True}
@ -55,10 +58,18 @@ class WatchMixin:
body['params'] = params
endpoint = 'next'
response = self._send_request(endpoint, body)
results = nav(response, [
watchNextRenderer = nav(response, [
'contents', 'singleColumnMusicWatchNextResultsRenderer', 'tabbedRenderer',
'watchNextTabbedResultsRenderer'
] + TAB_CONTENT + ['musicQueueRenderer', 'content', 'playlistPanelRenderer'])
])
lyrics_browse_id = None
if len(watchNextRenderer['tabs']) > 1:
lyrics_browse_id = watchNextRenderer['tabs'][1]['tabRenderer']['endpoint'][
'browseEndpoint']['browseId']
results = nav(watchNextRenderer,
TAB_CONTENT + ['musicQueueRenderer', 'content', 'playlistPanelRenderer'])
tracks = parse_watch_playlist(results['contents'])
if 'continuations' in results:
@ -69,9 +80,9 @@ class WatchMixin:
get_continuations(results, 'playlistPanelContinuation', limit - len(tracks),
request_func, parse_func, '' if is_playlist else 'Radio'))
return tracks
return {'tracks': tracks, 'lyrics': lyrics_browse_id}
def get_watch_playlist_shuffle(self, playlistId: str = None, limit=50) -> List[Dict]:
def get_watch_playlist_shuffle(self, playlistId: str = None, limit=50) -> Dict[List[Dict], str]:
"""
Shuffle any playlist