get_home: fix song artist parsing (#798)

* get_home: fix song artist parsing

extra text is now excluded from `artists`:

- `get_home`/`get_song_related`: play counts in certain track carousels
- `get_home`: "Song" specifiers for audio tracks

`get_explore` song charts are also no longer missing `album` data

* skip type specifiers in parse_song_runs without comparing text
This commit is contained in:
Solomon 2025-08-23 17:21:54 +00:00 • committed by GitHub
commit e738b2a70f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 118 additions and 68 deletions

View file

@ -15,6 +15,16 @@ class TestBrowsing:
assert len(result) >= 2
result = yt_auth.get_home(limit=15)
assert len(result) >= 15
assert all(
# ensure we aren't parsing specifiers like "Song" as artist names
[
item["artists"][0]["id"]
or item["artists"][0]["name"].lower() not in yt_auth.parser.get_api_result_types()
for section in result
for item in section["contents"]
if item and len(item.get("artists", [])) > 1
]
)
def test_get_artist(self, yt):
results = yt.get_artist("MPLAUCmMUZbaYdNH0bEd1PAlAqsA")
@ -179,6 +189,15 @@ class TestBrowsing:
song = yt_oauth.get_watch_playlist(sample_video)
song = yt_oauth.get_song_related(song["related"])
assert len(song) >= 5
assert all(
# ensure every video is associated with a view count or music album
[
item.get("views") or item.get("album")
for section in song
for item in section["contents"]
if "videoId" in item
]
)
def test_get_lyrics(self, config, yt, sample_video):
playlist = yt.get_watch_playlist(sample_video)

View file

@ -16,7 +16,10 @@ class TestExplore:
assert all(item["audioPlaylistId"].startswith("OLA") for item in explore["new_releases"])
# check top_songs if present
assert all(item["videoId"] for item in explore.get("top_songs", {"items": []})["items"])
assert all(
item["videoId"] and (item.get("views") or item.get("album"))
for item in explore.get("top_songs", {"items": []})["items"]
)
assert all(
item["videoId"] and all(artist["id"] for artist in item["artists"])

View file

@ -142,6 +142,16 @@ class TestSearch:
"name": "Stanford GSB Podcasts",
}
def test_search_top_result_video(self, yt):
results = yt.search("Fuel Eminem")
assert results[0]["category"] == "Top result"
assert results[0]["resultType"] == "video"
assert results[0]["videoId"] == "t5H_CewqpKA"
assert results[0]["artists"] == [
{"name": "Eminem", "id": "UCedvOgsKFzcK3hA5taf3KoQ"},
{"name": "JID", "id": "UCRlGNubLJBgW9VRCuiUnuYw"},
]
def test_search_uploads(self, config, yt, yt_oauth):
with pytest.raises(Exception, match="No filter can be set when searching uploads"):
yt.search(

View file

@ -1,6 +1,5 @@
import re
import warnings
from collections.abc import Callable
from typing import Literal, cast, overload
from ytmusicapi.continuations import (
@ -117,8 +116,7 @@ class BrowsingMixin(MixinProtocol):
body = {"browseId": "FEmusic_home"}
response = self._send_request(endpoint, body)
results = nav(response, SINGLE_COLUMN_TAB + SECTION_LIST)
home = []
home.extend(parse_mixed_content(results))
home = parse_mixed_content(results)
section_list = nav(response, [*SINGLE_COLUMN_TAB, "sectionListRenderer"])
if "continuations" in section_list:
@ -126,11 +124,13 @@ class BrowsingMixin(MixinProtocol):
endpoint, body, additionalParams
)
parse_func: Callable[[JsonList], JsonList] = lambda contents: parse_mixed_content(contents)
home.extend(
get_continuations(
section_list, "sectionListContinuation", limit - len(home), request_func, parse_func
section_list,
"sectionListContinuation",
limit - len(home),
request_func,
parse_mixed_content,
)
)
@ -847,7 +847,9 @@ class BrowsingMixin(MixinProtocol):
response = self._send_request("browse", {"browseId": browseId})
sections = nav(response, ["contents", *SECTION_LIST])
return parse_mixed_content(sections)
return parse_mixed_content(
sections,
)
@overload
def get_lyrics(self, browseId: str, timestamps: Literal[False] = False) -> Lyrics | None:

View file

@ -237,7 +237,7 @@ class ExploreMixin(MixinProtocol):
case playlist_id if playlist_id.startswith("VLOLA"):
explore["trending"] = {
"playlist": playlist_id,
"items": parse_content_list(contents, parse_trending_song, MRLIR),
"items": parse_content_list(contents, parse_song_flat, MRLIR),
}
return explore

View file

@ -234,18 +234,14 @@ class SearchMixin(MixinProtocol):
else:
continue
api_search_result_types = self.parser.get_api_result_types()
search_results.extend(
parse_search_results(shelf_contents, api_search_result_types, result_type, category)
)
search_results.extend(parse_search_results(shelf_contents, result_type, category))
if filter: # if filter is set, there are continuations
request_func: RequestFuncType = lambda additionalParams: self._send_request(
endpoint, body, additionalParams
)
parse_func: ParseFuncType = lambda contents: parse_search_results(
contents, api_search_result_types, result_type, category
contents, result_type, category
)
search_results.extend(

View file

@ -7,6 +7,8 @@ from typing import ParamSpec, TypeVar
from ytmusicapi.navigation import *
from ytmusicapi.type_alias import JsonDict, JsonList
from .constants import DOT_SEPARATOR_RUN
P = ParamSpec("P")
R = TypeVar("R")
@ -69,7 +71,7 @@ def get_fixed_column_item(item: JsonDict, index: int) -> JsonDict | None:
def get_dot_separator_index(runs: JsonList) -> int:
try:
index = runs.index({"text": " • "})
index = runs.index(DOT_SEPARATOR_RUN)
except ValueError:
index = len(runs)

View file

@ -7,7 +7,9 @@ from .podcasts import parse_episode, parse_podcast
from .songs import *
def parse_mixed_content(rows: JsonList) -> JsonList:
def parse_mixed_content(
rows: JsonList,
) -> JsonList:
items = []
for row in rows:
if DESCRIPTION_SHELF[0] in row:
@ -92,7 +94,7 @@ def parse_song(result: JsonDict) -> JsonDict:
"playlistId": nav(result, NAVIGATION_PLAYLIST_ID, True),
"thumbnails": nav(result, THUMBNAIL_RENDERER),
}
song.update(parse_song_runs(nav(result, SUBTITLE_RUNS)))
song.update(parse_song_runs(nav(result, SUBTITLE_RUNS), skip_type_spec=True))
return song
@ -101,17 +103,18 @@ def parse_song_flat(data: JsonDict) -> JsonDict:
song = {
"title": nav(columns[0], TEXT_RUN_TEXT),
"videoId": nav(columns[0], TEXT_RUN + NAVIGATION_VIDEO_ID, True),
"artists": parse_song_artists(data, 1),
"thumbnails": nav(data, THUMBNAILS),
"isExplicit": nav(data, BADGE_LABEL, True) is not None,
}
runs = nav(columns[1], TEXT_RUNS)
song.update(parse_song_runs(runs, skip_type_spec=True))
if len(columns) > 2 and columns[2] is not None and "navigationEndpoint" in nav(columns[2], TEXT_RUN):
song["album"] = {
"name": nav(columns[2], TEXT_RUN_TEXT),
"id": nav(columns[2], TEXT_RUN + NAVIGATION_BROWSE_ID),
}
else:
song["views"] = nav(columns[1], ["text", "runs", -1, "text"]).split(" ")[0]
return song

View file

@ -0,0 +1 @@
DOT_SEPARATOR_RUN = {"text": " • "}

View file

@ -7,7 +7,7 @@ TRENDS = {"ARROW_DROP_UP": "up", "ARROW_DROP_DOWN": "down", "ARROW_CHART_NEUTRAL
def parse_chart_song(data: JsonDict) -> JsonDict:
parsed = parse_trending_song(data)
parsed = parse_song_flat(data)
parsed.update(parse_ranking(data))
return parsed
@ -43,18 +43,6 @@ def parse_chart_artist(data: JsonDict) -> JsonDict:
return parsed
def parse_trending_song(data: JsonDict) -> JsonDict:
flex_0 = get_flex_column_item(data, 0)
return {
"title": nav(flex_0, TEXT_RUN_TEXT),
"videoId": nav(flex_0, TEXT_RUN + NAVIGATION_VIDEO_ID, True),
**(parse_song_runs(nav(get_flex_column_item(data, 1), TEXT_RUNS))),
"playlistId": nav(flex_0, TEXT_RUN + NAVIGATION_PLAYLIST_ID, True),
"thumbnails": nav(data, THUMBNAILS),
"isExplicit": nav(data, BADGE_LABEL, True) is not None,
}
def parse_ranking(data: JsonDict) -> JsonDict:
return {
"rank": nav(data, ["customIndexColumn", "musicCustomIndexColumnRenderer", *TEXT_RUN_TEXT]),

View file

@ -81,9 +81,7 @@ def parse_top_result(data: JsonDict, search_result_types: list[str]) -> JsonDict
return search_result
def parse_search_result(
data: JsonDict, api_search_result_types: list[str], result_type: str | None, category: str | None
) -> JsonDict:
def parse_search_result(data: JsonDict, result_type: str | None, category: str | None) -> JsonDict:
default_offset = (not result_type or result_type == "album") * 2
search_result: JsonDict = {"category": category}
video_type = nav(data, [*PLAY_BUTTON, "playNavigationEndpoint", *NAVIGATION_VIDEO_TYPE], True)
@ -191,9 +189,7 @@ def parse_search_result(
runs = flex_item["text"]["runs"]
if flex_item2 := get_flex_column_item(data, 2):
runs.extend([{"text": ""}, *flex_item2["text"]["runs"]]) # first item is a dummy separator
# ignore the first run if it is a type specifier (like "Single" or "Album")
runs_offset = (len(runs[0]) == 1 and runs[0]["text"].lower() in api_search_result_types) * 2
song_info = parse_song_runs(runs[runs_offset:])
song_info = parse_song_runs(runs, skip_type_spec=True)
search_result.update(song_info)
if result_type in ["artist", "album", "playlist", "profile", "podcast"]:
@ -219,14 +215,10 @@ def parse_search_result(
def parse_search_results(
results: JsonList,
api_search_result_types: list[str],
resultType: str | None = None,
category: str | None = None,
) -> JsonList:
return [
parse_search_result(result[MRLIR], api_search_result_types, resultType, category)
for result in results
]
return [parse_search_result(result[MRLIR], resultType, category) for result in results]
def get_search_params(filter: str | None, scope: str | None, ignore_spelling: bool) -> str | None:

View file

@ -3,6 +3,7 @@ import re
from ytmusicapi.type_alias import JsonDict, JsonList
from ._utils import *
from .constants import DOT_SEPARATOR_RUN
def parse_song_artists(data: JsonDict, index: int) -> JsonList:
@ -21,34 +22,67 @@ def parse_song_artists_runs(runs: JsonList) -> JsonList:
return artists
def parse_song_runs(runs: JsonList) -> JsonDict:
def parse_song_run(run: JsonDict) -> JsonDict:
text = run["text"]
if "navigationEndpoint" in run: # artist or album
item = {"name": text, "id": nav(run, NAVIGATION_BROWSE_ID, True)}
if item["id"] and (item["id"].startswith("MPRE") or "release_detail" in item["id"]): # album
return {"type": "album", "data": item}
else: # artist
return {"type": "artist", "data": item}
else:
# note: YT uses non-breaking space \xa0 to separate number and magnitude
if re.match(r"^\d([^ ])* [^ ]*$", text):
return {"type": "views", "data": text.split(" ")[0]}
elif re.match(r"^(\d+:)*\d+:\d+$", text):
return {"type": "duration", "data": text}
elif re.match(r"^\d{4}$", text):
return {"type": "year", "data": text}
else: # artist without id
return {"type": "artist", "data": {"name": text, "id": None}}
def parse_song_runs(runs: JsonList, skip_type_spec: bool = False) -> JsonDict:
"""
:param skip_type_spec: if true, skip the type specifier (like "Song", "Single", or "Album") that may appear before artists ("Song • Eminem"). Otherwise, that text item is parsed as an artist with no ID.
"""
parsed: JsonDict = {"artists": []}
for i, run in enumerate(runs):
# prevent type specifier from being parsed as an artist
# it's the first run, separated from the actual artists by " • "
if (
skip_type_spec
and len(runs) > 2
and parse_song_run(runs[0])["type"] == "artist"
and runs[1] == DOT_SEPARATOR_RUN
and parse_song_run(runs[2])["type"] == "artist"
):
runs = runs[2:]
for i, run in list(enumerate(runs)):
if i % 2: # uneven items are always separators
continue
text = run["text"]
if "navigationEndpoint" in run: # artist or album
item = {"name": text, "id": nav(run, NAVIGATION_BROWSE_ID, True)}
if item["id"] and (item["id"].startswith("MPRE") or "release_detail" in item["id"]): # album
parsed["album"] = item
else: # artist
parsed["artists"].append(item)
else:
# note: YT uses non-breaking space \xa0 to separate number and magnitude
if re.match(r"^\d([^ ])* [^ ]*$", text) and i > 0:
parsed["views"] = text.split(" ")[0]
elif re.match(r"^(\d+:)*\d+:\d+$", text):
parsed["duration"] = text
parsed["duration_seconds"] = parse_duration(text)
elif re.match(r"^\d{4}$", text):
parsed["year"] = text
else: # artist without id
parsed["artists"].append({"name": text, "id": None})
parsed_run = parse_song_run(run)
data = parsed_run["data"]
match parsed_run["type"]:
case "album":
parsed["album"] = data
case "artist":
parsed["artists"].append(data)
case "views":
parsed["views"] = data
case "duration":
parsed["duration"] = data
parsed["duration_seconds"] = parse_duration(data)
case "year":
parsed["year"] = data
return parsed