Skip to content

Commit d4a0c02

Browse files
authored
fromfilename plugin: proposed fix for #5218, some improvements (#5311)
### b5216a0 is a proposed fix for #5218 We don't assume anymore that if the pattern lacks the "artist" group it also has the "title" group (this was causing the "title" KeyError, when the pattern containg only the `?P<track>` group is used). Instead, we check for existence of "title" before assigning "title_field", otherwise we let the last pattern (which will always match) to assign it. The only slight drawback is that files like "01.mp3" will also get "01" as title (besides the "1" track number), instead of having no title, but I guess that is not going to cause any major problem in the rest of the import procedure (e.g. track matching after a search). On the other hand, I guess allowing a file to have no title would require a substantial rewriting of the plugin, since the empty string is in BAD_TITLE_PATTERNS. ### 0966042 adds a log message about the pattern being tried This is useful while debugging changes to the regexps in PATTERNS. I used loglevel "debug" for this message, should we use "debug" also for other messages (currently using level "info")? ### e6b7735 refactors the regexps in PATTERNS I reviewed the regexps (especially after the changes I made some time ago in 84cf336) and tried to make them cleaner. - Allow " - " and "-" as separator between track/artist/title fields: that should cover two common filename conventions: using spaces (e.g. `01 - Artist Name - Title of the song`) or not using spaces (e.g. `01-artist_name-title_of_the_song`). Some regexp groups are non-greedy, to avoid capturing unwanted leading/trailing spaces in artist/titles; we could think about some other enhancements, e.g. automatically converting underscores to spaces in artist/title names, but I guess the main use of the plugin is not to produce a perfectly formatted title, but a sufficient meaningful one to be used as reference in the following stages of the update procedure. - Allow `?P<tag>` groups by making them optional in the first two patterns (instead of having two versions of the pattern, with or without tag). BTW I'm not sure what these groups are about: we optionally check for them in the plugin, but we never use them to assign any metadata. - Allow optional "." after the track number - In the third pattern: also allow "_" as separator (e.g. for file names like `01_some_tack.mp3`)
2 parents 08d9f34 + 152cafb commit d4a0c02

File tree

3 files changed

+118
-14
lines changed

3 files changed

+118
-14
lines changed

beetsplug/fromfilename.py

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
# The above copyright notice and this permission notice shall be
1313
# included in all copies or substantial portions of the Software.
1414

