Debian Codegraph @

beetsplug/random.py

raw
1 from __future__ import annotations
2
3 import random
4 from itertools import groupby, islice
5 from operator import methodcaller
6 from typing import TYPE_CHECKING, Protocol, TypeVar
7
8 from beets.plugins import BeetsPlugin
9 from beets.ui import Subcommand, print_
10
11 if TYPE_CHECKING:
12 from collections.abc import Iterable, Iterator
13
14 from beets.library import LibModel, Library
15
16 RandomModel = TypeVar("RandomModel", bound=LibModel)
17
18
19 class RandomCLIOpts(Protocol):
20 album: bool
21 equal_chance: bool
22 field: str
23 number: int
24 time: float | None
25
26
27 def random_func(lib: Library, opts: RandomCLIOpts, args: list[str]) -> None:
28 """Select some random items or albums and print the results."""
29 # Fetch all the objects matching the query into a list.
30 objs = lib.albums(args) if opts.album else lib.items(args)
31
32 # Print a random subset.
33 for obj in random_objs(
34 objs=objs,
35 equal_chance_field=opts.field,
36 number=opts.number,
37 time_minutes=opts.time,
38 equal_chance=opts.equal_chance,
39 ):
40 print_(format(obj))
41
42
43 random_cmd = Subcommand("random", help="choose a random track or album")
44 random_cmd.parser.add_option(
45 "-n",
46 "--number",
47 action="store",
48 type="int",
49 help="number of objects to choose",
50 default=1,
51 )
52 random_cmd.parser.add_option(
53 "-e",
54 "--equal-chance",
55 action="store_true",
56 default=False,
57 help="each field has the same chance",
58 )
59 random_cmd.parser.add_option(
60 "-t",
61 "--time",
62 action="store",
63 type="float",
64 help="total length in minutes of objects to choose",
65 )
66 random_cmd.parser.add_option(
67 "--field",
68 action="store",
69 type="string",
70 default="albumartist",
71 help="field to use for equal chance sampling (default: albumartist)",
72 )
73 random_cmd.parser.add_all_common_options()
74 random_cmd.func = random_func
75
76
77 class Random(BeetsPlugin):
78 def commands(self) -> list[Subcommand]:
79 return [random_cmd]
80
81
82 def _equal_chance_permutation(
83 objs: Iterable[RandomModel], field: str
84 ) -> Iterator[RandomModel]:
85 """Generate (lazily) a permutation of the objects where every group
86 with equal values for `field` have an equal chance of appearing in
87 any given position.
88 """
89 # Group the objects by field so we can sample from them.
90 get_attr = methodcaller("get", field)
91
92 groups = {}
93 for k, values in groupby(sorted(objs, key=get_attr), key=get_attr):
94 if k is not None:
95 vals = list(values)
96 # shuffle in category
97 random.shuffle(vals)
98 groups[str(k)] = vals
99
100 while groups:
101 group = random.choice(list(groups.keys()))
102 yield groups[group].pop()
103 if not groups[group]:
104 del groups[group]
105
106
107 def _take_time(
108 iter_: Iterable[RandomModel], secs: float
109 ) -> Iterator[RandomModel]:
110 """Yield objects without exceeding the requested total duration."""
111 total_time = 0.0
112 for obj in iter_:
113 length = obj.length
114 if total_time + length <= secs:
115 yield obj
116 total_time += length
117
118
119 def random_objs(
120 objs: Iterable[RandomModel],
121 equal_chance_field: str,
122 number: int = 1,
123 time_minutes: float | None = None,
124 equal_chance: bool = False,
125 ) -> Iterator[RandomModel]:
126 """Get a random subset of items, optionally constrained by time or count.
127
128 Args:
129 - objs: The sequence of objects to choose from.
130 - number: The number of objects to select.
131 - time_minutes: If specified, the total length of selected objects
132 should not exceed this many minutes.
133 - equal_chance: If True, each field has the same chance of being
134 selected, regardless of how many tracks they have.
135 - random_gen: An optional random generator to use for shuffling.
136 """
137 # Permute the objects either in a straightforward way or an
138 # field-balanced way.
139 perm: Iterable[RandomModel]
140 if equal_chance:
141 perm = _equal_chance_permutation(objs, equal_chance_field)
142 else:
143 perm = list(objs)
144 random.shuffle(perm)
145
146 # Select objects by time our count.
147 if time_minutes:
148 return _take_time(perm, time_minutes * 60)
149 return islice(perm, number)