mirror of
https://github.com/kennethreitz/pytheory.git
synced 2026-06-05 23:00:20 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 960fdbe3df | |||
| b3f3e985b4 | |||
| c1925af69d | |||
| 7883c978f7 | |||
| 36d558573c | |||
| 1e2f09e2ab | |||
| 9404afc1f3 | |||
| 72aa097552 | |||
| 5ebf0bdd97 |
@@ -7,3 +7,4 @@ t2.py
|
||||
__pycache__
|
||||
pytheory.egg-info
|
||||
docs/_build
|
||||
.claude/worktrees/
|
||||
|
||||
@@ -2,6 +2,38 @@
|
||||
|
||||
All notable changes to PyTheory are documented here.
|
||||
|
||||
## 0.42.1
|
||||
|
||||
- **Fretboard tuning support** — `to_tab()` now accepts `Fretboard` objects as
|
||||
the `tuning` parameter. Works with `Fretboard.guitar()`, `Fretboard.bass()`,
|
||||
`Fretboard.ukulele()`, `Fretboard.mandolin()`, `Fretboard.banjo()`, and any
|
||||
custom Fretboard with capo.
|
||||
|
||||
## 0.42.0
|
||||
|
||||
- **LilyPond export** — `Score.to_lilypond()` generates complete LilyPond source
|
||||
files with multi-staff scores, key/time signatures, tempo markings, and
|
||||
automatic bass clef detection. Output can be compiled to publication-quality
|
||||
PDFs with LilyPond.
|
||||
- **MusicXML export** — `Score.to_musicxml()` generates MusicXML 4.0 documents
|
||||
that can be opened in MuseScore, Sibelius, Finale, and any notation software.
|
||||
Includes proper ties, chords, clef detection, and tempo/time signature metadata.
|
||||
- **Guitar/bass tablature** — `Part.to_tab()` and `Score.to_tab()` generate ASCII
|
||||
tablature. Supports guitar (6-string), bass (4-string), drop D, and custom
|
||||
tunings. Automatically maps notes to the best string/fret positions.
|
||||
|
||||
## 0.41.4
|
||||
|
||||
- **Fix** — `to_abc()` now ties long notes across barlines instead of emitting
|
||||
oversized durations that abcjs can't render (e.g. 16-beat notes become four
|
||||
tied whole notes).
|
||||
|
||||
## 0.41.3
|
||||
|
||||
- **Fix** — `to_abc()` now skips parts with only drum tones or rests (no pitched
|
||||
notes), fixing "pitch is undefined" errors in abcjs. Chords are correctly
|
||||
recognized as pitched content.
|
||||
|
||||
## 0.41.2
|
||||
|
||||
- **Auto bass clef** — `to_abc()` detects low-register parts (808, bass, timpani)
|
||||
|
||||
@@ -503,9 +503,16 @@ are standard arranging techniques for spreading chord tones across registers:
|
||||
>>> cmaj7 = Chord.from_symbol("Cmaj7")
|
||||
>>> cmaj7.close_voicing()
|
||||
<Chord C major 7th>
|
||||
>>> cmaj7.open_voicing()
|
||||
<Chord C major 7th>
|
||||
>>> cmaj7.drop2()
|
||||
<Chord C major 7th>
|
||||
|
||||
``open_voicing()`` takes the close voicing and raises every other
|
||||
non-root tone by an octave, spreading the chord across two octaves.
|
||||
The result is a wider, more spacious sound — common in orchestral
|
||||
writing and piano ballads where you want the harmony to breathe.
|
||||
|
||||
Chord Extensions
|
||||
----------------
|
||||
|
||||
@@ -596,6 +603,23 @@ music that doesn't follow traditional harmony, this is the tool.
|
||||
Major and minor triads share the same prime form — they're inversions
|
||||
of each other in pitch class space.
|
||||
|
||||
The **normal form** is the intermediate step — the most compact ascending
|
||||
arrangement of pitch classes before transposition. It preserves the
|
||||
actual pitch classes (not transposed to 0), so it tells you which
|
||||
specific notes are in the set:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> Chord.from_tones("C", "E", "G").normal_form
|
||||
(0, 4, 7)
|
||||
|
||||
>>> Chord.from_tones("A", "C", "E").normal_form
|
||||
(9, 0, 4)
|
||||
|
||||
Normal form keeps the original pitch classes; prime form transposes to 0
|
||||
for comparison. Use ``normal_form`` when you care about which notes,
|
||||
``prime_form`` when you care about the abstract shape.
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> Chord.from_tones("C", "E", "G").forte_number
|
||||
|
||||
@@ -0,0 +1,404 @@
|
||||
Nashville Numbers, Blues Scales, and Tablature
|
||||
===============================================
|
||||
|
||||
Three tools that work together: the Nashville number system for writing
|
||||
chord charts, blues scales for improvisation, and tablature for seeing
|
||||
where to put your fingers. This guide covers all three and shows how
|
||||
they connect.
|
||||
|
||||
The Nashville Number System
|
||||
---------------------------
|
||||
|
||||
The `Nashville number system <https://en.wikipedia.org/wiki/Nashville_Number_System>`_
|
||||
replaces chord names with Arabic numerals (1, 2, 3...) so that a chart
|
||||
works in **any key**. It's the standard chart format in Nashville
|
||||
recording studios — a session musician can read a number chart and
|
||||
transpose on the fly without rewriting anything.
|
||||
|
||||
The idea is simple: each number refers to a **scale degree**. In any
|
||||
major key, 1 is the tonic chord, 4 is the subdominant, 5 is the
|
||||
dominant, and so on. The chord quality (major, minor, diminished) is
|
||||
determined by the key — you don't need to write it out.
|
||||
|
||||
In C major::
|
||||
|
||||
1 = C major 5 = G major
|
||||
2 = D minor 6 = A minor
|
||||
3 = E minor 7 = B diminished
|
||||
4 = F major
|
||||
|
||||
In G major::
|
||||
|
||||
1 = G major 5 = D major
|
||||
2 = A minor 6 = E minor
|
||||
3 = B minor 7 = F# diminished
|
||||
4 = C major
|
||||
|
||||
Same numbers, different key, different chords — but the same harmonic
|
||||
relationships.
|
||||
|
||||
Using Nashville Numbers in PyTheory
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Both :class:`~pytheory.scales.Key` and :class:`~pytheory.scales.TonedScale`
|
||||
support the ``nashville()`` method:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> from pytheory import Key
|
||||
|
||||
>>> key = Key("C", "major")
|
||||
>>> [c.identify() for c in key.nashville(1, 4, 5, 1)]
|
||||
['C major', 'F major', 'G major', 'C major']
|
||||
|
||||
>>> # Same progression, different key — just change the Key
|
||||
>>> key_g = Key("G", "major")
|
||||
>>> [c.identify() for c in key_g.nashville(1, 4, 5, 1)]
|
||||
['G major', 'C major', 'D major', 'G major']
|
||||
|
||||
Nashville numbers and Roman numerals produce the same result — they're
|
||||
two notations for the same concept:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> key = Key("G", "major")
|
||||
>>> nash = [c.identify() for c in key.nashville(1, 5, 6, 4)]
|
||||
>>> roman = [c.identify() for c in key.progression("I", "V", "vi", "IV")]
|
||||
>>> nash == roman
|
||||
True
|
||||
|
||||
Seventh Chords
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
Suffix ``"7"`` to get seventh chords — essential for jazz and blues
|
||||
charts:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> key = Key("C", "major")
|
||||
>>> [c.identify() for c in key.nashville("17", "47", "57")]
|
||||
['C major 7th', 'F major 7th', 'G dominant 7th']
|
||||
|
||||
Nashville vs. Roman Numerals
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
When should you use which?
|
||||
|
||||
- **Nashville numbers** — faster to type, easier to read at a glance,
|
||||
standard in studio sessions. Use ``key.nashville(1, 4, 5, 1)``.
|
||||
- **Roman numerals** — encode chord quality (uppercase = major,
|
||||
lowercase = minor), standard in theory textbooks. Use
|
||||
``key.progression("I", "IV", "V", "I")``.
|
||||
|
||||
Both are fully supported. Use whichever fits your workflow.
|
||||
|
||||
Blues Scales
|
||||
------------
|
||||
|
||||
The `blues scale <https://en.wikipedia.org/wiki/Blues_scale>`_ is a
|
||||
six-note scale built from the minor pentatonic plus one chromatic
|
||||
passing tone — the **blue note** (flat 5th). That single added note
|
||||
gives the blues its tension and character.
|
||||
|
||||
The blues system in PyTheory includes several related scales:
|
||||
|
||||
==================== ===== ==================================
|
||||
Scale Notes Character
|
||||
==================== ===== ==================================
|
||||
minor pentatonic 5 Foundation of rock and blues soloing
|
||||
major pentatonic 5 Bright, country, pop
|
||||
blues 6 Minor pentatonic + blue note (b5)
|
||||
major blues 6 Major pentatonic + blue note (b3)
|
||||
dominant 7 Mixolydian — dominant 7th sound
|
||||
minor 7 Dorian-like — minor with natural 6th
|
||||
==================== ===== ==================================
|
||||
|
||||
Building Blues Scales
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Use ``system="blues"`` when creating a :class:`~pytheory.scales.TonedScale`:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> from pytheory import TonedScale
|
||||
|
||||
>>> c = TonedScale(tonic="C4", system="blues")
|
||||
|
||||
>>> c["minor pentatonic"].note_names
|
||||
['C', 'Eb', 'F', 'G', 'Bb', 'C']
|
||||
|
||||
>>> c["blues"].note_names
|
||||
['C', 'Eb', 'F', 'Gb', 'G', 'Bb', 'C']
|
||||
|
||||
>>> c["major pentatonic"].note_names
|
||||
['C', 'D', 'E', 'G', 'A', 'C']
|
||||
|
||||
>>> c["major blues"].note_names
|
||||
['C', 'D', 'Eb', 'E', 'G', 'A', 'C']
|
||||
|
||||
The Anatomy of a Blues Scale
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The blues scale in C::
|
||||
|
||||
C Eb F Gb G Bb C
|
||||
1 b3 4 b5 5 b7 8
|
||||
|
||||
Root ──┐
|
||||
├── minor 3rd (3 semitones)
|
||||
├── perfect 4th (5 semitones)
|
||||
├── diminished 5th (6 semitones) ← the "blue note"
|
||||
├── perfect 5th (7 semitones)
|
||||
├── minor 7th (10 semitones)
|
||||
└── octave (12 semitones)
|
||||
|
||||
The blue note (Gb/F#) sits between the 4th and 5th — a dissonant,
|
||||
unstable pitch that resolves up or down. It's what makes blues sound
|
||||
like blues.
|
||||
|
||||
The 12-Bar Blues
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
The `12-bar blues <https://en.wikipedia.org/wiki/Twelve-bar_blues>`_ is
|
||||
the most important chord progression in American music. It uses the
|
||||
Nashville numbers 1, 4, and 5::
|
||||
|
||||
| 1 | 1 | 1 | 1 |
|
||||
| 4 | 4 | 1 | 1 |
|
||||
| 5 | 4 | 1 | 5 |
|
||||
|
||||
In the key of A:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> from pytheory import Key
|
||||
|
||||
>>> key = Key("A", "major")
|
||||
>>> bars = key.nashville(1,1,1,1, 4,4,1,1, 5,4,1,5)
|
||||
>>> [c.identify() for c in bars]
|
||||
['A major', 'A major', 'A major', 'A major', 'D major', 'D major', 'A major', 'A major', 'E major', 'D major', 'A major', 'E major']
|
||||
|
||||
For an authentic blues sound, use dominant 7th chords:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> bars_7 = key.nashville("17","17","17","17", "47","47","17","17", "57","47","17","57")
|
||||
>>> [c.identify() for c in bars_7]
|
||||
['A major 7th', 'A major 7th', 'A major 7th', 'A major 7th', 'D major 7th', 'D major 7th', 'A major 7th', 'A major 7th', 'E dominant 7th', 'D major 7th', 'A major 7th', 'E dominant 7th']
|
||||
|
||||
Or use the built-in named progression:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> key = Key("A", "major")
|
||||
>>> blues = key.common_progressions()["12-bar blues"]
|
||||
>>> [c.identify() for c in blues]
|
||||
['A major', 'A major', 'A major', 'A major', 'D major', 'D major', 'A major', 'A major', 'E major', 'D major', 'A major', 'E major']
|
||||
|
||||
Blues Scale on the Fretboard
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Visualize the blues scale on guitar to see the patterns:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> from pytheory import Fretboard, TonedScale
|
||||
|
||||
>>> fb = Fretboard.guitar()
|
||||
>>> blues = TonedScale(tonic="A4", system="blues")["blues"]
|
||||
>>> print(fb.scale_diagram(blues, frets=12))
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12
|
||||
E| - | - | - | - | - | A | - | - | C | - | D | Eb| E |
|
||||
B| - | - | - | D | Eb| E | - | - | - | - | A | - | - |
|
||||
G| - | - | A | - | - | C | - | D | Eb| E | - | - | - |
|
||||
D| - | - | - | - | A | - | - | C | - | D | Eb| E | - |
|
||||
A| A | - | - | C | - | D | Eb| E | - | - | - | - | A |
|
||||
E| - | - | - | - | - | A | - | - | C | - | D | Eb| E |
|
||||
|
||||
The minor pentatonic (same scale without the Eb) is the most-played
|
||||
scale in rock guitar. Add the blue note and you have the full blues
|
||||
scale — the same shapes, one extra fret.
|
||||
|
||||
Tablature
|
||||
---------
|
||||
|
||||
`Tablature <https://en.wikipedia.org/wiki/Tablature>`_ (tab) shows
|
||||
**where to put your fingers** rather than what notes to play. Each line
|
||||
represents a string; numbers indicate fret positions. PyTheory generates
|
||||
tabs at three levels:
|
||||
|
||||
1. **Chord tabs** — single chord fingerings
|
||||
2. **Part tabs** — full melody/sequence notation
|
||||
3. **Score tabs** — extract a part from a multi-part score
|
||||
|
||||
Chord Tablature
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Get the tab for any chord on any instrument:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> from pytheory import Fretboard
|
||||
|
||||
>>> fb = Fretboard.guitar()
|
||||
>>> print(fb.tab("C"))
|
||||
C major
|
||||
e|--0--
|
||||
B|--1--
|
||||
G|--0--
|
||||
D|--2--
|
||||
A|--3--
|
||||
E|--x--
|
||||
|
||||
>>> print(fb.tab("Am"))
|
||||
A minor
|
||||
e|--0--
|
||||
B|--1--
|
||||
G|--2--
|
||||
D|--2--
|
||||
A|--0--
|
||||
E|--x--
|
||||
|
||||
>>> print(fb.tab("E7"))
|
||||
E dominant 7th
|
||||
e|--0--
|
||||
B|--0--
|
||||
G|--1--
|
||||
D|--0--
|
||||
A|--2--
|
||||
E|--0--
|
||||
|
||||
Works with any instrument:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> uke = Fretboard.ukulele()
|
||||
>>> print(uke.tab("C"))
|
||||
C major
|
||||
A|--3--
|
||||
E|--0--
|
||||
C|--0--
|
||||
G|--0--
|
||||
|
||||
Reading Tab Notation
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
::
|
||||
|
||||
e|--0-- ← open string (don't fret, just pluck)
|
||||
B|--1-- ← press fret 1
|
||||
G|--0-- ← open string
|
||||
D|--2-- ← press fret 2
|
||||
A|--3-- ← press fret 3
|
||||
E|--x-- ← muted (don't play this string)
|
||||
|
||||
- Each line is a string (highest pitch at top, lowest at bottom)
|
||||
- Numbers are fret positions (0 = open, 1-24 = fretted)
|
||||
- ``x`` means the string is muted / not played
|
||||
- ``|`` marks measure boundaries in sequence tabs
|
||||
|
||||
Part Tablature
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Generate tab from a composed part using ``to_tab()``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Score, Key, Duration
|
||||
|
||||
score = Score("4/4", bpm=120)
|
||||
lead = score.part("lead", synth="saw")
|
||||
|
||||
# A simple blues lick
|
||||
for note in ["A4", "C5", "D5", "Eb5", "E5", "G5", "A5"]:
|
||||
lead.add(note, Duration.QUARTER)
|
||||
|
||||
print(lead.to_tab())
|
||||
|
||||
This outputs standard ASCII tab with measure lines, mapping each note
|
||||
to the most playable string and fret position.
|
||||
|
||||
Tuning Options
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
The ``to_tab()`` method supports multiple tunings:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Standard guitar (default)
|
||||
lead.to_tab(tuning="guitar")
|
||||
|
||||
# 4-string bass
|
||||
lead.to_tab(tuning="bass")
|
||||
|
||||
# Drop D guitar
|
||||
lead.to_tab(tuning="drop_d")
|
||||
|
||||
# Any Fretboard object — use any of the 25+ instrument presets
|
||||
from pytheory import Fretboard
|
||||
lead.to_tab(tuning=Fretboard.mandolin())
|
||||
lead.to_tab(tuning=Fretboard.banjo())
|
||||
|
||||
# Custom tuning as MIDI note numbers (low string first)
|
||||
lead.to_tab(tuning=[40, 45, 50, 55, 59, 64])
|
||||
|
||||
Score Tablature
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
Extract tab from a multi-part score:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
score = Score("4/4", bpm=120)
|
||||
rhythm = score.part("rhythm", synth="saw")
|
||||
lead = score.part("lead", synth="triangle")
|
||||
bass = score.part("bass", synth="sine")
|
||||
|
||||
# ... compose parts ...
|
||||
|
||||
# Tab the lead part
|
||||
print(score.to_tab("lead"))
|
||||
|
||||
# Tab the first non-drum part (if no name given)
|
||||
print(score.to_tab())
|
||||
|
||||
# Bass tab
|
||||
print(score.to_tab("bass", tuning="bass"))
|
||||
|
||||
Putting It All Together
|
||||
-----------------------
|
||||
|
||||
Here's a complete example that uses all three features — Nashville
|
||||
numbers for the chord progression, the blues scale for the melody, and
|
||||
tab export to see the fingering:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Key, TonedScale, Fretboard, Score, Duration
|
||||
|
||||
# 1. Nashville numbers for the progression
|
||||
key = Key("A", "major")
|
||||
chords = key.nashville(1, 1, 1, 1, 4, 4, 1, 1, 5, 4, 1, 5)
|
||||
|
||||
# 2. Blues scale for the melody
|
||||
blues = TonedScale(tonic="A4", system="blues")["blues"]
|
||||
|
||||
# 3. Compose a score
|
||||
score = Score("4/4", bpm=120)
|
||||
rhythm = score.part("rhythm", synth="saw", envelope="pad")
|
||||
lead = score.part("lead", synth="triangle", envelope="pluck")
|
||||
|
||||
for chord in chords:
|
||||
rhythm.add(chord, Duration.WHOLE)
|
||||
|
||||
for note_name in blues.note_names[:-1]: # walk up the scale
|
||||
lead.add(f"{note_name}4", Duration.HALF)
|
||||
|
||||
# 4. See it as tablature
|
||||
print(lead.to_tab())
|
||||
|
||||
# 5. See the scale on the fretboard
|
||||
fb = Fretboard.guitar()
|
||||
print(fb.scale_diagram(blues, frets=12))
|
||||
|
||||
Nashville numbers tell you *what chords to play*. The blues scale tells you *what notes to solo with*. Tablature tells you *where to put your fingers*. Together, they're everything you need to play the blues.
|
||||
+157
-7
@@ -3,19 +3,21 @@ Playback and Export
|
||||
|
||||
This is the output layer. You've built your theory, composed your
|
||||
arrangement, shaped your sounds -- now you need to hear it. PyTheory
|
||||
gives you three ways to get your music out: speakers, WAV files, and
|
||||
MIDI files.
|
||||
gives you four ways to get your music out: speakers, WAV files, MIDI
|
||||
files, and sheet music.
|
||||
|
||||
Use **speakers** for immediate feedback while you're sketching and
|
||||
experimenting. Use **WAV export** when you want to share actual audio
|
||||
-- post it, send it, drop it into a video. Use **MIDI export** when you
|
||||
want to bring your sketch into a real DAW and finish it with
|
||||
professional instruments, mixing, and mastering. Each output serves a
|
||||
different stage of the creative process.
|
||||
professional instruments, mixing, and mastering. Use **ABC notation
|
||||
export** when you want sheet music -- rendered in the browser or shared
|
||||
as plain text. Each output serves a different stage of the creative
|
||||
process.
|
||||
|
||||
PyTheory can play audio through your speakers, save to WAV, or export
|
||||
to MIDI. Everything is synthesized from waveforms -- no samples or
|
||||
external audio files needed.
|
||||
PyTheory can play audio through your speakers, save to WAV, export to
|
||||
MIDI, or generate sheet music as ABC notation. Everything is synthesized
|
||||
from waveforms -- no samples or external audio files needed.
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -171,6 +173,154 @@ Score-based export (with time signature, tempo, and parts):
|
||||
score.add(chord, Duration.WHOLE)
|
||||
score.save_midi("progression.mid")
|
||||
|
||||
to_abc() -- ABC Notation / Sheet Music
|
||||
---------------------------------------
|
||||
|
||||
ABC notation is a human-readable text format for music that tools can
|
||||
turn into staff notation and MIDI. It's widely used for folk tunes,
|
||||
lead sheets, and quick sketches. PyTheory can export any Score as ABC
|
||||
notation -- and optionally wrap it in an HTML page that renders
|
||||
sheet music right in the browser using `abcjs <https://www.abcjs.net/>`_.
|
||||
|
||||
Basic export:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from pytheory import Score, Duration, Key
|
||||
|
||||
score = Score("4/4", bpm=120)
|
||||
lead = score.part("lead")
|
||||
for chord in Key("C", "major").progression("I", "V", "vi", "IV"):
|
||||
lead.add(chord, Duration.WHOLE)
|
||||
|
||||
print(score.to_abc(title="Pop Chords", key="C"))
|
||||
|
||||
Output:
|
||||
|
||||
.. code-block:: text
|
||||
|
||||
X:1
|
||||
T:Pop Chords
|
||||
M:4/4
|
||||
Q:1/4=120
|
||||
L:1/8
|
||||
K:C
|
||||
[CEG]8 | [GBd]8 | [Ace]8 | [FAc]8 |
|
||||
|
||||
Open sheet music in the browser with ``html=True``:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
html = score.to_abc(title="Pop Chords", key="C", html=True)
|
||||
|
||||
with open("chords.html", "w") as f:
|
||||
f.write(html)
|
||||
|
||||
import webbrowser
|
||||
webbrowser.open("chords.html")
|
||||
|
||||
This generates a self-contained HTML page with an embedded
|
||||
``<script>`` tag that loads abcjs from a CDN and renders the notation
|
||||
as SVG -- no build steps, no dependencies, just open the file.
|
||||
|
||||
Multi-part scores automatically get ``V:`` (voice) directives so each
|
||||
instrument appears on its own staff. Bass parts (average note below C4)
|
||||
get bass clef automatically. Drum-only parts are skipped. Notes longer
|
||||
than one measure are split into tied notes across barlines.
|
||||
|
||||
Parameters:
|
||||
|
||||
- **title** -- Tune title for the ``T:`` header (default ``"Untitled"``).
|
||||
- **key** -- ABC key signature string (default ``"C"``). Use ``"Am"`` for
|
||||
A minor, ``"Bb"`` for B-flat major, ``"F#m"`` for F-sharp minor, etc.
|
||||
- **html** -- If ``True``, return a full HTML document instead of raw ABC
|
||||
(default ``False``).
|
||||
|
||||
to_lilypond() -- LilyPond Export
|
||||
---------------------------------
|
||||
|
||||
`LilyPond <https://lilypond.org/>`_ is the gold standard for
|
||||
publication-quality music engraving. ``to_lilypond()`` generates
|
||||
complete LilyPond source files that you can compile to PDF:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
score = Score("4/4", bpm=120)
|
||||
lead = score.part("lead")
|
||||
for note in ["C4", "D4", "E4", "F4"]:
|
||||
lead.add(note, Duration.QUARTER)
|
||||
|
||||
ly = score.to_lilypond(title="My Score", key="C", mode="major")
|
||||
|
||||
with open("score.ly", "w") as f:
|
||||
f.write(ly)
|
||||
|
||||
Then compile with ``lilypond score.ly`` to get a PDF. Multi-part scores
|
||||
get separate staves in a ``StaffGroup``, bass clef is auto-detected,
|
||||
and long notes are split with ties across barlines.
|
||||
|
||||
Parameters:
|
||||
|
||||
- **title** -- Title for the ``\header`` block (default ``"Untitled"``).
|
||||
- **key** -- Key signature root (default ``"C"``). Use note names like
|
||||
``"Bb"``, ``"F#"``, ``"Eb"``.
|
||||
- **mode** -- LilyPond mode string (default ``"major"``). Use ``"minor"``
|
||||
for minor keys.
|
||||
|
||||
to_musicxml() -- MusicXML Export
|
||||
---------------------------------
|
||||
|
||||
MusicXML is the interchange format for notation software. Export your
|
||||
score and open it in MuseScore, Sibelius, Finale, Dorico, or any
|
||||
other notation app:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
xml = score.to_musicxml(title="My Score")
|
||||
|
||||
with open("score.musicxml", "w") as f:
|
||||
f.write(xml)
|
||||
|
||||
The output is a complete MusicXML 4.0 partwise document with proper
|
||||
time signatures, tempo markings, clef detection, tied notes across
|
||||
barlines, and chord notation. No external dependencies needed.
|
||||
|
||||
to_tab() -- Guitar/Bass Tablature
|
||||
-----------------------------------
|
||||
|
||||
Generate ASCII tablature from any Part or Score:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
lead = score.part("lead")
|
||||
lead.add("E4", Duration.QUARTER)
|
||||
lead.add("B3", Duration.QUARTER)
|
||||
lead.add("G3", Duration.QUARTER)
|
||||
lead.add("D3", Duration.QUARTER)
|
||||
|
||||
print(lead.to_tab())
|
||||
|
||||
Output::
|
||||
|
||||
e|---0---------|
|
||||
B|------0------|
|
||||
G|---------0---|
|
||||
D|------------0|
|
||||
A|-------------|
|
||||
E|-------------|
|
||||
|
||||
Works on Score too -- it picks the first melodic part automatically:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
print(score.to_tab()) # auto-pick part
|
||||
print(score.to_tab(part_name="bass")) # specific part
|
||||
print(score.to_tab(tuning="bass")) # 4-string bass tab
|
||||
print(score.to_tab(tuning="drop_d")) # drop D guitar
|
||||
|
||||
Supports ``"guitar"`` (6-string standard), ``"bass"`` (4-string),
|
||||
``"drop_d"``, or a custom list of MIDI note numbers for any tuning.
|
||||
|
||||
play_pattern() -- Drum Patterns
|
||||
-------------------------------
|
||||
|
||||
|
||||
+27
-1
@@ -269,6 +269,23 @@ easy:
|
||||
['G major', 'A minor', 'B minor', 'C major', 'D major', 'E minor', 'F# diminished']
|
||||
>>> key.seventh_chords
|
||||
['G major 7th', 'A minor 7th', 'B minor 7th', 'C major 7th', 'D dominant 7th', 'E minor 7th', 'F# half-diminished 7th']
|
||||
|
||||
Build a seventh chord on any individual degree with ``seventh()``:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> key.seventh(0) # I7
|
||||
G major 7th
|
||||
>>> key.seventh(4) # V7
|
||||
D dominant 7th
|
||||
>>> key.seventh(6) # vii7
|
||||
F# half-diminished 7th
|
||||
|
||||
This is the single-degree version of ``seventh_chords`` — useful when
|
||||
you need one specific chord rather than the full list.
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> Key.detect("C", "E", "G", "A", "D")
|
||||
C major
|
||||
|
||||
@@ -440,7 +457,16 @@ alternative scales to improvise over:
|
||||
>>> Scale.recommend("C", "Eb", "F", "Gb", "G", "Bb", top=3)
|
||||
[('C', 'blues', 1.0), ...]
|
||||
|
||||
Chromatic scales are deprioritized since they match everything.
|
||||
How it works: ``recommend()`` tests your notes against every scale in
|
||||
every key (all 12 tonics times all scale types in the Western system).
|
||||
Each candidate is scored using ``fitness()`` — the fraction of your notes
|
||||
that belong to that scale (1.0 = perfect match). Results are ranked by
|
||||
fitness, with chromatic scales deprioritized since they match everything.
|
||||
Scales whose length is closer to the number of input notes are preferred
|
||||
when fitness scores tie.
|
||||
|
||||
Returns a list of ``(tonic, scale_name, fitness)`` tuples. Pass ``top=``
|
||||
to control how many results you get back (default 5).
|
||||
|
||||
Parallel Modes
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
@@ -357,6 +357,32 @@ every tone knows its enharmonic spelling:
|
||||
>>> Tone.from_string("C4", system="western").enharmonic is None
|
||||
True
|
||||
|
||||
Accidental Properties
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Check whether a tone is natural, sharp, or flat:
|
||||
|
||||
.. code-block:: pycon
|
||||
|
||||
>>> c = Tone.from_string("C4", system="western")
|
||||
>>> c.is_natural
|
||||
True
|
||||
>>> c.is_sharp
|
||||
False
|
||||
|
||||
>>> cs = Tone.from_string("C#4", system="western")
|
||||
>>> cs.is_sharp
|
||||
True
|
||||
>>> cs.is_natural
|
||||
False
|
||||
|
||||
>>> bb = Tone.from_string("Bb4", system="western")
|
||||
>>> bb.is_flat
|
||||
True
|
||||
|
||||
Useful for filtering — for example, finding all natural notes in a
|
||||
scale, or counting accidentals in a melody.
|
||||
|
||||
Extended Enharmonics
|
||||
~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -118,6 +118,7 @@ What's Inside
|
||||
guide/scales
|
||||
guide/chords
|
||||
guide/fretboard
|
||||
guide/nashville-blues-tabs
|
||||
guide/systems
|
||||
guide/sequencing
|
||||
guide/synths
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "pytheory"
|
||||
version = "0.41.2"
|
||||
version = "0.42.1"
|
||||
description = "Music Theory for Humans"
|
||||
readme = "README.md"
|
||||
license = "MIT"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""PyTheory: Music Theory for Humans."""
|
||||
|
||||
__version__ = "0.41.2"
|
||||
__version__ = "0.42.1"
|
||||
|
||||
from .tones import Tone, Interval
|
||||
from .systems import System, SYSTEMS, TET
|
||||
|
||||
+665
-34
@@ -3796,6 +3796,127 @@ class Part:
|
||||
return max(note_beats, drum_beats)
|
||||
return note_beats
|
||||
|
||||
# ── ASCII tablature export ──────────────────────────────────────────
|
||||
|
||||
_TAB_TUNINGS = {
|
||||
"guitar": [40, 45, 50, 55, 59, 64],
|
||||
"bass": [28, 33, 38, 43],
|
||||
"drop_d": [38, 45, 50, 55, 59, 64],
|
||||
}
|
||||
_TAB_LABELS = {
|
||||
"guitar": ["E", "A", "D", "G", "B", "e"],
|
||||
"bass": ["E", "A", "D", "G"],
|
||||
"drop_d": ["D", "A", "D", "G", "B", "e"],
|
||||
}
|
||||
|
||||
def to_tab(self, *, tuning="guitar", frets=24, time_signature=None):
|
||||
"""Generate ASCII guitar/bass tablature from this part's notes.
|
||||
|
||||
Args:
|
||||
tuning: ``"guitar"`` (6-string standard), ``"bass"`` (4-string),
|
||||
``"drop_d"`` (guitar drop D), a ``Fretboard`` object, or a
|
||||
list of MIDI note numbers for custom tuning (low string first).
|
||||
frets: Maximum fret number (default 24).
|
||||
time_signature: A ``TimeSignature`` or ``None`` for 4/4.
|
||||
|
||||
Returns:
|
||||
A multi-line ASCII tablature string.
|
||||
"""
|
||||
if isinstance(tuning, str):
|
||||
open_midis = list(self._TAB_TUNINGS[tuning])
|
||||
labels = list(self._TAB_LABELS[tuning])
|
||||
elif hasattr(tuning, "tones"):
|
||||
# Fretboard object — tones are high-to-low, reverse for low-to-high
|
||||
fb_tones = list(reversed(tuning.tones))
|
||||
open_midis = [t.midi for t in fb_tones]
|
||||
labels = [t.name if len(t.name) <= 2 else t.name[0] for t in fb_tones]
|
||||
else:
|
||||
open_midis = list(tuning)
|
||||
_note_names = ["C", "C#", "D", "D#", "E", "F",
|
||||
"F#", "G", "G#", "A", "A#", "B"]
|
||||
labels = [_note_names[m % 12] for m in open_midis]
|
||||
|
||||
n_strings = len(open_midis)
|
||||
beats_per_measure = 4.0
|
||||
if time_signature is not None:
|
||||
beats_per_measure = time_signature.beats_per_measure
|
||||
|
||||
# Build columns: each column is a list[str] of length n_strings
|
||||
columns: list[list[str]] = []
|
||||
beat_acc = 0.0
|
||||
|
||||
for note in self.notes:
|
||||
dur_beats = note.duration.value
|
||||
# Insert barline if we've crossed a measure boundary
|
||||
while beat_acc >= beats_per_measure - 0.001:
|
||||
columns.append(["|"] * n_strings)
|
||||
beat_acc -= beats_per_measure
|
||||
|
||||
col = ["---"] * n_strings
|
||||
|
||||
tone = note.tone
|
||||
if tone is None or isinstance(tone, _DrumTone):
|
||||
pass
|
||||
elif hasattr(tone, "tones"):
|
||||
# Chord — assign each chord tone to a different string
|
||||
used: set[int] = set()
|
||||
for ct in tone.tones:
|
||||
midi_val = getattr(ct, "midi", None)
|
||||
if midi_val is None:
|
||||
continue
|
||||
best_s, best_f = self._find_best_string(
|
||||
midi_val, open_midis, frets, used)
|
||||
if best_s is not None:
|
||||
fret_str = str(best_f)
|
||||
col[best_s] = fret_str.center(3, "-")
|
||||
used.add(best_s)
|
||||
else:
|
||||
midi_val = getattr(tone, "midi", None)
|
||||
if midi_val is not None:
|
||||
best_s, best_f = self._find_best_string(
|
||||
midi_val, open_midis, frets, set())
|
||||
if best_s is not None:
|
||||
fret_str = str(best_f)
|
||||
col[best_s] = fret_str.center(3, "-")
|
||||
|
||||
columns.append(col)
|
||||
if not note._hold:
|
||||
beat_acc += dur_beats
|
||||
|
||||
# Trailing barline
|
||||
if columns and columns[-1] != ["|"] * n_strings:
|
||||
while beat_acc >= beats_per_measure - 0.001:
|
||||
columns.append(["|"] * n_strings)
|
||||
beat_acc -= beats_per_measure
|
||||
columns.append(["|"] * n_strings)
|
||||
|
||||
# Build output lines (highest-pitched string first in display)
|
||||
lines: list[str] = []
|
||||
for s_idx in range(n_strings - 1, -1, -1):
|
||||
label = labels[s_idx]
|
||||
parts_str = "".join(c[s_idx] for c in columns)
|
||||
lines.append(f"{label}|{parts_str}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@staticmethod
|
||||
def _find_best_string(midi_val, open_midis, max_fret, used):
|
||||
"""Find the best string/fret for a MIDI note.
|
||||
|
||||
Returns (string_index, fret) or (None, None) if unplayable.
|
||||
"""
|
||||
best_s = None
|
||||
best_f = None
|
||||
for s_idx, open_m in enumerate(open_midis):
|
||||
if s_idx in used:
|
||||
continue
|
||||
f = midi_val - open_m
|
||||
if 0 <= f <= max_fret:
|
||||
if best_f is None or f < best_f:
|
||||
best_s = s_idx
|
||||
best_f = f
|
||||
return best_s, best_f
|
||||
|
||||
def __len__(self):
|
||||
return len(self.notes) + len(self._drum_hits)
|
||||
|
||||
@@ -4396,15 +4517,25 @@ class Score:
|
||||
f"L:1/{default_unit}",
|
||||
]
|
||||
|
||||
# Collect voices: default notes first, then named parts (skip drums)
|
||||
# Collect voices: default notes first, then named parts
|
||||
# Skip drum parts and parts with no pitched notes
|
||||
voices: list[tuple[str, list]] = []
|
||||
if self.notes:
|
||||
voices.append(("default", self.notes))
|
||||
for name, part in self.parts.items():
|
||||
if part.is_drums:
|
||||
continue
|
||||
if part.notes:
|
||||
voices.append((name, part.notes))
|
||||
if not part.notes:
|
||||
continue
|
||||
# Skip parts that have no pitched tones (only drum tones / rests)
|
||||
has_pitched = any(
|
||||
n.tone is not None
|
||||
and (hasattr(n.tone, "name") or hasattr(n.tone, "tones"))
|
||||
for n in part.notes
|
||||
)
|
||||
if not has_pitched:
|
||||
continue
|
||||
voices.append((name, part.notes))
|
||||
|
||||
multi = len(voices) > 1
|
||||
|
||||
@@ -4489,6 +4620,24 @@ class Score:
|
||||
|
||||
return f"{abc_acc}{note_char}{oct_str}"
|
||||
|
||||
@staticmethod
|
||||
def _format_dur(multiplier):
|
||||
"""Format an ABC duration multiplier string."""
|
||||
if abs(multiplier - 1) < 0.001:
|
||||
return ""
|
||||
elif abs(multiplier - int(multiplier)) < 0.001:
|
||||
return str(int(multiplier))
|
||||
elif abs(multiplier - 0.5) < 0.001:
|
||||
return "/2"
|
||||
elif abs(multiplier - 0.25) < 0.001:
|
||||
return "/4"
|
||||
elif abs(multiplier - 1.5) < 0.001:
|
||||
return "3/2"
|
||||
else:
|
||||
from fractions import Fraction
|
||||
frac = Fraction(multiplier).limit_denominator(16)
|
||||
return f"{frac.numerator}/{frac.denominator}"
|
||||
|
||||
def _notes_to_abc(self, notes, default_unit, ts,
|
||||
bars_per_line=4):
|
||||
"""Convert a list of Note objects to an ABC body string."""
|
||||
@@ -4498,17 +4647,12 @@ class Score:
|
||||
measure_count = 0
|
||||
|
||||
for note in notes:
|
||||
beats = note.duration.value
|
||||
|
||||
# ABC length multiplier relative to L:1/default_unit
|
||||
# L:1/8 means 1 unit = 0.5 beats (an eighth note)
|
||||
total_beats = note.duration.value
|
||||
unit_beats = 4.0 / default_unit # beats per L unit
|
||||
multiplier = beats / unit_beats
|
||||
|
||||
if note.tone is None:
|
||||
abc_note = "z"
|
||||
elif hasattr(note.tone, "tones"):
|
||||
# Chord: [CEG]
|
||||
chord_notes = [
|
||||
self._tone_to_abc(t, default_unit)
|
||||
for t in note.tone.tones
|
||||
@@ -4517,33 +4661,32 @@ class Score:
|
||||
else:
|
||||
abc_note = self._tone_to_abc(note.tone, default_unit)
|
||||
|
||||
# Format duration multiplier
|
||||
if multiplier == 1:
|
||||
dur_str = ""
|
||||
elif multiplier == int(multiplier):
|
||||
dur_str = str(int(multiplier))
|
||||
elif multiplier == 0.5:
|
||||
dur_str = "/2"
|
||||
elif multiplier == 0.25:
|
||||
dur_str = "/4"
|
||||
elif multiplier == 1.5:
|
||||
dur_str = "3/2"
|
||||
else:
|
||||
# General fraction
|
||||
from fractions import Fraction
|
||||
frac = Fraction(multiplier).limit_denominator(16)
|
||||
dur_str = f"{frac.numerator}/{frac.denominator}"
|
||||
# Split notes longer than one measure into tied pieces
|
||||
remaining = total_beats
|
||||
first_chunk = True
|
||||
while remaining > 0.001:
|
||||
# How much room left in this measure?
|
||||
room = beats_per_measure - beat_in_measure
|
||||
chunk = min(remaining, room) if remaining > room + 0.001 else remaining
|
||||
needs_tie = remaining - chunk > 0.001
|
||||
|
||||
tokens.append(f"{abc_note}{dur_str}")
|
||||
multiplier = chunk / unit_beats
|
||||
dur_str = self._format_dur(multiplier)
|
||||
|
||||
beat_in_measure += beats
|
||||
if beat_in_measure >= beats_per_measure - 0.001:
|
||||
measure_count += 1
|
||||
if measure_count % bars_per_line == 0:
|
||||
tokens.append("|\n")
|
||||
else:
|
||||
tokens.append("|")
|
||||
beat_in_measure -= beats_per_measure
|
||||
tie_str = "-" if needs_tie and abc_note != "z" else ""
|
||||
tokens.append(f"{abc_note}{dur_str}{tie_str}")
|
||||
|
||||
remaining -= chunk
|
||||
beat_in_measure += chunk
|
||||
first_chunk = False
|
||||
|
||||
if beat_in_measure >= beats_per_measure - 0.001:
|
||||
measure_count += 1
|
||||
if measure_count % bars_per_line == 0:
|
||||
tokens.append("|\n")
|
||||
else:
|
||||
tokens.append("|")
|
||||
beat_in_measure -= beats_per_measure
|
||||
|
||||
body = " ".join(tokens)
|
||||
# Clean up trailing/double barlines
|
||||
@@ -4552,6 +4695,494 @@ class Score:
|
||||
body += " |"
|
||||
return body
|
||||
|
||||
# ── LilyPond notation export ─────────────────────────────────────
|
||||
|
||||
def to_lilypond(self, *, title="Untitled", key="C", mode="major"):
|
||||
"""Export the score as a LilyPond source string.
|
||||
|
||||
Args:
|
||||
title: Title for the ``\\header`` block.
|
||||
key: Key signature root (e.g. ``"C"``, ``"D"``, ``"Bb"``).
|
||||
mode: LilyPond mode string (``"major"``, ``"minor"``, etc.).
|
||||
|
||||
Returns:
|
||||
A complete LilyPond source string.
|
||||
"""
|
||||
ts = self.time_signature
|
||||
|
||||
# Collect voices (same filter as to_abc)
|
||||
voices: list[tuple[str, list]] = []
|
||||
if self.notes:
|
||||
voices.append(("default", self.notes))
|
||||
for name, part in self.parts.items():
|
||||
if part.is_drums:
|
||||
continue
|
||||
if not part.notes:
|
||||
continue
|
||||
has_pitched = any(
|
||||
n.tone is not None
|
||||
and (hasattr(n.tone, "name") or hasattr(n.tone, "tones"))
|
||||
for n in part.notes
|
||||
)
|
||||
if not has_pitched:
|
||||
continue
|
||||
voices.append((name, part.notes))
|
||||
|
||||
ly_key = self._tone_name_to_lilypond(key)
|
||||
|
||||
staves = []
|
||||
for vname, notes in voices:
|
||||
clef = self._guess_clef(notes)
|
||||
body = self._notes_to_lilypond(notes, ts)
|
||||
staff = (
|
||||
f' \\new Staff \\with {{ instrumentName = "{vname}" }} {{\n'
|
||||
f" \\clef {clef}\n"
|
||||
f" \\key {ly_key} \\{mode}\n"
|
||||
f" \\time {ts.beats}/{ts.unit}\n"
|
||||
f" \\tempo 4 = {self.bpm}\n"
|
||||
f" {body}\n"
|
||||
f" }}"
|
||||
)
|
||||
staves.append(staff)
|
||||
|
||||
staves_block = "\n".join(staves)
|
||||
|
||||
return (
|
||||
f'\\version "2.24.0"\n'
|
||||
f"\\header {{\n"
|
||||
f' title = "{title}"\n'
|
||||
f"}}\n\n"
|
||||
f"\\score {{\n"
|
||||
f" \\new StaffGroup <<\n"
|
||||
f"{staves_block}\n"
|
||||
f" >>\n"
|
||||
f" \\layout {{ }}\n"
|
||||
f"}}\n"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _tone_name_to_lilypond(name):
|
||||
"""Convert a note name like 'C#', 'Bb', 'F' to LilyPond pitch."""
|
||||
if not name:
|
||||
return "c"
|
||||
letter = name[0].lower()
|
||||
acc = name[1:] if len(name) > 1 else ""
|
||||
ly_acc = (
|
||||
acc.replace("##", "isis")
|
||||
.replace("#", "is")
|
||||
.replace("bb", "eses")
|
||||
.replace("b", "es")
|
||||
)
|
||||
return f"{letter}{ly_acc}"
|
||||
|
||||
@staticmethod
|
||||
def _tone_to_lilypond(tone):
|
||||
"""Convert a single Tone to a LilyPond pitch string (no duration)."""
|
||||
if tone is None:
|
||||
return None
|
||||
if not hasattr(tone, "name") or not hasattr(tone, "octave"):
|
||||
return None
|
||||
|
||||
name = tone.name
|
||||
octave = tone.octave if tone.octave is not None else 4
|
||||
|
||||
letter = name[0].lower()
|
||||
acc = name[1:] if len(name) > 1 else ""
|
||||
ly_acc = (
|
||||
acc.replace("##", "isis")
|
||||
.replace("#", "is")
|
||||
.replace("bb", "eses")
|
||||
.replace("b", "es")
|
||||
)
|
||||
|
||||
# LilyPond: c = C3, c' = C4, c'' = C5, c, = C2, c,, = C1
|
||||
if octave >= 4:
|
||||
oct_str = "'" * (octave - 3)
|
||||
else:
|
||||
oct_str = "," * (3 - octave)
|
||||
|
||||
return f"{letter}{ly_acc}{oct_str}"
|
||||
|
||||
@staticmethod
|
||||
def _beats_to_lilypond_dur(beats):
|
||||
"""Convert a beat count to a LilyPond duration string."""
|
||||
_MAP = {
|
||||
4.0: "1",
|
||||
2.0: "2",
|
||||
1.0: "4",
|
||||
0.5: "8",
|
||||
0.25: "16",
|
||||
3.0: "2.",
|
||||
1.5: "4.",
|
||||
}
|
||||
for ref, ly in _MAP.items():
|
||||
if abs(beats - ref) < 0.001:
|
||||
return ly
|
||||
if abs(beats - 2 / 3) < 0.05:
|
||||
return "4"
|
||||
closest = min(_MAP, key=lambda k: abs(k - beats))
|
||||
return _MAP[closest]
|
||||
|
||||
def _notes_to_lilypond(self, notes, ts, bars_per_line=4):
|
||||
"""Convert a list of Note objects to a LilyPond music body string."""
|
||||
beats_per_measure = ts.beats_per_measure
|
||||
tokens: list[str] = []
|
||||
beat_in_measure = 0.0
|
||||
measure_count = 0
|
||||
|
||||
for note in notes:
|
||||
total_beats = note.duration.value
|
||||
|
||||
if note.tone is None:
|
||||
pitch = None
|
||||
is_rest = True
|
||||
elif hasattr(note.tone, "tones"):
|
||||
chord_pitches = []
|
||||
for t in note.tone.tones:
|
||||
p = self._tone_to_lilypond(t)
|
||||
if p is not None:
|
||||
chord_pitches.append(p)
|
||||
if chord_pitches:
|
||||
pitch = "<" + " ".join(chord_pitches) + ">"
|
||||
is_rest = False
|
||||
else:
|
||||
pitch = None
|
||||
is_rest = True
|
||||
else:
|
||||
p = self._tone_to_lilypond(note.tone)
|
||||
if p is not None:
|
||||
pitch = p
|
||||
is_rest = False
|
||||
else:
|
||||
pitch = None
|
||||
is_rest = True
|
||||
|
||||
remaining = total_beats
|
||||
while remaining > 0.001:
|
||||
room = beats_per_measure - beat_in_measure
|
||||
chunk = min(remaining, room) if remaining > room + 0.001 else remaining
|
||||
needs_tie = remaining - chunk > 0.001
|
||||
|
||||
dur_str = self._beats_to_lilypond_dur(chunk)
|
||||
|
||||
if is_rest or pitch is None:
|
||||
tokens.append(f"r{dur_str}")
|
||||
else:
|
||||
tie_str = "~" if needs_tie else ""
|
||||
tokens.append(f"{pitch}{dur_str}{tie_str}")
|
||||
|
||||
remaining -= chunk
|
||||
beat_in_measure += chunk
|
||||
|
||||
if beat_in_measure >= beats_per_measure - 0.001:
|
||||
measure_count += 1
|
||||
if measure_count % bars_per_line == 0:
|
||||
tokens.append("|\n ")
|
||||
else:
|
||||
tokens.append("|")
|
||||
beat_in_measure -= beats_per_measure
|
||||
|
||||
body = " ".join(tokens)
|
||||
body = body.replace("| |", "|").rstrip("| \n").rstrip()
|
||||
if not body.endswith("|"):
|
||||
body += " |"
|
||||
return body
|
||||
|
||||
# ── MusicXML export ───────────────────────────────────────────────
|
||||
|
||||
def to_musicxml(self, *, title="Untitled"):
|
||||
"""Export the score as a MusicXML string.
|
||||
|
||||
Args:
|
||||
title: Work title embedded in the ``<work-title>`` element.
|
||||
|
||||
Returns:
|
||||
A MusicXML 4.0 partwise document as a pretty-printed XML string.
|
||||
"""
|
||||
import xml.etree.ElementTree as ET
|
||||
import xml.dom.minidom
|
||||
|
||||
DIVISIONS = 4 # divisions per quarter note
|
||||
|
||||
_DUR_MAP = {
|
||||
4.0: ("whole", False),
|
||||
3.0: ("half", True),
|
||||
2.0: ("half", False),
|
||||
1.5: ("quarter", True),
|
||||
1.0: ("quarter", False),
|
||||
0.5: ("eighth", False),
|
||||
0.25: ("16th", False),
|
||||
}
|
||||
|
||||
def _beats_to_divisions(beats):
|
||||
return int(round(beats * DIVISIONS))
|
||||
|
||||
def _best_dur_type(beats):
|
||||
for val, info in _DUR_MAP.items():
|
||||
if abs(beats - val) < 0.001:
|
||||
return info
|
||||
return None
|
||||
|
||||
def _split_into_measures(notes, beats_per_measure):
|
||||
beat_in_measure = 0.0
|
||||
for note in notes:
|
||||
tone = note.tone
|
||||
if tone is not None and not hasattr(tone, "name") and not hasattr(tone, "tones"):
|
||||
tone = None
|
||||
remaining = note.duration.value
|
||||
is_first = True
|
||||
while remaining > 0.001:
|
||||
room = beats_per_measure - beat_in_measure
|
||||
if room < 0.001:
|
||||
room = beats_per_measure
|
||||
beat_in_measure = 0.0
|
||||
chunk = min(remaining, room)
|
||||
needs_tie_start = (remaining - chunk) > 0.001
|
||||
needs_tie_stop = not is_first
|
||||
|
||||
yield (tone, chunk, needs_tie_start, needs_tie_stop,
|
||||
note.velocity, note.articulation)
|
||||
|
||||
remaining -= chunk
|
||||
beat_in_measure += chunk
|
||||
is_first = False
|
||||
|
||||
if beat_in_measure >= beats_per_measure - 0.001:
|
||||
beat_in_measure = 0.0
|
||||
|
||||
def _tone_to_pitch_el(tone):
|
||||
pitch = ET.Element("pitch")
|
||||
name = tone.name
|
||||
letter = name[0].upper()
|
||||
acc_str = name[1:] if len(name) > 1 else ""
|
||||
|
||||
step = ET.SubElement(pitch, "step")
|
||||
step.text = letter
|
||||
|
||||
alter_val = 0
|
||||
if acc_str == "#":
|
||||
alter_val = 1
|
||||
elif acc_str == "##":
|
||||
alter_val = 2
|
||||
elif acc_str == "b":
|
||||
alter_val = -1
|
||||
elif acc_str == "bb":
|
||||
alter_val = -2
|
||||
|
||||
if alter_val != 0:
|
||||
alter = ET.SubElement(pitch, "alter")
|
||||
alter.text = str(alter_val)
|
||||
|
||||
octave_el = ET.SubElement(pitch, "octave")
|
||||
octave_el.text = str(tone.octave if tone.octave is not None else 4)
|
||||
|
||||
return pitch
|
||||
|
||||
def _add_note_el(measure, tone, dur_beats, is_chord_continuation,
|
||||
tie_start, tie_stop, velocity):
|
||||
note_el = ET.SubElement(measure, "note")
|
||||
|
||||
if is_chord_continuation:
|
||||
ET.SubElement(note_el, "chord")
|
||||
|
||||
if tone is None:
|
||||
ET.SubElement(note_el, "rest")
|
||||
elif hasattr(tone, "tones"):
|
||||
ET.SubElement(note_el, "rest")
|
||||
else:
|
||||
note_el.append(_tone_to_pitch_el(tone))
|
||||
|
||||
dur_el = ET.SubElement(note_el, "duration")
|
||||
dur_el.text = str(_beats_to_divisions(dur_beats))
|
||||
|
||||
if tie_stop:
|
||||
tie_s = ET.SubElement(note_el, "tie")
|
||||
tie_s.set("type", "stop")
|
||||
if tie_start:
|
||||
tie_s = ET.SubElement(note_el, "tie")
|
||||
tie_s.set("type", "start")
|
||||
|
||||
dur_info = _best_dur_type(dur_beats)
|
||||
if dur_info:
|
||||
type_el = ET.SubElement(note_el, "type")
|
||||
type_el.text = dur_info[0]
|
||||
if dur_info[1]:
|
||||
ET.SubElement(note_el, "dot")
|
||||
|
||||
if tie_start or tie_stop:
|
||||
notations = ET.SubElement(note_el, "notations")
|
||||
if tie_stop:
|
||||
tied = ET.SubElement(notations, "tied")
|
||||
tied.set("type", "stop")
|
||||
if tie_start:
|
||||
tied = ET.SubElement(notations, "tied")
|
||||
tied.set("type", "start")
|
||||
|
||||
# ── Collect voices ──────────────────────────────────────────
|
||||
voices = []
|
||||
if self.notes:
|
||||
voices.append(("default", self.notes))
|
||||
for name, part in self.parts.items():
|
||||
if part.is_drums:
|
||||
continue
|
||||
if not part.notes:
|
||||
continue
|
||||
has_pitched = any(
|
||||
n.tone is not None
|
||||
and (hasattr(n.tone, "name") or hasattr(n.tone, "tones"))
|
||||
for n in part.notes
|
||||
)
|
||||
if not has_pitched:
|
||||
continue
|
||||
voices.append((name, part.notes))
|
||||
|
||||
if not voices:
|
||||
voices.append(("default", []))
|
||||
|
||||
# ── Build XML tree ──────────────────────────────────────────
|
||||
root = ET.Element("score-partwise")
|
||||
root.set("version", "4.0")
|
||||
|
||||
work = ET.SubElement(root, "work")
|
||||
work_title = ET.SubElement(work, "work-title")
|
||||
work_title.text = title
|
||||
|
||||
part_list = ET.SubElement(root, "part-list")
|
||||
ts = self.time_signature
|
||||
beats_per_measure = ts.beats_per_measure
|
||||
|
||||
for idx, (vname, notes) in enumerate(voices, 1):
|
||||
pid = f"P{idx}"
|
||||
sp = ET.SubElement(part_list, "score-part")
|
||||
sp.set("id", pid)
|
||||
pn = ET.SubElement(sp, "part-name")
|
||||
pn.text = vname
|
||||
|
||||
for idx, (vname, notes) in enumerate(voices, 1):
|
||||
pid = f"P{idx}"
|
||||
part_el = ET.SubElement(root, "part")
|
||||
part_el.set("id", pid)
|
||||
|
||||
clef_type = self._guess_clef(notes)
|
||||
|
||||
chunks = list(_split_into_measures(notes, beats_per_measure))
|
||||
|
||||
beat_in_measure = 0.0
|
||||
measure_num = 1
|
||||
measure_el = ET.SubElement(part_el, "measure")
|
||||
measure_el.set("number", str(measure_num))
|
||||
|
||||
attrs = ET.SubElement(measure_el, "attributes")
|
||||
div_el = ET.SubElement(attrs, "divisions")
|
||||
div_el.text = str(DIVISIONS)
|
||||
time_el = ET.SubElement(attrs, "time")
|
||||
beats_el = ET.SubElement(time_el, "beats")
|
||||
beats_el.text = str(ts.beats)
|
||||
bt_el = ET.SubElement(time_el, "beat-type")
|
||||
bt_el.text = str(ts.unit)
|
||||
clef_el = ET.SubElement(attrs, "clef")
|
||||
sign_el = ET.SubElement(clef_el, "sign")
|
||||
line_el = ET.SubElement(clef_el, "line")
|
||||
if clef_type == "bass":
|
||||
sign_el.text = "F"
|
||||
line_el.text = "4"
|
||||
else:
|
||||
sign_el.text = "G"
|
||||
line_el.text = "2"
|
||||
|
||||
direction = ET.SubElement(measure_el, "direction")
|
||||
dir_type = ET.SubElement(direction, "direction-type")
|
||||
metronome = ET.SubElement(dir_type, "metronome")
|
||||
bu = ET.SubElement(metronome, "beat-unit")
|
||||
bu.text = "quarter"
|
||||
pm = ET.SubElement(metronome, "per-minute")
|
||||
pm.text = str(self.bpm)
|
||||
|
||||
for (tone, dur_beats, tie_start, tie_stop,
|
||||
vel, artic) in chunks:
|
||||
|
||||
if beat_in_measure >= beats_per_measure - 0.001:
|
||||
measure_num += 1
|
||||
measure_el = ET.SubElement(part_el, "measure")
|
||||
measure_el.set("number", str(measure_num))
|
||||
beat_in_measure = 0.0
|
||||
|
||||
if tone is not None and hasattr(tone, "tones"):
|
||||
chord_tones = [
|
||||
t for t in tone.tones
|
||||
if hasattr(t, "name") and hasattr(t, "octave")
|
||||
]
|
||||
if not chord_tones:
|
||||
_add_note_el(measure_el, None, dur_beats, False,
|
||||
tie_start, tie_stop, vel)
|
||||
else:
|
||||
for ci, ct in enumerate(chord_tones):
|
||||
_add_note_el(measure_el, ct, dur_beats,
|
||||
ci > 0, tie_start, tie_stop, vel)
|
||||
else:
|
||||
_add_note_el(measure_el, tone, dur_beats, False,
|
||||
tie_start, tie_stop, vel)
|
||||
|
||||
beat_in_measure += dur_beats
|
||||
|
||||
# ── Serialize ───────────────────────────────────────────────
|
||||
raw = ET.tostring(root, encoding="unicode")
|
||||
doctype = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<!DOCTYPE score-partwise PUBLIC '
|
||||
'"-//Recordare//DTD MusicXML 4.0 Partwise//EN" '
|
||||
'"http://www.musicxml.org/dtds/partwise.dtd">\n'
|
||||
)
|
||||
pretty = xml.dom.minidom.parseString(raw).toprettyxml(indent=" ")
|
||||
lines = pretty.split("\n")
|
||||
if lines and lines[0].startswith("<?xml"):
|
||||
lines = lines[1:]
|
||||
return doctype + "\n".join(lines)
|
||||
|
||||
# ── ASCII tablature export ──────────────────────────────────────────
|
||||
|
||||
def to_tab(self, part_name=None, **kwargs):
|
||||
"""Generate ASCII tablature for a part in this score.
|
||||
|
||||
Args:
|
||||
part_name: Name of the part to tab. If *None*, tabs the first
|
||||
non-drum part that has notes.
|
||||
**kwargs: Passed through to :meth:`Part.to_tab` (e.g.
|
||||
``tuning``, ``frets``, ``time_signature``).
|
||||
|
||||
Returns:
|
||||
An ASCII tablature string.
|
||||
|
||||
Raises:
|
||||
ValueError: If no suitable part is found.
|
||||
"""
|
||||
if "time_signature" not in kwargs:
|
||||
kwargs["time_signature"] = self.time_signature
|
||||
|
||||
if part_name is not None:
|
||||
if part_name not in self.parts:
|
||||
raise ValueError(f"No part named {part_name!r}")
|
||||
return self.parts[part_name].to_tab(**kwargs)
|
||||
|
||||
for name, part in self.parts.items():
|
||||
if part.is_drums:
|
||||
continue
|
||||
if not part.notes:
|
||||
continue
|
||||
has_pitched = any(
|
||||
n.tone is not None and not isinstance(n.tone, _DrumTone)
|
||||
for n in part.notes
|
||||
)
|
||||
if has_pitched:
|
||||
return part.to_tab(**kwargs)
|
||||
|
||||
if self.notes:
|
||||
tmp = Part("_default")
|
||||
tmp.notes = list(self.notes)
|
||||
return tmp.to_tab(**kwargs)
|
||||
|
||||
raise ValueError("No pitched parts with notes found in score")
|
||||
|
||||
def save_midi(self, path, velocity=100):
|
||||
"""Export to Standard MIDI File, measure-aware."""
|
||||
ticks_per_beat = 480
|
||||
|
||||
@@ -672,7 +672,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "9.0.2"
|
||||
version = "9.0.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
@@ -683,14 +683,14 @@ dependencies = [
|
||||
{ name = "pygments" },
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d1/db/7ef3487e0fb0049ddb5ce41d3a49c235bf9ad299b6a25d5780a89f19230f/pytest-9.0.2.tar.gz", hash = "sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11", size = 1568901, upload-time = "2025-12-06T21:30:51.014Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3b/ab/b3226f0bd7cdcf710fbede2b3548584366da3b19b5021e74f5bde2a8fa3f/pytest-9.0.2-py3-none-any.whl", hash = "sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b", size = 374801, upload-time = "2025-12-06T21:30:49.154Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytheory"
|
||||
version = "0.41.2"
|
||||
version = "0.42.1"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "rich" },
|
||||
|
||||
Reference in New Issue
Block a user