Skip to main content

music21/corpus/
work.rs

1//! The core corpus's directories and the works in each: music21's
2//! `corpus.work` and `Corpus.getComposer`.
3
4use std::path::{Path, PathBuf};
5
6use crate::common::formats::find_format;
7use crate::common::stringtools::{space_camel_case, title_case};
8
9/// What music21 keeps together when it spaces a camel-cased name.
10const KEPT_TOGETHER: [&str; 1] = ["PMFC"];
11
12/// One directory of the corpus: its name on disk, the composer or
13/// collection it holds, and whether that is a composer.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct Directory {
16    /// The directory's name.
17    pub name: &'static str,
18    /// The composer's or collection's name.
19    pub title: &'static str,
20    /// Whether the directory holds one composer's works.
21    pub holds: Holder,
22}
23
24/// Whose works a directory holds.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub enum Holder {
27    /// One composer's.
28    Composer,
29    /// A collection's, of several or unknown composers.
30    Collection,
31}
32
33const fn composer(name: &'static str, title: &'static str) -> Directory {
34    Directory {
35        name,
36        title,
37        holds: Holder::Composer,
38    }
39}
40
41const fn collection(name: &'static str, title: &'static str) -> Directory {
42    Directory {
43        name,
44        title,
45        holds: Holder::Collection,
46    }
47}
48
49/// The core corpus's directories, in music21's order: its
50/// `CoreCorpus._directoryInformation`.
51pub const CORE_DIRECTORIES: [Directory; 35] = [
52    collection("airdsAirs", "Aird's Airs"),
53    composer("bach", "Johann Sebastian Bach"),
54    composer("beach", "Amy Beach"),
55    composer("beethoven", "Ludwig van Beethoven"),
56    composer("chopin", "Frederic Chopin"),
57    composer("ciconia", "Johannes Ciconia"),
58    composer("corelli", "Arcangelo Corelli"),
59    composer("cpebach", "C.P.E. Bach"),
60    collection("demos", "Demonstration Files"),
61    collection("essenFolksong", "Essen Folksong Collection"),
62    composer("handel", "George Frideric Handel"),
63    composer("haydn", "Joseph Haydn"),
64    composer("joplin", "Scott Joplin"),
65    composer("johnson_j_r", "J. Rosamund Johnson"),
66    composer("josquin", "Josquin des Prez"),
67    collection("leadSheet", "Leadsheet demos"),
68    composer("liliuokalani", "Queen Liliʻuokalani"),
69    composer("luca", "D. Luca"),
70    composer("lusitano", "Vicente Lusitano"),
71    collection("miscFolk", "Miscellaneous Folk"),
72    composer("monteverdi", "Claudio Monteverdi"),
73    composer("mozart", "Wolfgang Amadeus Mozart"),
74    collection("nottingham-dataset", "Nottingham Music Database (partial)"),
75    collection("oneills1850", "Oneill's 1850 Collection"),
76    composer("palestrina", "Giovanni Palestrina"),
77    collection("ryansMammoth", "Ryan's Mammoth Collection"),
78    composer("schoenberg", "Arnold Schoenberg"),
79    composer("schubert", "Franz Schubert"),
80    composer("schumann_robert", "Robert Schumann"),
81    composer("schumann_clara", "Clara Schumann"),
82    collection("theoryExercises", "Theory Exercises"),
83    collection("trecento", "Fourteenth-Century Italian Music"),
84    composer("verdi", "Giuseppe Verdi"),
85    composer("weber", "Carl Maria von Weber"),
86    composer("webern", "Anton Webern"),
87];
88
89/// One file of a work: music21's `CorpusFile`.
90#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct CorpusFile {
92    /// The path under the corpus, from the directory on.
93    pub path: String,
94    /// A title made from the file's name.
95    pub title: String,
96    /// The file's name.
97    pub filename: String,
98    /// The file's format.
99    pub format: &'static str,
100    /// The file's extension, with its dot.
101    pub ext: String,
102}
103
104/// A work of a directory and its files: music21's `CorpusWork`.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct CorpusWork {
107    /// The work's name on disk: the subdirectory, or the file without its
108    /// extension.
109    pub stub: String,
110    /// A title made from the stub.
111    pub title: String,
112    /// The work's files, in the order given.
113    pub files: Vec<CorpusFile>,
114}
115
116/// The paths that belong to a composer or collection: those with a part,
117/// or a part's name before its last dot, of that name, ignoring case.
118/// Sorted, as music21's `getComposer` answers them.
119///
120/// ```
121/// use std::path::PathBuf;
122/// use music21::corpus::work::composer_paths;
123///
124/// let paths = [PathBuf::from("/c/bach/bwv66.6.mxl"), PathBuf::from("/c/beach/x.mxl")];
125/// assert_eq!(composer_paths("Bach", &paths), [PathBuf::from("/c/bach/bwv66.6.mxl")]);
126/// ```
127pub fn composer_paths(name: &str, paths: &[PathBuf]) -> Vec<PathBuf> {
128    let name = name.to_lowercase();
129    let mut found: Vec<PathBuf> = paths
130        .iter()
131        .filter(|path| names_composer(path, &name))
132        .cloned()
133        .collect();
134    found.sort();
135    found
136}
137
138fn names_composer(path: &Path, name: &str) -> bool {
139    path.components().any(|part| {
140        let part = part.as_os_str().to_string_lossy().to_lowercase();
141        if part == name {
142            return true;
143        }
144        match part.rsplit_once('.') {
145            Some((stem, _)) => stem == name,
146            None => false,
147        }
148    })
149}
150
151/// The works a directory's files make, in the order their files first come:
152/// music21's `DirectoryInformation.findWorks`. A file is placed after the
153/// first place the directory's name appears in its path; a file whose
154/// format is not known is left out.
155///
156/// ```
157/// use std::path::PathBuf;
158/// use music21::corpus::work::find_works;
159///
160/// let paths = [
161///     PathBuf::from("/c/schoenberg/opus19/movement2.mxl"),
162///     PathBuf::from("/c/schoenberg/opus19/movement6.mxl"),
163/// ];
164/// let works = find_works("schoenberg", &paths);
165/// assert_eq!(works[0].title, "Opus 19");
166/// assert_eq!(works[0].files[1].path, "schoenberg/opus19/movement6.mxl");
167/// assert_eq!(works[0].files[1].title, "Movement 6");
168/// ```
169pub fn find_works(directory: &str, paths: &[PathBuf]) -> Vec<CorpusWork> {
170    let mut works: Vec<CorpusWork> = Vec::new();
171    for path in paths {
172        let text = path.to_string_lossy();
173        let Some((_, stub)) = text.split_once(directory) else {
174            continue;
175        };
176        // Windows takes either separator, and a path can mix them.
177        let separators = ['/', std::path::MAIN_SEPARATOR];
178        let stub = stub.strip_prefix(separators).unwrap_or(stub);
179        let components: Vec<&str> = stub.split(separators).collect();
180        let filename = components.last().copied().unwrap_or_default();
181        let ext = suffix(filename);
182        let Some(format) = find_format(ext).0 else {
183            continue;
184        };
185
186        // The work is the first component, a file's extension removed.
187        let work_stub = components[0].replace(ext, "");
188        let at = match works.iter().position(|work| work.stub == work_stub) {
189            Some(at) => at,
190            None => {
191                works.push(CorpusWork {
192                    title: titled(&work_stub),
193                    stub: work_stub,
194                    files: Vec::new(),
195                });
196                works.len() - 1
197            }
198        };
199        works[at].files.push(CorpusFile {
200            // A corpus path, written with '/' on every platform.
201            path: format!("{directory}/{}", components.join("/")),
202            title: titled(&filename.replace(ext, "")),
203            filename: filename.to_string(),
204            format,
205            ext: ext.to_string(),
206        });
207    }
208    works
209}
210
211/// A name spaced at its case changes and numbers, in title case.
212fn titled(name: &str) -> String {
213    title_case(&space_camel_case(name, true, &KEPT_TOGETHER))
214}
215
216/// A file name's extension with its dot, as `pathlib`'s `suffix` finds it.
217fn suffix(name: &str) -> &str {
218    match name.rfind('.') {
219        Some(at) if at > 0 && at + 1 < name.len() => &name[at..],
220        _ => "",
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn a_file_named_like_the_composer_is_found() {
230        let paths = [
231            PathBuf::from("/c/demos/bach.krn"),
232            PathBuf::from("/c/demos/x.krn"),
233        ];
234        assert_eq!(
235            composer_paths("bach", &paths),
236            [PathBuf::from("/c/demos/bach.krn")]
237        );
238    }
239
240    #[test]
241    fn a_file_of_no_known_format_makes_no_work() {
242        let paths = [
243            PathBuf::from("/c/verdi/score.pdf"),
244            PathBuf::from("/c/verdi/x"),
245        ];
246        assert!(find_works("verdi", &paths).is_empty());
247    }
248
249    #[test]
250    fn a_file_at_the_top_is_a_work_of_its_own() {
251        let works = find_works("beach", &[PathBuf::from("/c/beach/prayer.mxl")]);
252        assert_eq!(works[0].stub, "prayer");
253        assert_eq!(works[0].files[0].ext, ".mxl");
254    }
255}