Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
224 changes: 131 additions & 93 deletions beetsplug/fromfilename.py
Original file line number Diff line number Diff line change
@@ -1,60 +1,82 @@
# This file is part of beets.
# Copyright 2016, Jan-Erik Dahlin
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this header any more

# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

"""If the title is empty, try to extract it from the filename
(possibly also extract track and artist)
"""

from __future__ import annotations

import os
import re
from typing import TYPE_CHECKING
import typing

from beets import plugins
from beets.plugins import BeetsPlugin
from beets.util import displayable_path

if TYPE_CHECKING:
from collections.abc import Hashable, Iterable

if typing.TYPE_CHECKING:
from beets.importer import ImportSession, ImportTask
from beets.library import Item
from beets.logging import BeetsLogger as Logger

from ._typing import JSONDict


# Filename field extraction patterns.
PATTERNS = [
# Useful patterns.
(
r"^(?P<track>\d+)\.?\s*-\s*(?P<artist>.+?)\s*-\s*(?P<title>.+?)"
r"(\s*-\s*(?P<tag>.*))?$"
),
r"^(?P<artist>.+?)\s*-\s*(?P<title>.+?)(\s*-\s*(?P<tag>.*))?$",
r"^(?P<track>\d+)\.?[\s_-]+(?P<title>.+)$",
r"^(?P<title>.+) by (?P<artist>.+)$",
r"^(track ?)?(?P<track>\d+).*$",
r"^(?P<title>.+)$",
]

# Titles considered "empty" and in need of replacement.
BAD_TITLE_PATTERNS = [r"^$"]


def equal(seq: Iterable[Hashable]) -> bool:
# Filename field extraction patterns
RE_TRACK_INFO = re.compile(
r"""
(?P<disc>\d+(?=[\.\-_]\d))?
# a disc must be followed by punctuation and a digit
[\.\-]{,1}
# disc punctuation
(?P<track>\d+)?
# match the track number
[\.\-_\s]*
# artist separators
(?P<artist>.+?(?=[\s*_]?[\.\-by].+))?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[\.\-by] is a character class, so this lookahead matches any b or y in the name, not the word by. This is why 01. Hey Jude turns into artist He and title y Jude. The (?P<by>by)? group below then swallows these letters as well (02 Baby -> Ba).

# artist match depends on title existing
[\.\-_\s]*
(?P<by>by)?
# if 'by' is found, artist and title will need to be swapped
[\.\-_\s]*
# title separators
(?P<title>.+)?
# match the track title
""",
re.VERBOSE | re.IGNORECASE,
)
Comment on lines +32 to +53

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move the comments inline, like this?

Suggested change
RE_TRACK_INFO = re.compile(
r"""
(?P<disc>\d+(?=[\.\-_]\d))?
# a disc must be followed by punctuation and a digit
[\.\-]{,1}
# disc punctuation
(?P<track>\d+)?
# match the track number
[\.\-_\s]*
# artist separators
(?P<artist>.+?(?=[\s*_]?[\.\-by].+))?
# artist match depends on title existing
[\.\-_\s]*
(?P<by>by)?
# if 'by' is found, artist and title will need to be swapped
[\.\-_\s]*
# title separators
(?P<title>.+)?
# match the track title
""",
re.VERBOSE | re.IGNORECASE,
)
RE_TRACK_INFO = re.compile(
r"""
(?P<disc>\d+(?=[\.\-_]\d))? # a disc must be followed by punctuation and a digit
[\.\-]{,1} # disc punctuation
(?P<track>\d+)? # match the track number
[\.\-_\s]* # artist separators
(?P<artist>.+?(?=[\s*_]?[\.\-by].+))? # artist match depends on title existing
[\.\-_\s]*
(?P<by>by)? # if 'by' is found, artist and title will need to be swapped
[\.\-_\s]* # title separators
(?P<title>.+)? # match the track title
""", # noqa: E501
re.VERBOSE | re.IGNORECASE,
)


# Match the disc names of parent folders
RE_DISC = re.compile(r"((?:cd|disc)\s*\d+)", re.IGNORECASE)

# Matches fields that are empty or only whitespace
RE_BAD_TITLE = re.compile(r"^\s*$")


def equal(seq: list[str]) -> bool:
"""Determine whether a sequence holds identical elements."""
return len(set(seq)) <= 1


