Compare commits
8 Commits
adding_gen
...
49c3734526
Author | SHA1 | Date | |
---|---|---|---|
49c3734526 | |||
bc19a94e7f | |||
5d26fdbf94 | |||
465af49057 | |||
2aa0f02fa5 | |||
7b0b830d64 | |||
1ba6c97f5a | |||
c8cbfc7cb9 |
@@ -6,6 +6,7 @@ from typing import List, Optional
|
|||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
|
from ..utils import output, BColors
|
||||||
from ..utils.config import main_settings
|
from ..utils.config import main_settings
|
||||||
from ..utils.string_processing import fit_to_file_system
|
from ..utils.string_processing import fit_to_file_system
|
||||||
|
|
||||||
@@ -204,9 +205,12 @@ class Cache:
|
|||||||
for path in self._dir.iterdir():
|
for path in self._dir.iterdir():
|
||||||
if path.is_dir():
|
if path.is_dir():
|
||||||
for file in path.iterdir():
|
for file in path.iterdir():
|
||||||
|
output(f"Deleting file {file}", color=BColors.GREY)
|
||||||
file.unlink()
|
file.unlink()
|
||||||
|
output(f"Deleting folder {path}", color=BColors.HEADER)
|
||||||
path.rmdir()
|
path.rmdir()
|
||||||
else:
|
else:
|
||||||
|
output(f"Deleting folder {path}", color=BColors.HEADER)
|
||||||
path.unlink()
|
path.unlink()
|
||||||
|
|
||||||
self.cached_attributes.clear()
|
self.cached_attributes.clear()
|
||||||
|
@@ -1,18 +1,14 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import List, Optional, Dict, Tuple, Type, Union, TypedDict
|
from typing import Dict, List, Optional, Set, Tuple, Type, TypedDict, Union
|
||||||
|
|
||||||
from .collection import Collection
|
|
||||||
from .metadata import (
|
|
||||||
Mapping as id3Mapping,
|
|
||||||
ID3Timestamp,
|
|
||||||
Metadata
|
|
||||||
)
|
|
||||||
from ..utils.string_processing import unify, hash_url
|
|
||||||
|
|
||||||
from .parents import OuterProxy as Base
|
|
||||||
|
|
||||||
from ..utils.config import main_settings
|
from ..utils.config import main_settings
|
||||||
|
from ..utils.string_processing import hash_url, unify
|
||||||
|
from .collection import Collection
|
||||||
|
from .metadata import ID3Timestamp
|
||||||
|
from .metadata import Mapping as id3Mapping
|
||||||
|
from .metadata import Metadata
|
||||||
|
from .parents import OuterProxy as Base
|
||||||
|
|
||||||
|
|
||||||
class ArtworkVariant(TypedDict):
|
class ArtworkVariant(TypedDict):
|
||||||
@@ -23,7 +19,9 @@ class ArtworkVariant(TypedDict):
|
|||||||
|
|
||||||
|
|
||||||
class Artwork:
|
class Artwork:
|
||||||
def __init__(self, *variants: List[ArtworkVariant]) -> None:
|
def __init__(self, *variants: List[ArtworkVariant], parent_artworks: Set[Artwork] = None) -> None:
|
||||||
|
self.parent_artworks: Set[Artwork] = parent_artworks or set()
|
||||||
|
|
||||||
self._variant_mapping: Dict[str, ArtworkVariant] = {}
|
self._variant_mapping: Dict[str, ArtworkVariant] = {}
|
||||||
|
|
||||||
for variant in variants:
|
for variant in variants:
|
||||||
@@ -36,7 +34,7 @@ class Artwork:
|
|||||||
def append(self, url: str, width: int = main_settings["preferred_artwork_resolution"], height: int = main_settings["preferred_artwork_resolution"], **kwargs) -> None:
|
def append(self, url: str, width: int = main_settings["preferred_artwork_resolution"], height: int = main_settings["preferred_artwork_resolution"], **kwargs) -> None:
|
||||||
if url is None:
|
if url is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
self._variant_mapping[hash_url(url=url)] = {
|
self._variant_mapping[hash_url(url=url)] = {
|
||||||
"url": url,
|
"url": url,
|
||||||
"width": width,
|
"width": width,
|
||||||
@@ -44,21 +42,36 @@ class Artwork:
|
|||||||
"deviation": self._calculate_deviation(width, height),
|
"deviation": self._calculate_deviation(width, height),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def flat_empty(self) -> bool:
|
||||||
|
return len(self._variant_mapping.keys()) <= 0
|
||||||
|
|
||||||
|
def _get_best_from_list(self, artwork_variants: List[ArtworkVariant]) -> Optional[ArtworkVariant]:
|
||||||
|
return min(artwork_variants, key=lambda x: x["deviation"])
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def best_variant(self) -> ArtworkVariant:
|
def best_variant(self) -> ArtworkVariant:
|
||||||
if len(self._variant_mapping.keys()) <= 0:
|
if self.flat_empty:
|
||||||
return None
|
return self._get_best_from_list([parent.best_variant for parent in self.parent_artworks])
|
||||||
return min(self._variant_mapping.values(), key=lambda x: x["deviation"])
|
return self._get_best_from_list(self._variant_mapping.values())
|
||||||
|
|
||||||
def get_variant_name(self, variant: ArtworkVariant) -> str:
|
def get_variant_name(self, variant: ArtworkVariant) -> str:
|
||||||
return f"artwork_{variant['width']}x{variant['height']}_{hash_url(variant['url']).replace('/', '_')}"
|
return f"artwork_{variant['width']}x{variant['height']}_{hash_url(variant['url']).replace('/', '_')}"
|
||||||
|
|
||||||
def __merge__(self, other: Artwork, **kwargs) -> None:
|
def __merge__(self, other: Artwork, **kwargs) -> None:
|
||||||
|
self.parent_artworks.update(other.parent_artworks)
|
||||||
|
|
||||||
for key, value in other._variant_mapping.items():
|
for key, value in other._variant_mapping.items():
|
||||||
if key not in self._variant_mapping:
|
if key not in self._variant_mapping:
|
||||||
self._variant_mapping[key] = value
|
self._variant_mapping[key] = value
|
||||||
|
|
||||||
|
def __hash__(self) -> int:
|
||||||
|
return id(self)
|
||||||
|
|
||||||
def __eq__(self, other: Artwork) -> bool:
|
def __eq__(self, other: Artwork) -> bool:
|
||||||
|
if hash(self) == hash(other):
|
||||||
|
return True
|
||||||
|
|
||||||
if not isinstance(other, Artwork):
|
if not isinstance(other, Artwork):
|
||||||
return False
|
return False
|
||||||
return any(a == b for a, b in zip(self._variant_mapping.keys(), other._variant_mapping.keys()))
|
return any(a == b for a, b in zip(self._variant_mapping.keys(), other._variant_mapping.keys()))
|
||||||
|
@@ -1,16 +1,44 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections import defaultdict
|
|
||||||
from typing import TypeVar, Generic, Dict, Optional, Iterable, List, Iterator, Tuple, Generator, Union, Any, Set
|
|
||||||
import copy
|
import copy
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import (Any, Callable, Dict, Generator, Generic, Iterable,
|
||||||
|
Iterator, List, Optional, Set, Tuple, TypeVar, Union)
|
||||||
|
|
||||||
from .parents import OuterProxy
|
from ..utils import BColors, object_trace, output
|
||||||
from ..utils import object_trace
|
from .parents import InnerData, OuterProxy
|
||||||
from ..utils import output, BColors
|
|
||||||
|
|
||||||
T = TypeVar('T', bound=OuterProxy)
|
T = TypeVar('T', bound=OuterProxy)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppendHookArguments:
|
||||||
|
"""
|
||||||
|
This class is used to store the arguments for the append hook.
|
||||||
|
The best explanation is with an examples:
|
||||||
|
|
||||||
|
```
|
||||||
|
# this is the action that triggers the append hook
|
||||||
|
album = Album()
|
||||||
|
song = Song()
|
||||||
|
album.song_collection.append(song)
|
||||||
|
```
|
||||||
|
|
||||||
|
In this case, the append hook is triggered with the following arguments:
|
||||||
|
```
|
||||||
|
AppendHookArguments(
|
||||||
|
collection=album.song_collection,
|
||||||
|
new_object=song,
|
||||||
|
collection_root_objects=[album]
|
||||||
|
)
|
||||||
|
```
|
||||||
|
"""
|
||||||
|
|
||||||
|
collection: Collection
|
||||||
|
new_object: T
|
||||||
|
collection_root_objects: Set[InnerData]
|
||||||
|
|
||||||
class Collection(Generic[T]):
|
class Collection(Generic[T]):
|
||||||
__is_collection__ = True
|
__is_collection__ = True
|
||||||
|
|
||||||
@@ -27,6 +55,7 @@ class Collection(Generic[T]):
|
|||||||
sync_on_append: Dict[str, Collection] = None,
|
sync_on_append: Dict[str, Collection] = None,
|
||||||
append_object_to_attribute: Dict[str, T] = None,
|
append_object_to_attribute: Dict[str, T] = None,
|
||||||
extend_object_to_attribute: Dict[str, Collection] = None,
|
extend_object_to_attribute: Dict[str, Collection] = None,
|
||||||
|
append_callbacks: List[Callable[[AppendHookArguments], None]] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
self._collection_for: dict = dict()
|
self._collection_for: dict = dict()
|
||||||
|
|
||||||
@@ -41,6 +70,7 @@ class Collection(Generic[T]):
|
|||||||
self.sync_on_append: Dict[str, Collection] = sync_on_append or {}
|
self.sync_on_append: Dict[str, Collection] = sync_on_append or {}
|
||||||
self.pull_from: List[Collection] = []
|
self.pull_from: List[Collection] = []
|
||||||
self.push_to: List[Collection] = []
|
self.push_to: List[Collection] = []
|
||||||
|
self.append_callbacks: List[Callable[[AppendHookArguments], None]] = append_callbacks or []
|
||||||
|
|
||||||
# This is to cleanly unmap previously mapped items by their id
|
# This is to cleanly unmap previously mapped items by their id
|
||||||
self._indexed_from_id: Dict[int, Dict[str, Any]] = defaultdict(dict)
|
self._indexed_from_id: Dict[int, Dict[str, Any]] = defaultdict(dict)
|
||||||
@@ -141,6 +171,14 @@ class Collection(Generic[T]):
|
|||||||
for attribute, new_object in self.append_object_to_attribute.items():
|
for attribute, new_object in self.append_object_to_attribute.items():
|
||||||
other.__getattribute__(attribute).append(new_object, **kwargs)
|
other.__getattribute__(attribute).append(new_object, **kwargs)
|
||||||
|
|
||||||
|
append_hook_args = AppendHookArguments(
|
||||||
|
collection=self,
|
||||||
|
new_object=other,
|
||||||
|
collection_root_objects=self._collection_for.keys(),
|
||||||
|
)
|
||||||
|
for callback in self.append_callbacks:
|
||||||
|
callback(append_hook_args)
|
||||||
|
|
||||||
def append(self, other: Optional[T], **kwargs):
|
def append(self, other: Optional[T], **kwargs):
|
||||||
"""
|
"""
|
||||||
If an object, that represents the same entity exists in a relevant collection,
|
If an object, that represents the same entity exists in a relevant collection,
|
||||||
|
@@ -477,6 +477,8 @@ class Artist(Base):
|
|||||||
general_genre: str
|
general_genre: str
|
||||||
unformatted_location: str
|
unformatted_location: str
|
||||||
|
|
||||||
|
artwork: List[Artwork]
|
||||||
|
|
||||||
source_collection: SourceCollection
|
source_collection: SourceCollection
|
||||||
contact_collection: Collection[Contact]
|
contact_collection: Collection[Contact]
|
||||||
|
|
||||||
@@ -493,6 +495,8 @@ class Artist(Base):
|
|||||||
"lyrical_themes": list,
|
"lyrical_themes": list,
|
||||||
"general_genre": lambda: "",
|
"general_genre": lambda: "",
|
||||||
|
|
||||||
|
"artwork": list,
|
||||||
|
|
||||||
"source_collection": SourceCollection,
|
"source_collection": SourceCollection,
|
||||||
"album_collection": Collection,
|
"album_collection": Collection,
|
||||||
"contact_collection": Collection,
|
"contact_collection": Collection,
|
||||||
@@ -511,6 +515,7 @@ class Artist(Base):
|
|||||||
notes: FormattedText = None,
|
notes: FormattedText = None,
|
||||||
lyrical_themes: List[str] = None,
|
lyrical_themes: List[str] = None,
|
||||||
general_genre: str = None,
|
general_genre: str = None,
|
||||||
|
artwork: List[Artwork] = None,
|
||||||
unformatted_location: str = None,
|
unformatted_location: str = None,
|
||||||
source_list: List[Source] = None,
|
source_list: List[Source] = None,
|
||||||
contact_list: List[Contact] = None,
|
contact_list: List[Contact] = None,
|
||||||
|
@@ -134,7 +134,7 @@ class Genius(Page):
|
|||||||
source_list=[source],
|
source_list=[source],
|
||||||
artist_list=[self.parse_api_object(data.get("artist"))],
|
artist_list=[self.parse_api_object(data.get("artist"))],
|
||||||
artwork=artwork,
|
artwork=artwork,
|
||||||
date=ID3Timestamp(**data.get("release_date_components", {})),
|
date=ID3Timestamp(**(data.get("release_date_components") or {})),
|
||||||
)
|
)
|
||||||
|
|
||||||
if object_type == "song":
|
if object_type == "song":
|
||||||
|
@@ -457,17 +457,17 @@ class Musify(Page):
|
|||||||
for album_info in soup.find_all("ul", {"class": "album-info"}):
|
for album_info in soup.find_all("ul", {"class": "album-info"}):
|
||||||
list_element: BeautifulSoup = album_info.find("li")
|
list_element: BeautifulSoup = album_info.find("li")
|
||||||
|
|
||||||
if list_element is not None:
|
if list_element is not None:
|
||||||
artist_soup: BeautifulSoup
|
artist_soup: BeautifulSoup
|
||||||
for artist_soup in list_element.find_all("a"):
|
for artist_soup in list_element.find_all("a"):
|
||||||
artist_source_list = []
|
artist_source_list = []
|
||||||
href = artist_soup["href"]
|
href = artist_soup["href"]
|
||||||
if href is not None:
|
if href is not None:
|
||||||
artist_source_list = [Source(self.SOURCE_TYPE, self.HOST + href)]
|
artist_source_list = [Source(self.SOURCE_TYPE, self.HOST + href)]
|
||||||
artist_list.append(Artist(
|
artist_list.append(Artist(
|
||||||
name=artist_soup.text.strip(),
|
name=artist_soup.text.strip(),
|
||||||
source_list=artist_source_list
|
source_list=artist_source_list
|
||||||
))
|
))
|
||||||
|
|
||||||
# breadcrums
|
# breadcrums
|
||||||
breadcrumb_list_element_list: List[BeautifulSoup] = soup.find_all("ol", {"class": "breadcrumb"})
|
breadcrumb_list_element_list: List[BeautifulSoup] = soup.find_all("ol", {"class": "breadcrumb"})
|
||||||
@@ -485,7 +485,7 @@ class Musify(Page):
|
|||||||
|
|
||||||
track_name = list_points[4].text.strip()
|
track_name = list_points[4].text.strip()
|
||||||
|
|
||||||
# artwork
|
# album artwork
|
||||||
artwork: Artwork = Artwork()
|
artwork: Artwork = Artwork()
|
||||||
album_image_element_list: List[BeautifulSoup] = soup.find_all("img", {"class": "album-img"})
|
album_image_element_list: List[BeautifulSoup] = soup.find_all("img", {"class": "album-img"})
|
||||||
for album_image_element in album_image_element_list:
|
for album_image_element in album_image_element_list:
|
||||||
@@ -918,7 +918,8 @@ class Musify(Page):
|
|||||||
name=name,
|
name=name,
|
||||||
country=country,
|
country=country,
|
||||||
source_list=source_list,
|
source_list=source_list,
|
||||||
notes=notes
|
notes=notes,
|
||||||
|
artwork=self._fetch_artist_artwork(soup, **kwargs)
|
||||||
)
|
)
|
||||||
|
|
||||||
def _parse_album_card(self, album_card: BeautifulSoup, artist_name: str = None, **kwargs) -> Album:
|
def _parse_album_card(self, album_card: BeautifulSoup, artist_name: str = None, **kwargs) -> Album:
|
||||||
@@ -1056,6 +1057,20 @@ class Musify(Page):
|
|||||||
|
|
||||||
artist.album_collection.append(album)
|
artist.album_collection.append(album)
|
||||||
|
|
||||||
|
def _fetch_artist_artwork(self, soup: BeautifulSoup, **kwargs):
|
||||||
|
# artist artwork
|
||||||
|
artist_artwork: List[Artwork] = Artwork()
|
||||||
|
artist_a_element_list: List[BeautifulSoup] = soup.find_all("a")
|
||||||
|
for artist_a_element in artist_a_element_list:
|
||||||
|
if artist_a_element.find_all("img", {"class": "artist-img"}).count() > 0:
|
||||||
|
artwork_gallery = self.connection.get(artist_a_element("data-src", artist_a_element.get("href")))
|
||||||
|
if artwork_gallery is not None:
|
||||||
|
gallery_image_element_list: List[BeautifulSoup] = artwork_gallery.find_all("img", {"class": "artist-img"})
|
||||||
|
for gallery_image_element in gallery_image_element_list:
|
||||||
|
artist_artwork.push(Artwork(url=gallery_image_element.get("data-src", gallery_image_element.get("src"))))
|
||||||
|
|
||||||
|
return artist_artwork
|
||||||
|
|
||||||
def fetch_artist(self, source: Source, **kwargs) -> Artist:
|
def fetch_artist(self, source: Source, **kwargs) -> Artist:
|
||||||
"""
|
"""
|
||||||
TODO
|
TODO
|
||||||
@@ -1068,7 +1083,7 @@ class Musify(Page):
|
|||||||
|
|
||||||
artist = self._fetch_initial_artist(url, source=source, **kwargs)
|
artist = self._fetch_initial_artist(url, source=source, **kwargs)
|
||||||
self._fetch_artist_discography(artist, url, artist.name, **kwargs)
|
self._fetch_artist_discography(artist, url, artist.name, **kwargs)
|
||||||
|
self._fetch_artist_artwork(artist, **kwargs)
|
||||||
return artist
|
return artist
|
||||||
|
|
||||||
def fetch_label(self, source: Source, stop_at_level: int = 1) -> Label:
|
def fetch_label(self, source: Source, stop_at_level: int = 1) -> Label:
|
||||||
|
@@ -549,6 +549,11 @@ class YoutubeMusic(SuperYouTube):
|
|||||||
return album
|
return album
|
||||||
|
|
||||||
def fetch_lyrics(self, video_id: str, playlist_id: str = None) -> str:
|
def fetch_lyrics(self, video_id: str, playlist_id: str = None) -> str:
|
||||||
|
"""
|
||||||
|
1. fetches the tabs of a song, to get the browse id
|
||||||
|
2. finds the browse id of the lyrics
|
||||||
|
3. fetches the lyrics with the browse id
|
||||||
|
"""
|
||||||
request_data = {
|
request_data = {
|
||||||
"context": {**self.credentials.context, "adSignalsInfo": {"params": []}},
|
"context": {**self.credentials.context, "adSignalsInfo": {"params": []}},
|
||||||
"videoId": video_id,
|
"videoId": video_id,
|
||||||
@@ -575,7 +580,8 @@ class YoutubeMusic(SuperYouTube):
|
|||||||
pageType = traverse_json_path(tab, "tabRenderer.endpoint.browseEndpoint.browseEndpointContextSupportedConfigs.browseEndpointContextMusicConfig.pageType", default="")
|
pageType = traverse_json_path(tab, "tabRenderer.endpoint.browseEndpoint.browseEndpointContextSupportedConfigs.browseEndpointContextMusicConfig.pageType", default="")
|
||||||
if pageType in ("MUSIC_TAB_TYPE_LYRICS", "MUSIC_PAGE_TYPE_TRACK_LYRICS") or "lyrics" in pageType.lower():
|
if pageType in ("MUSIC_TAB_TYPE_LYRICS", "MUSIC_PAGE_TYPE_TRACK_LYRICS") or "lyrics" in pageType.lower():
|
||||||
browse_id = traverse_json_path(tab, "tabRenderer.endpoint.browseEndpoint.browseId", default=None)
|
browse_id = traverse_json_path(tab, "tabRenderer.endpoint.browseEndpoint.browseId", default=None)
|
||||||
break
|
if browse_id is not None:
|
||||||
|
break
|
||||||
|
|
||||||
if browse_id is None:
|
if browse_id is None:
|
||||||
return None
|
return None
|
||||||
@@ -721,7 +727,6 @@ class YoutubeMusic(SuperYouTube):
|
|||||||
|
|
||||||
self.download_values_by_url[source.url] = {
|
self.download_values_by_url[source.url] = {
|
||||||
"url": _best_format.get("url"),
|
"url": _best_format.get("url"),
|
||||||
"chunk_size": _best_format.get("downloader_options", {}).get("http_chunk_size", main_settings["chunk_size"]),
|
|
||||||
"headers": _best_format.get("http_headers", {}),
|
"headers": _best_format.get("http_headers", {}),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user