15-
"""If the title is empty, try to extract track and title from the
16-
filename.
15+
"""If the title is empty, try to extract it from the filename
16+
(possibly also extract track and artist)
1717
"""
1818

1919
import os
@@ -25,12 +25,12 @@
2525
# Filename field extraction patterns.
2626
PATTERNS = [
2727
# Useful patterns.
28-
r"^(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$",
29-
r"^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)[\-_](?P<tag>.*)$",
30-
r"^(?P<artist>.+)[\-_](?P<title>.+)$",
31-
r"^(?P<track>\d+)[\s.\-_]+(?P<artist>.+)[\-_](?P<title>.+)$",
32-
r"^(?P<track>\d+)[\s.\-_]+(?P<title>.+)$",
33-
r"^(?P<track>\d+)\s+(?P<title>.+)$",
28+
(
29+
r"^(?P<track>\d+)\.?\s*-\s*(?P<artist>.+?)\s*-\s*(?P<title>.+?)"
30+
r"(\s*-\s*(?P<tag>.*))?$"
31+
),
32+
r"^(?P<artist>.+?)\s*-\s*(?P<title>.+?)(\s*-\s*(?P<tag>.*))?$",
33+
r"^(?P<track>\d+)\.?[\s_-]+(?P<title>.+)$",
3434
r"^(?P<title>.+) by (?P<artist>.+)$",
3535
r"^(?P<track>\d+).*$",
3636
r"^(?P<title>.+)$",
@@ -98,6 +98,7 @@ def apply_matches(d, log):
9898
# Given both an "artist" and "title" field, assume that one is
9999
# *actually* the artist, which must be uniform, and use the other
100100
# for the title. This, of course, won't work for VA albums.
101+
# Only check for "artist": patterns containing it, also contain "title"
101102
if "artist" in keys:
102103
if equal_fields(d, "artist"):
103104
artist = some_map["artist"]
@@ -113,15 +114,16 @@ def apply_matches(d, log):
113114
if not item.artist:
114115
item.artist = artist
115116
log.info("Artist replaced with: {.artist}", item)
116-
117-
# No artist field: remaining field is the title.
118-
else:
117+
# otherwise, if the pattern contains "title", use that for title_field
118+
elif "title" in keys:
119119
title_field = "title"
120+
else:
121+
title_field = None
120122

121-
# Apply the title and track.
123+
# Apply the title and track, if any.
122124
for item in d:
123-
if bad_title(item.title):
124-
item.title = str(d[item].get(title_field, ""))
125+
if title_field and bad_title(item.title):
126+
item.title = str(d[item][title_field])
125127
log.info("Title replaced with: {.title}", item)
126128

127129
if "track" in d[item] and item.track == 0:
@@ -160,6 +162,7 @@ def filename_task(self, task, session):
160162

161163
# Look for useful information in the filenames.
162164
for pattern in PATTERNS:
165+
self._log.debug(f"Trying pattern: {pattern}")
163166
d = all_matches(names, pattern)
164167
if d:
165168
apply_matches(d, self._log)

docs/changelog.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ Bug fixes:
4141
artists but not labels. :bug:`5366`
4242
- :doc:`plugins/chroma` :doc:`plugins/bpsync` Fix plugin loading issue caused by
4343
an import of another :class:`beets.plugins.BeetsPlugin` class. :bug:`6033`
44+
- :doc:`/plugins/fromfilename`: Fix :bug:`5218`, improve the code (refactor
45+
regexps, allow for more cases, add some logging), add tests.
4446

4547
For packagers:
4648

test/plugins/test_fromfilename.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# This file is part of beets.
2+
#
3+
# Permission is hereby granted, free of charge, to any person obtaining
4+
# a copy of this software and associated documentation files (the
5+
# "Software"), to deal in the Software without restriction, including
6+
# without limitation the rights to use, copy, modify, merge, publish,
7+
# distribute, sublicense, and/or sell copies of the Software, and to
8+
# permit persons to whom the Software is furnished to do so, subject to
9+
# the following conditions:
10+
#
11+
# The above copyright notice and this permission notice shall be
12+
# included in all copies or substantial portions of the Software.
13+
14+
"""Tests for the fromfilename plugin."""
15+
16+
import pytest
17+
18+
from beetsplug import fromfilename
19+
20+
21+
class Session:
22+
pass
23+
24+
25+
class Item:
26+
def __init__(self, path):
27+
self.path = path
28+
self.track = 0
29+
self.artist = ""
30+
self.title = ""
31+
32+
33+
class Task:
34+
def __init__(self, items):
35+
self.items = items
36+
self.is_album = True
37+
38+
39+
@pytest.mark.parametrize(
40+
"song1, song2",
41+
[
42+
(
43+
(
44+
"/tmp/01 - The Artist - Song One.m4a",
45+
1,
46+
"The Artist",
47+
"Song One",
48+
),
49+
(
50+
"/tmp/02. - The Artist - Song Two.m4a",
51+
2,
52+
"The Artist",
53+
"Song Two",
54+
),
55+
),
56+
(
57+
("/tmp/01-The_Artist-Song_One.m4a", 1, "The_Artist", "Song_One"),
58+
("/tmp/02.-The_Artist-Song_Two.m4a", 2, "The_Artist", "Song_Two"),
59+
),
60+
(
61+
("/tmp/01 - Song_One.m4a", 1, "", "Song_One"),
62+
("/tmp/02. - Song_Two.m4a", 2, "", "Song_Two"),
63+
),
64+
(
65+
("/tmp/Song One by The Artist.m4a", 0, "The Artist", "Song One"),
66+
("/tmp/Song Two by The Artist.m4a", 0, "The Artist", "Song Two"),
67+
),
68+
(("/tmp/01.m4a", 1, "", "01"), ("/tmp/02.m4a", 2, "", "02")),
69+
(
70+
("/tmp/Song One.m4a", 0, "", "Song One"),
71+
("/tmp/Song Two.m4a", 0, "", "Song Two"),
72+
),
73+
],
74+
)
75+
def test_fromfilename(song1, song2):
76+
"""
77+
Each "song" is a tuple of path, expected track number, expected artist,
78+
expected title.
79+
80+
We use two songs for each test for two reasons:
81+
- The plugin needs more than one item to look for uniform strings in paths
82+
in order to guess if the string describes an artist or a title.
83+
- Sometimes we allow for an optional "." after the track number in paths.
84+
"""
85+
86+
session = Session()
87+
item1 = Item(song1[0])
88+
item2 = Item(song2[0])
89+
task = Task([item1, item2])
90+
91+
f = fromfilename.FromFilenamePlugin()
92+
f.filename_task(task, session)
93+
94+
assert task.items[0].track == song1[1]
95+
assert task.items[0].artist == song1[2]
96+
assert task.items[0].title == song1[3]
97+
assert task.items[1].track == song2[1]
98+
assert task.items[1].artist == song2[2]
99+
assert task.items[1].title == song2[3]

0 commit comments

Comments
 (0)