def equal_fields(matchdict: dict[Item, JSONDict], field: str) -> bool:
def equal_fields(
matchdict: dict[typing.Any, dict[str, str]], field: str
) -> bool:
"""Do all items in `matchdict`, whose values are dictionaries, have
the same value for `field`? (If they do, the field is probably not
the title.)
"""
return equal(m[field] for m in matchdict.values())
return equal(list(m[field] for m in matchdict.values()))


def all_matches(
names: dict[Item, str], pattern: str
) -> dict[Item, JSONDict] | None:
) -> dict[Item, dict[str, str]] | None:
"""If all the filenames in the item/filename mapping match the
pattern, return a dictionary mapping the items to dictionaries
giving the value for each named subpattern in the match. Otherwise,
Expand All @@ -77,63 +99,12 @@ def bad_title(title: str) -> bool:
"""Determine whether a given title is "bad" (empty or otherwise
meaningless) and in need of replacement.
"""
for pat in BAD_TITLE_PATTERNS:
if re.match(pat, title, re.IGNORECASE):
return True
if RE_BAD_TITLE.match(title):
return True
return False


def apply_matches(d: dict[Item, JSONDict], log: Logger) -> None:
"""Given a mapping from items to field dicts, apply the fields to
the objects.
"""
some_map = next(iter(d.values()))
keys = some_map.keys()

# Only proceed if the "tag" field is equal across all filenames.
if "tag" in keys and not equal_fields(d, "tag"):
return

# Given both an "artist" and "title" field, assume that one is
# *actually* the artist, which must be uniform, and use the other
# for the title. This, of course, won't work for VA albums.
# Only check for "artist": patterns containing it, also contain "title"
if "artist" in keys:
if equal_fields(d, "artist"):
artist = some_map["artist"]
title_field = "title"
elif equal_fields(d, "title"):
artist = some_map["title"]
title_field = "artist"
else:
# Both vary. Abort.
return

for item in d:
if not item.artist:
item.artist = artist
log.info("Artist replaced with: {.artist}", item)
# otherwise, if the pattern contains "title", use that for title_field
elif "title" in keys:
title_field = "title"
else:
title_field = None

# Apply the title and track, if any.
for item in d:
if title_field and bad_title(item.title):
item.title = str(d[item][title_field])
log.info("Title replaced with: {.title}", item)

if "track" in d[item] and item.track == 0:
item.track = int(d[item]["track"])
log.info("Track replaced with: {.track}", item)


# Plugin structure and hook into import process.


class FromFilenamePlugin(plugins.BeetsPlugin):
class FromFilenamePlugin(BeetsPlugin):
def __init__(self) -> None:
super().__init__()
self.register_listener("import_task_start", self.filename_task)
Expand All @@ -146,22 +117,89 @@ def filename_task(self, task: ImportTask, session: ImportSession) -> None:
same regex we can make an educated guess of which part of the
regex that contains the title.
"""
items = task.items
# Create the list of items to process
items: list[Item] = task.items

# Look for suspicious (empty or meaningless) titles.
missing_titles = sum(bad_title(i.title) for i in items)

if missing_titles:
# Get the base filenames (no path or extension).
names = {}
names: dict[Item, str] = {}
for item in items:
path = displayable_path(item.path)
name, _ = os.path.splitext(os.path.basename(path))
names[item] = name

# Look for useful information in the filenames.
for pattern in PATTERNS:
self._log.debug(f"Trying pattern: {pattern}")
d = all_matches(names, pattern)
if d:
apply_matches(d, self._log)
matches: dict[Item, dict[str, str]] = {}
for item, name in names.items():
m = self.parse_track_info(name)
matches[item] = m
self._apply_matches(matches)

def parse_track_info(self, text: str) -> dict[str, str]:
m = RE_TRACK_INFO.match(text)
assert m is not None
matches = m.groupdict()
# if the phrase "by" is matched, swap
# artist and title
if matches["by"]:
artist = matches["title"]
matches["title"] = matches["artist"]
matches["artist"] = artist
del matches["by"]
# if all fields except track are none
# set title to track - we can't be sure if it's the
# index or track number
if set(matches.values()) == {None, matches["track"]}:
matches["title"] = matches["track"]

return matches

def _apply_matches(self, d: dict[Item, dict[str, str]]) -> None:
"""Given a mapping from items to field dicts, apply the fields to
the objects.
"""
some_map = next(iter(d.values()))
keys = some_map.keys()

