Feature: support additional languages (closes #29)

de,es,fr,it,jp are supported for now, pull requests for additional languages are welcome!
This commit is contained in:
sigma67 2020-07-09 18:19:09 +02:00
commit 76453bb155
No known key found for this signature in database
GPG key ID: 1545A01D4474BAF0
21 changed files with 549 additions and 70 deletions

View file

@ -3,6 +3,7 @@
max-line-length = 99 max-line-length = 99
select = C,E,F,W,B,B950 select = C,E,F,W,B,B950
ignore = E203, E266, E731, E501, W503, F401, F403, F405 ignore = E203, E266, E731, E501, W503, F401, F403, F405
builtins = _
exclude = exclude =
.git .git
.github .github

View file

@ -1,2 +1,3 @@
include README.md include README.md
recursive-include ytmusicapi/locales *.mo
include ytmusicapi/*.json include ytmusicapi/*.json

View file

@ -7,7 +7,7 @@ from ytmusicapi.ytmusic import YTMusic # noqa: E402
config = configparser.RawConfigParser() config = configparser.RawConfigParser()
config.read('./test.cfg', 'utf-8') config.read('./test.cfg', 'utf-8')
youtube = YTMusic() youtube = YTMusic(language='de')
youtube_auth = YTMusic(config['auth']['headers_file']) youtube_auth = YTMusic(config['auth']['headers_file'])
youtube_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account']) youtube_brand = YTMusic(config['auth']['headers'], config['auth']['brand_account'])
@ -99,8 +99,7 @@ class TestYTMusic(unittest.TestCase):
self.assertIn('actions', response) self.assertIn('actions', response)
def test_rate_playlist(self): def test_rate_playlist(self):
response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', 'LIKE')
'LIKE')
self.assertIn('actions', response) self.assertIn('actions', response)
response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4', response = youtube_auth.rate_playlist('OLAK5uy_l3g4WcHZsEx_QuEDZzWEiyFzZl6pL0xZ4',
'INDIFFERENT') 'INDIFFERENT')
@ -177,6 +176,7 @@ class TestYTMusic(unittest.TestCase):
response = youtube_auth.upload_song(config['uploads']['file']) response = youtube_auth.upload_song(config['uploads']['file'])
self.assertEqual(response.status_code, 409) self.assertEqual(response.status_code, 409)
@unittest.skip("Do not delete uploads")
def test_delete_upload_entity(self): def test_delete_upload_entity(self):
results = youtube_auth.get_library_upload_songs() results = youtube_auth.get_library_upload_songs()
response = youtube_auth.delete_upload_entity(results[0]['entityId']) response = youtube_auth.delete_upload_entity(results[0]['entityId'])

View file

@ -1 +1 @@
__version__ = "0.8.0" __version__ = "0.8.1"

View file

@ -2,6 +2,8 @@ import re
from http.cookies import SimpleCookie from http.cookies import SimpleCookie
from hashlib import sha1 from hashlib import sha1
import time import time
from functools import wraps
import locale
def prepare_browse_endpoint(type, browseId): def prepare_browse_endpoint(type, browseId):
@ -48,5 +50,16 @@ def get_authorization(auth):
return "SAPISIDHASH " + unix_timestamp + "_" + sha_1.hexdigest() return "SAPISIDHASH " + unix_timestamp + "_" + sha_1.hexdigest()
def to_int(string): def to_int(string, language):
return int(string.split(' ')[0].replace(',', '')) locale.setlocale(locale.LC_ALL, language)
number = string.split(' ')[0]
return locale.atoi(number)
def i18n(method):
@wraps(method)
def _impl(self, *method_args, **method_kwargs):
method.__globals__['_'] = self.lang.gettext
return method(self, *method_args, **method_kwargs)
return _impl

View file

@ -0,0 +1,29 @@
Translations
============================================
Translations use the Linux command line utility xgettext, which you can install for example using your package manager.
Add new translatable texts from code
----------------------------------------
xgettext -d base -o locales/base.pot ytmusicapi/*.py
sed --in-place locales/base.pot --expression=s/CHARSET/UTF-8/
Create new translation
----------------------
mkdir -p locales/{en,es}/LC_MESSAGES
cp locales/base.pot locales/LANG/LC_MESSAGES/base.po
Update translation
----------------
msgmerge --update locales/de/LC_MESSAGES/base.po locales/base.pot
Edit translation
----------------
You can use POEdit
Finalize translation
---------------------
To generate mo files, run
msgfmt -o locales/de/LC_MESSAGES/base.mo locales/de/LC_MESSAGES/base

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr ""
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr ""

Binary file not shown.

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr "künstler"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr "playlist"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr "titel"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr "video"
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr "album"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr "alben"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr "singles"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr "videos"

Binary file not shown.

View file

@ -0,0 +1,47 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 11:52+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:221 ytmusicapi/parsers.py:229
#: ytmusicapi/parsers.py:232
msgid "artist"
msgstr ""
#: ytmusicapi/parsers.py:221 ytmusicapi/parsers.py:229
#: ytmusicapi/parsers.py:241
msgid "playlist"
msgstr ""
#: ytmusicapi/parsers.py:221 ytmusicapi/parsers.py:224
#: ytmusicapi/parsers.py:246
msgid "song"
msgstr ""
#: ytmusicapi/parsers.py:221 ytmusicapi/parsers.py:224
#: ytmusicapi/parsers.py:253
msgid "video"
msgstr ""
#: ytmusicapi/parsers.py:222 ytmusicapi/parsers.py:229
#: ytmusicapi/parsers.py:235
msgid "album"
msgstr ""
#: ytmusicapi/ytmusic.py:69
msgid "Hello World"
msgstr ""

Binary file not shown.

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr "artista"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr "lista de reproducción"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr "canción"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr "vídeo"
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr "álbum"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr "álbumes"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr "sencillos"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr "vídeos"

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr ""
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr ""

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr ""
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr ""
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr ""
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr ""

Binary file not shown.

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr "artista"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr "playlist"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr "brano"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr "video"
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr "album"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr "album"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr "singoli"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr "video"

Binary file not shown.

View file

@ -0,0 +1,50 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2020-07-09 14:10+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:55
msgid "artist"
msgstr "アーティスト"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:64
msgid "playlist"
msgstr "プレイリスト"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:69
msgid "song"
msgstr "曲"
#: ytmusicapi/parsers.py:44 ytmusicapi/parsers.py:47 ytmusicapi/parsers.py:76
msgid "video"
msgstr "動画"
#: ytmusicapi/parsers.py:45 ytmusicapi/parsers.py:52 ytmusicapi/parsers.py:58
msgid "album"
msgstr "アルバム"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:328
msgid "albums"
msgstr "アルバム"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:331
msgid "singles"
msgstr "シングル"
#: ytmusicapi/ytmusic.py:307 ytmusicapi/ytmusic.py:334
msgid "videos"
msgstr "動画"

View file

@ -1,3 +1,4 @@
from ytmusicapi.helpers import i18n
# commonly used navigation paths # commonly used navigation paths
SINGLE_COLUMN_TAB = [ SINGLE_COLUMN_TAB = [
'contents', 'singleColumnBrowseResultsRenderer', 'tabs', 0, 'tabRenderer', 'content' 'contents', 'singleColumnBrowseResultsRenderer', 'tabs', 0, 'tabRenderer', 'content'
@ -28,6 +29,64 @@ THUMBNAIL_RENDERER = ['thumbnailRenderer', 'musicThumbnailRenderer', 'thumbnail'
THUMBNAIL_CROPPED = ['thumbnail', 'croppedSquareThumbnailRenderer', 'thumbnail', 'thumbnails'] THUMBNAIL_CROPPED = ['thumbnail', 'croppedSquareThumbnailRenderer', 'thumbnail', 'thumbnails']
class Parser:
def __init__(self, language):
self.lang = language
@i18n
def parse_search_result(self, data, resultType=None):
search_result = {}
default = not resultType
if not resultType:
resultType = get_item_text(data, 1).lower()
result_types = ['artist', 'playlist', 'song', 'video']
result_types_local = [_('artist'), _('playlist'), _('song'), _('video')]
# default to album since it's labeled with multiple values ('Single', 'EP', etc.)
if resultType not in result_types_local:
resultType = 'album'
else:
resultType = result_types[result_types_local.index(resultType)]
if resultType in ['song', 'video']:
search_result['videoId'] = nav(
data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId']
search_result['title'] = get_item_text(data, 0)
if resultType in ['artist', 'album', 'playlist']:
search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID)
if resultType in ['artist']:
search_result['artist'] = get_item_text(data, 0)
elif resultType in ['album']:
search_result['title'] = get_item_text(data, 0)
search_result['type'] = get_item_text(data, 1)
search_result['artist'] = get_item_text(data, 2)
search_result['year'] = get_item_text(data, 3)
elif resultType in ['playlist']:
search_result['title'] = get_item_text(data, 0)
search_result['author'] = get_item_text(data, 1 + default)
search_result['itemCount'] = get_item_text(data, 2 + default).split(' ')[0]
elif resultType in ['song']:
search_result['artists'] = parse_song_artists(data, 1 + default)
hasAlbum = len(data['flexColumns']) == 4 + default
if hasAlbum:
search_result['album'] = parse_song_album(data, 2 + default)
search_result['duration'] = get_item_text(data, 2 + hasAlbum + default)
elif resultType in ['video']:
search_result['artist'] = get_item_text(data, 1 + default)
search_result['views'] = get_item_text(data, 2 + default).split(' ')[0]
search_result['duration'] = get_item_text(data, 3 + default)
search_result['thumbnails'] = nav(data, THUMBNAILS)
search_result['resultType'] = resultType
return search_result
def parse_playlists(results): def parse_playlists(results):
playlists = [] playlists = []
for result in results: for result in results:
@ -89,10 +148,8 @@ def parse_albums(results, upload=True):
if has_artists: if has_artists:
subtitle = data['subtitle']['runs'][2] subtitle = data['subtitle']['runs'][2]
album['artists'].append({ album['artists'].append({
'name': 'name': subtitle['text'],
subtitle['text'], 'id': nav(subtitle, NAVIGATION_BROWSE_ID)
'id':
nav(subtitle, NAVIGATION_BROWSE_ID)
}) })
else: else:
album['artists'] = nav(data, SUBTITLE) album['artists'] = nav(data, SUBTITLE)
@ -210,55 +267,6 @@ def parse_uploaded_items(results):
return songs return songs
def parse_search_result(data, resultType=None):
search_result = {}
default = not resultType
if not resultType:
resultType = get_item_text(data, 1).lower()
# default to album since it's labeled with multiple values ('Single', 'EP', etc.)
if resultType not in ['artist', 'playlist', 'song', 'video']:
resultType = 'album'
if resultType in ['song', 'video']:
search_result['videoId'] = nav(
data, PLAY_BUTTON)['playNavigationEndpoint']['watchEndpoint']['videoId']
search_result['title'] = get_item_text(data, 0)
if resultType in ['artist', 'album', 'playlist']:
search_result['browseId'] = nav(data, NAVIGATION_BROWSE_ID)
if resultType in ['artist']:
search_result['artist'] = get_item_text(data, 0)
elif resultType in ['album']:
search_result['title'] = get_item_text(data, 0)
search_result['type'] = get_item_text(data, 1)
search_result['artist'] = get_item_text(data, 2)
search_result['year'] = get_item_text(data, 3)
elif resultType in ['playlist']:
search_result['title'] = get_item_text(data, 0)
search_result['author'] = get_item_text(data, 1 + default)
search_result['itemCount'] = get_item_text(data, 2 + default).split(' ')[0]
elif resultType in ['song']:
search_result['artists'] = parse_song_artists(data, 1 + default)
hasAlbum = len(data['flexColumns']) == 4 + default
if hasAlbum:
search_result['album'] = parse_song_album(data, 2 + default)
search_result['duration'] = get_item_text(data, 2 + hasAlbum + default)
elif resultType in ['video']:
search_result['artist'] = get_item_text(data, 1 + default)
search_result['views'] = get_item_text(data, 2 + default).split(' ')[0]
search_result['duration'] = get_item_text(data, 3 + default)
search_result['thumbnails'] = nav(data, THUMBNAILS)
search_result['resultType'] = resultType
return search_result
def parse_song_artists(data, index): def parse_song_artists(data, index):
flex_item = get_flex_column_item(data, index) flex_item = get_flex_column_item(data, index)
if not flex_item: if not flex_item:

View file

@ -1,5 +1,7 @@
import requests import requests
import json import json
import unicodedata
import gettext
import pkg_resources import pkg_resources
import ntpath import ntpath
import os import os
@ -18,7 +20,11 @@ class YTMusic:
Permits both authenticated and non-authenticated requests. Permits both authenticated and non-authenticated requests.
Authentication header data must be provided on initialization. Authentication header data must be provided on initialization.
""" """
def __init__(self, auth: str = None, user: str = None, proxies: dict = {}): def __init__(self,
auth: str = None,
user: str = None,
proxies: dict = None,
language: str = 'en'):
""" """
Create a new instance to interact with YouTube Music. Create a new instance to interact with YouTube Music.
@ -34,8 +40,12 @@ class YTMusic:
The user ID will be in the URL: https://myaccount.google.com/b/user_id/ The user ID will be in the URL: https://myaccount.google.com/b/user_id/
:param proxies: Optional. Proxy configuration in requests_ format_. :param proxies: Optional. Proxy configuration in requests_ format_.
.. _requests: https://requests.readthedocs.io/ .. _requests: https://requests.readthedocs.io/
.. _format: https://requests.readthedocs.io/en/master/user/advanced/#proxies .. _format: https://requests.readthedocs.io/en/master/user/advanced/#proxies
:param language: Optional. Can be used to change the language of returned data.
English will be used by default. Available languages can be checked in
the ytmusicapi/locales directory.
""" """
self.auth = auth self.auth = auth
self.proxies = proxies self.proxies = proxies
@ -55,6 +65,20 @@ class YTMusic:
with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file: with open(pkg_resources.resource_filename('ytmusicapi', 'context.json')) as json_file:
self.context = json.load(json_file) self.context = json.load(json_file)
self.context['context']['client']['hl'] = language
supported_languages = [
f for f in pkg_resources.resource_listdir('ytmusicapi', 'locales')
]
if language in supported_languages:
self.language = language
self.lang = gettext.translation('base',
localedir=pkg_resources.resource_filename(
'ytmusicapi', 'locales'),
languages=[language])
self.parser = Parser(self.lang)
else:
raise Exception("Language not supported. Supported languages are ")
if user: if user:
self.context['context']['user']['onBehalfOfUser'] = user self.context['context']['user']['onBehalfOfUser'] = user
@ -187,7 +211,7 @@ class YTMusic:
for result in results: for result in results:
data = result['musicResponsiveListItemRenderer'] data = result['musicResponsiveListItemRenderer']
type = filter[:-1] if filter else None type = filter[:-1] if filter else None
search_result = parse_search_result(data, type) search_result = self.parser.parse_search_result(data, type)
search_results.append(search_result) search_results.append(search_result)
except Exception as e: except Exception as e:
@ -195,6 +219,7 @@ class YTMusic:
return search_results return search_results
@i18n
def get_artist(self, channelId: str) -> Dict: def get_artist(self, channelId: str) -> Dict:
""" """
Get information about an artist and their top releases (songs, Get information about an artist and their top releases (songs,
@ -295,11 +320,13 @@ class YTMusic:
artist['songs']['results'] = parse_playlist_items(musicShelf['contents']) artist['songs']['results'] = parse_playlist_items(musicShelf['contents'])
categories = ['albums', 'singles', 'videos'] categories = ['albums', 'singles', 'videos']
for category in categories: categories_local = [_('albums'), _('singles'), _('videos')]
for i, category in enumerate(categories):
data = [ data = [
r['musicCarouselShelfRenderer'] r['musicCarouselShelfRenderer'] for r in results
for r in results if 'musicCarouselShelfRenderer' in r and nav( if 'musicCarouselShelfRenderer' in r
r['musicCarouselShelfRenderer'], CAROUSEL_TITLE)['text'].lower() == category and nav(r['musicCarouselShelfRenderer'],
CAROUSEL_TITLE)['text'].lower() == categories_local[i]
] ]
if len(data) > 0: if len(data) > 0:
artist[category] = {'browseId': None, 'results': []} artist[category] = {'browseId': None, 'results': []}
@ -794,7 +821,9 @@ class YTMusic:
playlist['year'] = nav(header, SUBTITLE3) playlist['year'] = nav(header, SUBTITLE3)
if len(header['secondSubtitle']['runs']) > 1: if len(header['secondSubtitle']['runs']) > 1:
song_count = to_int(header['secondSubtitle']['runs'][0]['text']) song_count = to_int(
unicodedata.normalize("NFKD", header['secondSubtitle']['runs'][0]['text']),
self.language)
playlist['duration'] = header['secondSubtitle']['runs'][2]['text'] playlist['duration'] = header['secondSubtitle']['runs'][2]['text']
else: else:
playlist['duration'] = header['secondSubtitle']['runs'][0]['text'] playlist['duration'] = header['secondSubtitle']['runs'][0]['text']
@ -1138,7 +1167,8 @@ class YTMusic:
album['year'] = nav(header, SUBTITLE3) album['year'] = nav(header, SUBTITLE3)
if len(header['secondSubtitle']['runs']) > 1: if len(header['secondSubtitle']['runs']) > 1:
album['trackCount'] = to_int(header['secondSubtitle']['runs'][0]['text']) album['trackCount'] = to_int(header['secondSubtitle']['runs'][0]['text'],
self.language)
album['duration'] = header['secondSubtitle']['runs'][2]['text'] album['duration'] = header['secondSubtitle']['runs'][2]['text']
else: else:
album['duration'] = header['secondSubtitle']['runs'][0]['text'] album['duration'] = header['secondSubtitle']['runs'][0]['text']
@ -1184,7 +1214,7 @@ class YTMusic:
else: else:
return response return response
def delete_upload_entity(self, entityId: str) -> Union[str, Dict]: def delete_upload_entity(self, entityId: str) -> Union[str, Dict]: # pragma: no cover
""" """
Deletes a previously uploaded song or album Deletes a previously uploaded song or album