Skip to main content

music21/metadata/
rich.rs

1//! Metadata with what was found in the score it heads: music21's
2//! `RichMetadata`, which its corpus cache keeps for every work.
3//!
4//! Beside a score's own metadata it holds thirteen values read off the
5//! score itself -- the meters, keys and tempos in it, how many notes and
6//! parts, its range, how long it is and where it lives in the corpus -- so
7//! the corpus can be searched by them without reading any score.
8
9use std::borrow::Cow;
10use std::path::Path;
11
12use super::{
13    Metadata, contributor_answers_to, is_contributor_unique_name, namespace_name, old_work_id,
14    unique_name_of_field,
15};
16use crate::common::numbertools::{OffsetQL, op_frac};
17use crate::defaults::IntegerType;
18use crate::error::Result;
19use crate::interval::Interval;
20use crate::stream::{Stream, StreamElement};
21
22/// The names of the values read off the score: music21's
23/// `additionalRichMetadataAttributes`, sorted.
24pub const RICH_ATTRIBUTES: [&str; 13] = [
25    "ambitus",
26    "keySignatureFirst",
27    "keySignatures",
28    "noteCount",
29    "numberOfParts",
30    "pitchHighest",
31    "pitchLowest",
32    "scoreQuarterLength",
33    "sourcePath",
34    "tempoFirst",
35    "tempos",
36    "timeSignatureFirst",
37    "timeSignatures",
38];
39
40/// A score's range as a few plain values: music21's `AmbitusShort`.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43pub struct AmbitusShort {
44    /// The span in semitones.
45    pub semitones: IntegerType,
46    /// The span's simple diatonic name, `P5`.
47    pub diatonic: String,
48    /// The lowest pitch, by name with octave.
49    pub pitch_lowest: Option<String>,
50    /// The highest pitch, by name with octave.
51    pub pitch_highest: Option<String>,
52}
53
54/// One of the values read off a score, as a search compares it.
55#[derive(Clone, Debug, PartialEq)]
56pub enum RichValue<'a> {
57    /// Nothing was found.
58    None,
59    /// A text: a meter, a tempo, a pitch, a path.
60    Text(Cow<'a, str>),
61    /// A count, or a key signature's sharps.
62    Integer(IntegerType),
63    /// A length in quarter notes.
64    Length(OffsetQL),
65    /// Every meter or tempo, in order.
66    Texts(&'a [String]),
67    /// Every key signature, as sharps, in order.
68    Integers(&'a [IntegerType]),
69    /// The range.
70    Ambitus(&'a AmbitusShort),
71}
72
73/// What a [`RichMetadata::search`] asks of a value: music21's query, which
74/// may be a string, a pattern, a function or a number.
75pub enum RichQuery<'a> {
76    /// Text held in a value's text, either case ignored.
77    Text(&'a str),
78    /// A pattern, answered for a value's text: music21's regular
79    /// expression, which never matches what is not text.
80    Pattern(&'a dyn Fn(&str) -> bool),
81    /// A function of any value: music21's callable query.
82    Function(&'a dyn Fn(&RichValue<'_>) -> bool),
83    /// A number: held in a text as written, or equal to a count.
84    Integer(IntegerType),
85    /// A key signature: equal to a count of sharps.
86    Sharps(IntegerType),
87}
88
89impl std::fmt::Debug for RichQuery<'_> {
90    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match self {
92            Self::Text(query) => formatter.debug_tuple("Text").field(query).finish(),
93            Self::Pattern(_) => formatter.write_str("Pattern(..)"),
94            Self::Function(_) => formatter.write_str("Function(..)"),
95            Self::Integer(query) => formatter.debug_tuple("Integer").field(query).finish(),
96            Self::Sharps(query) => formatter.debug_tuple("Sharps").field(query).finish(),
97        }
98    }
99}
100
101impl RichQuery<'_> {
102    fn matches(&self, value: &RichValue<'_>) -> bool {
103        match (self, value) {
104            (Self::Function(function), value) => function(value),
105            (Self::Text(query), RichValue::Text(text)) => {
106                text.to_lowercase().contains(&query.to_lowercase())
107            }
108            (Self::Pattern(pattern), RichValue::Text(text)) => pattern(text),
109            (Self::Integer(query), RichValue::Text(text)) => text.contains(&query.to_string()),
110            (Self::Integer(query) | Self::Sharps(query), RichValue::Integer(value)) => {
111                query == value
112            }
113            _ => false,
114        }
115    }
116}
117
118/// A score's metadata and what was read off the score: music21's
119/// `RichMetadata`.
120///
121/// ```
122/// use music21::metadata::rich::{RichMetadata, RichQuery};
123/// use music21::tinynotation::from_tiny_notation;
124///
125/// let line = from_tiny_notation("3/4 c4 d e g a b")?;
126/// let mut rich = RichMetadata::default();
127/// rich.update(&line, None)?;
128/// assert_eq!(rich.time_signatures, ["3/4"]);
129/// assert_eq!(rich.note_count, Some(6));
130/// assert_eq!(rich.search(&RichQuery::Text("3/4"), None), Some(Some("timeSignatureFirst")));
131/// # Ok::<(), music21::Error>(())
132/// ```
133#[derive(Clone, Debug, PartialEq)]
134#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
135pub struct RichMetadata {
136    /// The score's own metadata.
137    pub metadata: Metadata,
138    /// The range of its pitches.
139    pub ambitus: Option<AmbitusShort>,
140    /// The sharps of its first key signature.
141    pub key_signature_first: Option<IntegerType>,
142    /// The sharps of every key signature, each once, in order.
143    pub key_signatures: Vec<IntegerType>,
144    /// How many notes, chords and rests it has.
145    pub note_count: Option<IntegerType>,
146    /// How many parts it has.
147    pub number_of_parts: Option<IntegerType>,
148    /// Its highest pitch, by name with octave.
149    pub pitch_highest: Option<String>,
150    /// Its lowest pitch, by name with octave.
151    pub pitch_lowest: Option<String>,
152    /// How long it is, in quarter notes.
153    pub score_quarter_length: OffsetQL,
154    /// Where it lives in the corpus, a POSIX path.
155    pub source_path: String,
156    /// Its first tempo, as music21 writes it.
157    pub tempo_first: Option<String>,
158    /// Every tempo, each once, in order.
159    pub tempos: Vec<String>,
160    /// Its first meter, `3/4`.
161    pub time_signature_first: Option<String>,
162    /// Every meter, each once, in order.
163    pub time_signatures: Vec<String>,
164}
165
166impl Default for RichMetadata {
167    fn default() -> Self {
168        Self {
169            metadata: Metadata::new(),
170            ambitus: None,
171            key_signature_first: None,
172            key_signatures: Vec::new(),
173            note_count: None,
174            number_of_parts: None,
175            pitch_highest: None,
176            pitch_lowest: None,
177            score_quarter_length: OffsetQL::Float(0.0),
178            source_path: String::new(),
179            tempo_first: None,
180            tempos: Vec::new(),
181            time_signature_first: None,
182            time_signatures: Vec::new(),
183        }
184    }
185}
186
187impl RichMetadata {
188    /// Rich metadata over a score's own.
189    pub fn of(metadata: Metadata) -> Self {
190        Self {
191            metadata,
192            ..Self::default()
193        }
194    }
195
196    /// One of the values read off the score, by its name in
197    /// [`RICH_ATTRIBUTES`].
198    pub fn value(&self, name: &str) -> Option<RichValue<'_>> {
199        fn text(found: &Option<String>) -> RichValue<'_> {
200            found
201                .as_deref()
202                .map_or(RichValue::None, |text| RichValue::Text(Cow::Borrowed(text)))
203        }
204        let integer =
205            |found: Option<IntegerType>| found.map_or(RichValue::None, RichValue::Integer);
206        let value = match name {
207            "ambitus" => self
208                .ambitus
209                .as_ref()
210                .map_or(RichValue::None, RichValue::Ambitus),
211            "keySignatureFirst" => integer(self.key_signature_first),
212            "keySignatures" => RichValue::Integers(&self.key_signatures),
213            "noteCount" => integer(self.note_count),
214            "numberOfParts" => integer(self.number_of_parts),
215            "pitchHighest" => text(&self.pitch_highest),
216            "pitchLowest" => text(&self.pitch_lowest),
217            "scoreQuarterLength" => RichValue::Length(self.score_quarter_length),
218            "sourcePath" => RichValue::Text(Cow::Borrowed(&self.source_path)),
219            "tempoFirst" => text(&self.tempo_first),
220            "tempos" => RichValue::Texts(&self.tempos),
221            "timeSignatureFirst" => text(&self.time_signature_first),
222            "timeSignatures" => RichValue::Texts(&self.time_signatures),
223            _ => return None,
224        };
225        Some(value)
226    }
227
228    /// Reads the thirteen values off a score: music21's `update`.
229    /// `corpus` is the corpus directory, which a score's file path is
230    /// written relative to where it holds no corpus path of its own.
231    ///
232    /// # Errors
233    ///
234    /// A span of pitches no interval names.
235    pub fn update(&mut self, stream: &Stream, corpus: Option<&Path>) -> Result<()> {
236        self.number_of_parts = Some(stream.parts().len() as IntegerType);
237        self.source_path = source_path(stream, corpus);
238        self.key_signatures.clear();
239        self.tempos.clear();
240        self.time_signatures.clear();
241
242        // One pass over the flattened score gathers meters, keys and tempos.
243        let flat = stream.flatten();
244        for (_, element) in flat.leaves() {
245            match element {
246                StreamElement::TimeSignature(meter) => {
247                    push_new(&mut self.time_signatures, meter.ratio_string());
248                }
249                StreamElement::KeySignature(signature) => {
250                    push_new(&mut self.key_signatures, signature.sharps());
251                }
252                StreamElement::Key(key) => push_new(&mut self.key_signatures, key.sharps()),
253                StreamElement::MetronomeMark(mark) => {
254                    push_new(&mut self.tempos, mark.music21_repr());
255                }
256                StreamElement::TempoText(text) => push_new(&mut self.tempos, text.music21_repr()),
257                _ => {}
258            }
259        }
260        self.time_signature_first = self.time_signatures.first().cloned();
261        self.key_signature_first = self.key_signatures.first().copied();
262        self.tempo_first = self.tempos.first().cloned();
263        self.note_count = Some(flat.notes_and_rests().len() as IntegerType);
264        self.score_quarter_length = op_frac(crate::variant::highest_time(&flat))?;
265
266        // The range, P1 where there are no pitches.
267        let span = crate::analysis::stream_pitch_span(stream);
268        self.pitch_lowest = span.as_ref().map(|(low, _)| low.name_with_octave());
269        self.pitch_highest = span.as_ref().map(|(_, high)| high.name_with_octave());
270        let interval = match &span {
271            Some((low, high)) => Interval::between_pitches(low, high)?,
272            None => Interval::from_name("P1")?,
273        };
274        self.ambitus = Some(AmbitusShort {
275            semitones: interval.semitones() as IntegerType,
276            diatonic: interval.diatonic().simple_name(),
277            pitch_lowest: self.pitch_lowest.clone(),
278            pitch_highest: self.pitch_highest.clone(),
279        });
280        Ok(())
281    }
282
283    /// The first value a query matches, and the field it was found under,
284    /// searching the score's values beside its metadata: music21's
285    /// `RichMetadata.search`. `None` where nothing matched; `Some(None)`
286    /// for a contributor with no role.
287    pub fn search(&self, query: &RichQuery<'_>, field: Option<&str>) -> Option<Option<&str>> {
288        let field = field.map(str::to_lowercase);
289        self.search_pairs(field.as_deref())
290            .into_iter()
291            .find(|(value, _)| query.matches(value))
292            .map(|(_, field)| field)
293    }
294
295    /// The values a search looks through and the field each answers under,
296    /// in music21's order.
297    fn search_pairs(&self, field: Option<&str>) -> Vec<(RichValue<'_>, Option<&str>)> {
298        let mut pairs = Vec::new();
299        match field {
300            Some(field) => pairs.extend(self.field_pairs(field)),
301            None => pairs.extend(
302                self.standard_values()
303                    .into_iter()
304                    .map(|(name, value)| (value, Some(name))),
305            ),
306        }
307
308        // Every contributor's name, under its role.
309        for (_, value) in self.metadata.contributors() {
310            if !contributor_answers_to(value.role(), field) {
311                continue;
312            }
313            let names: Vec<&str> = match value.as_contributor() {
314                Some(contributor) => contributor.names().iter().map(|name| name.data()).collect(),
315                None => vec![value.text()],
316            };
317            for name in names {
318                pairs.push((RichValue::Text(Cow::Borrowed(name)), value.role()));
319            }
320        }
321        pairs
322    }
323
324    /// What a search of one field looks through: the values of the name it
325    /// spells out, or else the first standard name holding it.
326    fn field_pairs(&self, field: &str) -> Vec<(RichValue<'_>, Option<&str>)> {
327        // music21 lowercases the field first, so only the two rich names
328        // written in lower case are found whole.
329        if let Some(name) = RICH_ATTRIBUTES.iter().find(|name| **name == field) {
330            let value = self.value(name).unwrap_or(RichValue::None);
331            if value != RichValue::None {
332                return vec![(value, Some(*name))];
333            }
334        }
335        if let Some((unique_name, asked)) = unique_name_of_field(field) {
336            let texts = self.metadata.field_texts(unique_name);
337            if !texts.is_empty() {
338                return texts
339                    .into_iter()
340                    .map(|text| (RichValue::Text(text), Some(asked)))
341                    .collect();
342            }
343        }
344
345        // The first standard name holding the field, or whose old work id
346        // does, with that one value.
347        for (name, value) in self.standard_values() {
348            if name.to_lowercase().contains(field) {
349                return vec![(value, Some(name))];
350            }
351            let Some(work_id) = old_work_id(name) else {
352                continue;
353            };
354            if work_id.to_lowercase().contains(field) {
355                return vec![(value, Some(work_id))];
356            }
357        }
358        Vec::new()
359    }
360
361    /// Every standard value that is not a contributor's, the score's values
362    /// among them, sorted by name: music21's `all(skipContributors=True)`
363    /// without the names a caller made up.
364    fn standard_values(&self) -> Vec<(&str, RichValue<'_>)> {
365        let mut values: Vec<(&str, RichValue<'_>)> = self
366            .metadata
367            .all_sorted()
368            .into_iter()
369            .filter(|(name, _)| !is_contributor_unique_name(name) && namespace_name(name).is_some())
370            .map(|(name, value)| (name, RichValue::Text(Cow::Borrowed(value.text()))))
371            .collect();
372        for name in RICH_ATTRIBUTES {
373            values.push((name, self.value(name).unwrap_or(RichValue::None)));
374        }
375        values.sort_by(|left, right| left.0.cmp(right.0));
376        values
377    }
378}
379
380/// Adds a value not there yet.
381fn push_new<T: PartialEq>(values: &mut Vec<T>, value: T) {
382    if !values.contains(&value) {
383        values.push(value);
384    }
385}
386
387/// Where a score lives in the corpus: its metadata's corpus path, or its
388/// file path relative to the corpus, as POSIX: music21's `getSourcePath`.
389fn source_path(stream: &Stream, corpus: Option<&Path>) -> String {
390    let Some(metadata) = stream.metadata() else {
391        return String::new();
392    };
393    if let Some(found) = metadata
394        .first_text("corpusFilePath")
395        .filter(|found| !found.is_empty())
396    {
397        return found.to_string();
398    }
399    let Some(file) = metadata
400        .first_text("filePath")
401        .filter(|file| !file.is_empty())
402    else {
403        return String::new();
404    };
405    let file = Path::new(file);
406    let relative = corpus
407        .and_then(|corpus| file.strip_prefix(corpus).ok())
408        .unwrap_or(file);
409    relative
410        .components()
411        .map(|part| part.as_os_str().to_string_lossy())
412        .collect::<Vec<_>>()
413        .join("/")
414        .replacen("//", "/", 1)
415}
416
417#[cfg(test)]
418mod tests {
419    use super::*;
420
421    fn bach() -> RichMetadata {
422        let mut metadata = Metadata::new();
423        metadata.add_contributor("composer", "J.S. Bach");
424        metadata.add_text("title", "Aus meines Herzens Grunde");
425        let mut rich = RichMetadata::of(metadata);
426        rich.note_count = Some(12);
427        rich.time_signatures = vec!["3/4".to_string()];
428        rich.time_signature_first = Some("3/4".to_string());
429        rich.source_path = "bach/bwv1.6.mxl".to_string();
430        rich
431    }
432
433    #[test]
434    fn a_search_reads_the_score_s_values() {
435        let rich = bach();
436        assert_eq!(
437            rich.search(&RichQuery::Text("3/4"), None),
438            Some(Some("timeSignatureFirst"))
439        );
440        assert_eq!(
441            rich.search(&RichQuery::Text("bach"), Some("composer")),
442            Some(Some("composer"))
443        );
444        assert_eq!(
445            rich.search(&RichQuery::Text("bwv1.6"), None),
446            Some(Some("sourcePath"))
447        );
448        assert_eq!(rich.search(&RichQuery::Text("mozart"), None), None);
449    }
450
451    #[test]
452    fn a_camel_case_field_is_found_by_its_lowercase_spelling() {
453        let rich = bach();
454        let fewer =
455            |value: &RichValue<'_>| matches!(value, RichValue::Integer(count) if *count < 20);
456        let query = RichQuery::Function(&fewer);
457        assert_eq!(
458            rich.search(&query, Some("noteCount")),
459            Some(Some("noteCount"))
460        );
461        assert_eq!(
462            rich.search(&RichQuery::Integer(12), Some("notecount")),
463            Some(Some("noteCount"))
464        );
465    }
466
467    #[test]
468    fn a_list_is_not_text() {
469        let rich = bach();
470        assert_eq!(
471            rich.search(&RichQuery::Text("3/4"), Some("timeSignatures")),
472            None
473        );
474    }
475}