# Only proceed if the "tag" field is equal across all filenames.
if "tag" in keys and not equal_fields(d, "tag"):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the tag group is gone from the regex?

return

# Given both an "artist" and "title" field, assume that one is
# *actually* the artist, which must be uniform, and use the other
# for the title. This, of course, won't work for VA albums.
# Only check for "artist": patterns containing it, also contain "title"
if "artist" in keys:
if equal_fields(d, "artist"):
artist = some_map["artist"]
title_field = "title"
elif equal_fields(d, "title"):
artist = some_map["title"]
title_field = "artist"
else:
# Both vary. Abort.
return

for item in d:
if not item.artist and artist:
item.artist = artist
self._log.info(f"Artist replaced with: {item.artist}")
# otherwise, if the pattern contains "title", use that for title_field
elif "title" in keys:
title_field = "title"
else:
title_field = None

# Apply the title and track, if any.
for item in d:
if title_field and bad_title(item.title):
item.title = str(d[item][title_field])
self._log.info(f"Title replaced with: {item.title}")

if "track" in d[item] and item.track == 0:
if d[item]["track"]:
item.track = int(d[item]["track"])
self._log.info(f"Track replaced with: {item.track}")
85 changes: 81 additions & 4 deletions test/plugins/test_fromfilename.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,73 @@ def __init__(self, items):
self.is_album = True


@pytest.mark.parametrize(
"text,matchgroup",
[
("3", {"disc": None, "track": "3", "artist": None, "title": "3"}),
("04", {"disc": None, "track": "04", "artist": None, "title": "04"}),
("6.", {"disc": None, "track": "6", "artist": None, "title": "6"}),
("3.5", {"disc": "3", "track": "5", "artist": None, "title": None}),
("1-02", {"disc": "1", "track": "02", "artist": None, "title": None}),
("100-4", {"disc": "100", "track": "4", "artist": None, "title": None}),
(
"04.Title",
{"disc": None, "track": "04", "artist": None, "title": "Title"},
),
(
"5_-_Title",
{"disc": None, "track": "5", "artist": None, "title": "Title"},
),
(
"1-02 Title",
{"disc": "1", "track": "02", "artist": None, "title": "Title"},
),
(
"3.5 - Title",
{"disc": "3", "track": "5", "artist": None, "title": "Title"},
),
(
"5_-_Artist_-_Title",
{"disc": None, "track": "5", "artist": "Artist", "title": "Title"},
),
(
"3-8- Artist-Title",
{"disc": "3", "track": "8", "artist": "Artist", "title": "Title"},
),
(
"4-3 - Artist Name - Title",
{
"disc": "4",
"track": "3",
"artist": "Artist Name",
"title": "Title",
},
),
(
"4-3_-_Artist_Name_-_Title",
{
"disc": "4",
"track": "3",
"artist": "Artist_Name",
"title": "Title",
},
),
(
"6 Title by Artist",
{"disc": None, "track": "6", "artist": "Artist", "title": "Title"},
),
(
"Title",
{"disc": None, "track": None, "artist": None, "title": "Title"},
),
],
)
def test_parse_track_info(text, matchgroup):
f = fromfilename.FromFilenamePlugin()
m = f.parse_track_info(text)
assert matchgroup == m


@pytest.mark.parametrize(
"song1, song2",
[
Expand All @@ -40,6 +107,20 @@ def __init__(self, items):
"Song Two",
),
),
(
(
"/tmp/01 The Artist - Song One.m4a",
1,
"The Artist",
"Song One",
),
(
"/tmp/02 The Artist - Song Two.m4a",
2,
"The Artist",
"Song Two",
),
),
(
("/tmp/01-The_Artist-Song_One.m4a", 1, "The_Artist", "Song_One"),
("/tmp/02.-The_Artist-Song_Two.m4a", 2, "The_Artist", "Song_Two"),
Expand All @@ -57,10 +138,6 @@ def __init__(self, items):
("/tmp/Song One.m4a", 0, "", "Song One"),
("/tmp/Song Two.m4a", 0, "", "Song Two"),
),
(
("/tmp/track01.m4a", 1, "", "track01"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are these two removed?

("/tmp/track 2.m4a", 2, "", "track 2"),
),
],
)
def test_fromfilename(song1, song2):
Expand Down
Loading