Skip to content

Commit

Permalink
internal: Use sourcery to optimise various bits and bots
Browse files Browse the repository at this point in the history
  • Loading branch information
snejus committed Dec 10, 2024
1 parent c531ce0 commit 190fa0d
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 80 deletions.
12 changes: 4 additions & 8 deletions beetsplug/bandcamp/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,7 @@ def loaded(self) -> None:

@classmethod
def parse_label_url(cls, text: str) -> str | None:
if m := cls.LABEL_URL_IN_COMMENT.search(text):
return m[1]

return None
return m[1] if (m := cls.LABEL_URL_IN_COMMENT.search(text)) else None

def _find_url_in_item(self, item: Item, name: str, _type: CandidateType) -> str:
"""Try to extract release URL from the library item.
Expand Down Expand Up @@ -418,12 +415,11 @@ def main() -> None:
pl = BandcampPlugin()
pl._log.setLevel(10)
url = args.release_url
result = pl.get_album_info(args.release_url) or pl.get_track_info(url)
if not result:
if result := pl.get_album_info(args.release_url) or pl.get_track_info(url):
print(json.dumps(result))
else:
raise AssertionError("Failed to find a release under the given url")

print(json.dumps(result))


if __name__ == "__main__":
main()
10 changes: 2 additions & 8 deletions beetsplug/bandcamp/album_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,7 @@ def from_title(self) -> str | None:
if m := self.QUOTED_ALBUM.search(self.original):
return m.expand(r"\2\3")

if m := self.EPLP_ALBUM.search(self.original):
return m.group()

return None
return m.group() if (m := self.EPLP_ALBUM.search(self.original)) else None

@cached_property
def album_names(self) -> list[str]:
Expand Down Expand Up @@ -251,10 +248,7 @@ def check_eplp(self, album: str) -> str:
else:
m = self.EPLP_ALBUM_LINE.search(self.description)

if m:
return m.group()

return album
return m.group() if m else album

def get(
self,
Expand Down
2 changes: 1 addition & 1 deletion beetsplug/bandcamp/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def valid_format(obj: JSONDict) -> bool:
# musicReleaseFormat format is given or it is a USB
and ("musicReleaseFormat" in obj or obj["type_id"] == USB_TYPE_ID)
# it is not a vinyl bundle
and not (obj["item_type"] == "p" and "bundle" in obj["name"].lower())
and (obj["item_type"] != "p" or "bundle" not in obj["name"].lower())
)

valid_formats = filter(valid_format, map(Helpers.unpack_props, format_list))
Expand Down
32 changes: 12 additions & 20 deletions beetsplug/bandcamp/metaguru.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,13 +206,14 @@ def release_date(self) -> date | None:
If the field is not found, return None.
"""
dt = self.meta.get("datePublished") or self.meta.get("dateModified")
if not dt:
return None
if dt := self.meta.get("datePublished") or self.meta.get("dateModified"):
return (
datetime.strptime(dt[:11], "%d %b %Y")
.replace(tzinfo=timezone.utc)
.date()
)

return (
datetime.strptime(dt[:11], "%d %b %Y").replace(tzinfo=timezone.utc).date()
)
return None

@cached_property
def albumstatus(self) -> str:
Expand Down Expand Up @@ -264,9 +265,7 @@ def tracks(self) -> Tracks:
def unique_artists(self) -> list[str]:
"""Return all unique artists in the release ignoring differences in case."""
artists = self.split_artists(self._tracks.artists)
if len(set(map(str.lower, artists))) == 1:
return artists[:1]
return artists
return artists[:1] if len(set(map(str.lower, artists))) == 1 else artists

@cached_property
def track_count(self) -> int:
Expand Down Expand Up @@ -296,10 +295,7 @@ def albumartist(self) -> str:

aartist = self.preliminary_albumartist
if aartist and (set(self.split_artists(aartist)) <= set(self.unique_artists)):
if "remix" in aartist:
return self.remove_ft(aartist)
return aartist

return self.remove_ft(aartist) if "remix" in aartist else aartist
if len(self.tracks.original_artists) == 1:
return self.tracks.original_artists[0]

Expand Down Expand Up @@ -414,10 +410,7 @@ def albumtype(self) -> str:
return "ep"
if self.is_single_album:
return "single"
if self.is_comp:
return "compilation"

return "album"
return "compilation" if self.is_comp else "album"

@cached_property
def albumtypes(self) -> list[str]:
Expand All @@ -439,7 +432,7 @@ def albumtypes(self) -> list[str]:
if word in self.original_album.lower():
albumtypes.add(word.replace("rmx", "remix").replace("edits", "remix"))

if sum(1 for t in self._tracks if t.remix and t.remix.valid) >= max(
if sum(bool(t.remix and t.remix.valid) for t in self._tracks) >= max(
self.track_count - 1, 1
):
albumtypes.add("remix")
Expand Down Expand Up @@ -522,8 +515,7 @@ def _common_album(self) -> JSONDict:
"artists",
]
common_data.update(self.get_fields(fields))
reldate = self.release_date
if reldate:
if reldate := self.release_date:
common_data.update(self.get_fields(["year", "month", "day"], reldate))

