Debian Codegraph @

beetsplug/fromfilename.py

raw
1 """If the title is empty, try to extract it from the filename
2 (possibly also extract track and artist)
3 """
4
5 from __future__ import annotations
6
7 import os
8 import re
9 from typing import TYPE_CHECKING
10
11 from beets import plugins
12 from beets.util import displayable_path
13
14 if TYPE_CHECKING:
15 from collections.abc import Hashable, Iterable
16
17 from beets.importer import ImportSession, ImportTask
18 from beets.library import Item
19 from beets.logging import BeetsLogger as Logger
20
21 from ._typing import JSONDict
22
23
24 # Filename field extraction patterns.
25 PATTERNS = [
26 # Useful patterns.
27 (
28 r"^(?P<track>\d+)\.?\s*-\s*(?P<artist>.+?)\s*-\s*(?P<title>.+?)"
29 r"(\s*-\s*(?P<tag>.*))?$"
30 ),
31 r"^(?P<artist>.+?)\s*-\s*(?P<title>.+?)(\s*-\s*(?P<tag>.*))?$",
32 r"^(?P<track>\d+)\.?[\s_-]+(?P<title>.+)$",
33 r"^(?P<title>.+) by (?P<artist>.+)$",
34 r"^(track ?)?(?P<track>\d+).*$",
35 r"^(?P<title>.+)$",
36 ]
37
38 # Titles considered "empty" and in need of replacement.
39 BAD_TITLE_PATTERNS = [r"^$"]
40
41
42 def equal(seq: Iterable[Hashable]) -> bool:
43 """Determine whether a sequence holds identical elements."""
44 return len(set(seq)) <= 1
45
46
47 def equal_fields(matchdict: dict[Item, JSONDict], field: str) -> bool:
48 """Do all items in `matchdict`, whose values are dictionaries, have
49 the same value for `field`? (If they do, the field is probably not
50 the title.)
51 """
52 return equal(m[field] for m in matchdict.values())
53
54
55 def all_matches(
56 names: dict[Item, str], pattern: str
57 ) -> dict[Item, JSONDict] | None:
58 """If all the filenames in the item/filename mapping match the
59 pattern, return a dictionary mapping the items to dictionaries
60 giving the value for each named subpattern in the match. Otherwise,
61 return None.
62 """
63 matches = {}
64 for item, name in names.items():
65 m = re.match(pattern, name, re.IGNORECASE)
66 if m and m.groupdict():
67 # Only yield a match when the regex applies *and* has
68 # capture groups. Otherwise, no information can be extracted
69 # from the filename.
70 matches[item] = m.groupdict()
71 else:
72 return None
73 return matches
74
75
76 def bad_title(title: str) -> bool:
77 """Determine whether a given title is "bad" (empty or otherwise
78 meaningless) and in need of replacement.
79 """
80 for pat in BAD_TITLE_PATTERNS:
81 if re.match(pat, title, re.IGNORECASE):
82 return True
83 return False
84
85
86 def apply_matches(d: dict[Item, JSONDict], log: Logger) -> None:
87 """Given a mapping from items to field dicts, apply the fields to
88 the objects.
89 """
90 some_map = next(iter(d.values()))
91 keys = some_map.keys()
92
93 # Only proceed if the "tag" field is equal across all filenames.
94 if "tag" in keys and not equal_fields(d, "tag"):
95 return
96
97 # Given both an "artist" and "title" field, assume that one is
98 # *actually* the artist, which must be uniform, and use the other
99 # for the title. This, of course, won't work for VA albums.
100 # Only check for "artist": patterns containing it, also contain "title"
101 if "artist" in keys:
102 if equal_fields(d, "artist"):
103 artist = some_map["artist"]
104 title_field = "title"
105 elif equal_fields(d, "title"):
106 artist = some_map["title"]
107 title_field = "artist"
108 else:
109 # Both vary. Abort.
110 return
111
112 for item in d:
113 if not item.artist:
114 item.artist = artist
115 log.info("Artist replaced with: {.artist}", item)
116 # otherwise, if the pattern contains "title", use that for title_field
117 elif "title" in keys:
118 title_field = "title"
119 else:
120 title_field = None
121
122 # Apply the title and track, if any.
123 for item in d:
124 if title_field and bad_title(item.title):
125 item.title = str(d[item][title_field])
126 log.info("Title replaced with: {.title}", item)
127
128 if "track" in d[item] and item.track == 0:
129 item.track = int(d[item]["track"])
130 log.info("Track replaced with: {.track}", item)
131
132
133 # Plugin structure and hook into import process.
134
135
136 class FromFilenamePlugin(plugins.BeetsPlugin):
137 def __init__(self) -> None:
138 super().__init__()
139 self.register_listener("import_task_start", self.filename_task)
140
141 def filename_task(self, task: ImportTask, session: ImportSession) -> None:
142 """Examine each item in the task to see if we can extract a title
143 from the filename. Try to match all filenames to a number of
144 regexps, starting with the most complex patterns and successively
145 trying less complex patterns. As soon as all filenames match the
146 same regex we can make an educated guess of which part of the
147 regex that contains the title.
148 """
149 items = task.items
150
151 # Look for suspicious (empty or meaningless) titles.
152 missing_titles = sum(bad_title(i.title) for i in items)
153
154 if missing_titles:
155 # Get the base filenames (no path or extension).
156 names = {}
157 for item in items:
158 path = displayable_path(item.path)
159 name, _ = os.path.splitext(os.path.basename(path))
160 names[item] = name
161
162 # Look for useful information in the filenames.
163 for pattern in PATTERNS:
164 self._log.debug(f"Trying pattern: {pattern}")
165 d = all_matches(names, pattern)
166 if d:
167 apply_matches(d, self._log)