return common_data
Expand Down
2 changes: 1 addition & 1 deletion beetsplug/bandcamp/names.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ def ensure_artist_first(self, names: list[str]) -> list[str]:
)
)
# or there are at least 2 remixes on the left side of the delimiter
or sum(1 for x in left if Remix.PATTERN.search(x)) > 1
or sum(bool(Remix.PATTERN.search(x)) for x in left) > 1
)
):
return [f"{a} - {t}" for t, a in splits]
Expand Down
12 changes: 5 additions & 7 deletions beetsplug/bandcamp/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def get_matches(text: str) -> JSONDict:
"""Reduce matches from all patterns into a single dictionary."""
result: JSONDict = {}
for pat in RELEASE_PATTERNS:
m = pat.search(text)
if m:
if m := pat.search(text):
result = {**m.groupdict(), **result}
if "type" in result:
result["type"] = result["type"].lower()
Expand All @@ -84,11 +83,10 @@ def parse_and_sort_results(html: str, **kwargs: str) -> list[JSONDict]:
"""
results: list[JSONDict] = []
for block in html.split("searchresult data-search")[1:]:
similarities = []
res = get_matches(block)
for field, query in kwargs.items():
similarities.append(get_similarity(query, res.get(field, "")))

similarities = [
get_similarity(query, res.get(field, "")) for field, query in kwargs.items()
]
res["similarity"] = round(sum(similarities) / len(similarities), 3)
results.append(res)
results = sorted(results, key=itemgetter("similarity"), reverse=True)
Expand All @@ -105,6 +103,6 @@ def search_bandcamp(
"""Return a list with item JSONs of type search_type matching the query."""
url = SEARCH_URL.format(page, quote_plus(query))
if search_type:
url += "&item_type=" + search_type
url += f"&item_type={search_type}"
kwargs["name"] = query
return parse_and_sort_results(get(url), **kwargs)
17 changes: 4 additions & 13 deletions beetsplug/bandcamp/track.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ class Remix:

@classmethod
def from_name(cls, name: str) -> Remix | None:
m = cls.PATTERN.search(name)
if m:
if m := cls.PATTERN.search(name):
remix: dict[str, Any] = m.groupdict()
remix["start"] = remix["start"] is not None
remix["end"] = remix["end"] is not None
Expand Down Expand Up @@ -168,17 +167,11 @@ def parse_name(cls, name: str, artist: str, index: int | None) -> JSONDict:
artist = Helpers.clean_name(artist)
name = Helpers.clean_name(name).strip()

# find the track_alt and remove it from the name
m = cls.TRACK_ALT_PAT.search(name)
if m:
if m := cls.TRACK_ALT_PAT.search(name):
result["track_alt"] = m.group(1).replace(".", "").upper()
name = name.replace(m.group(), "")

# check whether track name contains the catalog number within parens
# or square brackets
# see https://objection999x.bandcamp.com/album/eruption-va-obj012
m = Catalognum.delimited.search(name)
if m:
if m := Catalognum.delimited.search(name):
result["catalognum"] = m.group(1)
name = name.replace(m.group(), "").strip()

Expand All @@ -187,9 +180,7 @@ def parse_name(cls, name: str, artist: str, index: int | None) -> JSONDict:
name = re.sub(rf"^0?{index}\W\W+", "", name)
result["medium_index"] = index

# find the remixer and remove it from the name
remix = Remix.from_name(name)
if remix:
if remix := Remix.from_name(name):
result["remix"] = remix
if remix.start:
name = name.removeprefix(remix.full).strip()
Expand Down
7 changes: 4 additions & 3 deletions tests/test_genre.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ def modes_spec():
"double_word_valid_separately": False,
"only_last_word_valid": False,
}
modes = {}
modes["classical"] = base_spec
modes["progressive"] = {**base_spec, "double_word_valid_separately": True}
modes = {
"classical": base_spec,
"progressive": {**base_spec, "double_word_valid_separately": True},
}
modes["psychedelic"] = {**modes["progressive"], "only_last_word_valid": True}
return modes

Expand Down
34 changes: 15 additions & 19 deletions tests/test_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ def make(cls, field: str, old: Any, new: Any, *args: Any) -> Field:

@cached_property
def changed(self) -> bool:
return bool(self.new != self.old)
return self.new != self.old

@cached_property
def diff(self) -> FieldDiff:
Expand Down Expand Up @@ -261,30 +261,26 @@ def _report(

columns = []
for name, all_changes, color in sections:
album_panels = []
if include_fields:
changes = [(u, d) for u, d in all_changes if d.field in include_fields]
else:
changes = all_changes
changes.sort(key=FIRST_ITEM)
for url, diffs in groupby(changes, FIRST_ITEM):
album_panels.append(
border_panel(
new_table(
rows=[
(f"[b dim]{diff.field}[/]", str(diff))
for _, diff in diffs
]
),
title=f"[dim]{url}[/]",
title_align="right",
subtitle_align="right",
border_style="dim",
box=box.DOUBLE,
)
if album_panels := [
border_panel(
new_table(
rows=[
(f"[b dim]{diff.field}[/]", str(diff)) for _, diff in diffs
]
),
title=f"[dim]{url}[/]",
title_align="right",
subtitle_align="right",
border_style="dim",
box=box.DOUBLE,
)

if album_panels:
for url, diffs in groupby(changes, FIRST_ITEM)
]:
columns.append(
border_panel(
list_table(album_panels),
Expand Down

0 comments on commit 190fa0d

Please sign in to comment.