accompy#
accompy - Generate accompaniment audio from chord charts.
Generate backing tracks with bass, drums, piano from chord progressions, similar to iReal Pro.
Example
>>> from accompy import generate_accompaniment, Score
>>>
>>> # Simple usage
>>> path = generate_accompaniment("| C | Am | F | G |", style="bossa", tempo=120)
>>>
>>> # With Score object for more control
>>> score = Score.from_string("| Dm7 | G7 | C^7 | A7b9 |", title="ii-V-I")
>>> path = generate_accompaniment(score, style="swing", tempo=160, repeats=4)
Available styles: swing, bossa, rock, ballad, funk, latin, waltz, blues
Converter Pipeline:
>>> from accompy import converter, ChordSequence, MidiData, convert
>>> # List available converters for a given step
>>> converter.list_converters(ChordSequence, MidiData)
>>> # Convert using the default or a named converter
>>> midi = convert(chord_seq, MidiData)
>>> midi = convert(chord_seq, MidiData, via="midiutil")
Advanced Usage (Extensibility):
>>> # Register custom patterns
>>> from accompy import get_pattern_registry
>>> registry = get_pattern_registry()
>>> # registry['my_style'] = {'drums': [...], 'bass': [...], 'comp': [...]}
>>>
>>> # Use custom chord resolver
>>> from accompy import set_chord_resolver
>>> # set_chord_resolver(my_custom_resolver)
>>>
>>> # Access protocol definitions for custom implementations
>>> from accompy.protocols import ChordResolver, PatternSource, SynthesizerBackend
Functions
|
Generate an accompaniment audio file from a chord progression. |
|
The note events the builtin backend plays for |
|
The drum, bass and piano events |
|
The |
|
Return unique pitch classes (0-11) as a tuple. |
|
Resolve a pitch offset against a chord. |
|
The bass note a pattern's |
|
The notes the piano plays for a chord: its first four notes moved into C4-B4. |
|
Coerce common chord-progression formats into a |
|
Play an audio file using the system's default audio player. |
Check which dependencies are available. |
|
Print installation instructions for missing dependencies. |
|
|
Convert a songleaf-shaped |
|
Convert source to target_type using the registered converter. |
|
Parse a chord string into a ChordSequence. |
|
Convert chord string or ChordSequence to resolved MIDI notes. |
|
Convert chord string to MIDI data. |
|
Convert chord string to audio. |
|
Convert MidiData to audio. |
|
Convert an iReal Pro HTML/URL file to audio. |
|
Convert an iReal Pro HTML/URL file to MIDI. |
List all available converters organized by pipeline stage. |
|
|
Convert chords to MIDI using a rhythmic skeleton for restrike timing. |
|
Convert chords to audio using a rhythmic skeleton for restrike timing. |
|
Resolve a skeleton specification to a tuple of durations. |
|
Apply a rhythmic skeleton to a chord sequence. |
|
Register a custom rhythmic skeleton. |
|
List available skeleton keys, optionally filtered. |
|
Extract a Score from an iReal Pro HTML export file. |
|
Parse an iReal Pro URL ( |
|
Transpose a |
|
Transpose a chord symbol by semitones. |
|
Transpose a single note name by semitones. |
|
Generate a WAV file from a Score using a pluggable engine. |
|
Alias for |
|
Render a Score to WAV using MMA (Musical MIDI Accompaniment). |
|
Create a |
|
Batch-generate WAV files for many key / tempo / groove combinations. |
|
Render chords to a high-quality audio file, optionally AI-enhanced. |
|
Run |
|
Get all patterns for a given style. |
Get the global pattern registry, initializing if needed. |
|
|
Register a custom style with the global registry. |
|
Verify all dependencies and optionally auto-configure. |
|
Download and configure a SoundFont file. |
Diagnose common setup issues and provide solutions. |
|
Print a comprehensive diagnostic report. |
|
|
Convert chord symbol to MIDI notes using the current default resolver. |
Get the current default chord resolver. |
|
|
Set the default chord resolver. |
|
Resolve chord symbol to MIDI notes using the tonal package (default). |
|
Return the app directory for folder_kind, creating it if needed. |
|
Return a user resource path, seeding from package data if missing. |
|
Return a config file path, seeding from package data if missing. |
|
Return (and create) an artifact sub-directory for kind. |
|
Read a resource file as text. |
|
Read a resource file as a list of non-empty stripped lines. |
|
Read a resource file as JSON. |
Classes
|
A musical score containing chord events and metadata. |
|
A chord at a specific position in the progression. |
|
Configuration for accompaniment generation. |
|
A single MIDI event. |
|
Ordered sequence of (chord_symbol, duration_beats) pairs with metadata. |
|
Ordered sequence of (midi_notes, duration_beats) with metadata. |
|
Container for MIDI data — either as bytes or as a pretty_midi object. |
|
Container for audio data — numpy array + sample rate. |
Registry mapping (source_type, target_type) to named converter functions. |
|
|
Callable that renders a |
|
A drum pattern for one or more measures. |
|
A bass pattern template. |
|
A piano/guitar comping (accompaniment) pattern. |
|
A single drum hit in a pattern. |
|
A melodic note event for bass or other instruments. |
|
Convert chord symbols to MIDI note numbers. |
|
Provides musical patterns for a given style. |
|
Audio synthesis backend. |
|
Real-time accompaniment player (foundation for future work). |
- class accompy.AccompanimentConfig(style='swing', tempo=120, repeats=2, instruments=<factory>, volumes=<factory>, soundfont=None, sample_rate=44100, output_format='wav', chord_resolver=None, pattern_source=None, synthesis_backend=None)[source]#
Bases:
objectConfiguration for accompaniment generation.
This is the single source of truth for all configuration options, including dependency injection hooks for extensibility.
- style#
Musical style (swing, bossa, rock, etc.)
- Type:
Literal['swing','bossa','rock','ballad','funk','latin','waltz','blues']
- class accompy.AudioData(waveform, sr=44100)[source]#
Bases:
objectContainer for audio data — numpy array + sample rate.
>>> import numpy as np >>> ad = AudioData(waveform=np.zeros(44100), sr=44100) >>> ad.duration_seconds 1.0
- class accompy.BassPattern(name, notes)[source]#
Bases:
objectA bass pattern template.
Uses pitch_offset in NoteEvent to specify intervals from the chord root. The actual pitches are determined when the pattern is applied to specific chords.
- class accompy.ChordEvent(symbol, beats=4)[source]#
Bases:
objectA chord at a specific position in the progression.
Example
>>> event = ChordEvent("Dm7", beats=4) >>> event.symbol 'D-7'
- class accompy.ChordResolver(*args, **kwargs)[source]#
Bases:
ProtocolConvert chord symbols to MIDI note numbers.
Example implementation:
>>> def my_resolver(symbol: str) -> list[int]: ... # Return MIDI notes for chord ... return [60, 64, 67] # C major
- class accompy.ChordSequence(chords, title='', key='C', tempo=120, time_signature=(4, 4), sections=list())[source]#
Bases:
objectOrdered sequence of (chord_symbol, duration_beats) pairs with metadata.
This is the canonical internal representation of a chord progression.
>>> cs = ChordSequence([("Dm7", 4.0), ("G7", 4.0), ("Cmaj7", 8.0)]) >>> len(cs) 3 >>> cs[0] ('Dm7', 4.0) >>> cs.total_beats 16.0
- section_chords(label)[source]#
The chords of the first section called
label(case-insensitive), or[].>>> cs = ChordSequence([("C", 4.0), ("G", 4.0)], sections=[("Verse", 0, 1), ("Chorus", 1, 2)]) >>> cs.section_chords("chorus") [('G', 4.0)]
- class accompy.CompingPattern(name, hits)[source]#
Bases:
objectA piano/guitar comping (accompaniment) pattern.
- class accompy.ConverterRegistry[source]#
Bases:
objectRegistry mapping (source_type, target_type) to named converter functions.
Supports multiple converters for the same type pair, distinguished by name. The first registered converter becomes the default.
>>> reg = ConverterRegistry() >>> reg.register(str, int, int, name='builtin') >>> reg[str, int]('42') 42 >>> reg.list_converters(str, int) ['builtin']
- get(source_type, target_type, name=None)[source]#
Get a specific named converter, or the default if name is None.
- Return type:
- class accompy.DrumPattern(name, beats_per_bar, hits)[source]#
Bases:
objectA drum pattern for one or more measures.
Example
>>> pattern = DrumPattern("rock", 4, [DrumHit(0, KICK, 100)]) >>> pattern.beats_per_bar 4
- class accompy.MidiData(bytes_=None, pretty_midi_obj=None, tempo=120, time_signature=(4, 4))[source]#
Bases:
objectContainer for MIDI data — either as bytes or as a pretty_midi object.
Wraps MIDI content so converters have a uniform interface regardless of which MIDI library produced the data.
>>> import io >>> md = MidiData(bytes_=b'MThd...', tempo=120) >>> md.has_bytes True
- class accompy.MidiEvent(time, channel, note, velocity, duration)[source]#
Bases:
objectA single MIDI event.
Used for event-based MIDI generation that enables both batch file creation and future real-time streaming.
- class accompy.NoteEvent(beat, pitch_offset, duration, velocity)[source]#
Bases:
objectA melodic note event for bass or other instruments.
- class accompy.NoteSequence(notes, tempo=120, time_signature=(4, 4))[source]#
Bases:
objectOrdered sequence of (midi_notes, duration_beats) with metadata.
Represents resolved chords — chord symbols have been converted to concrete MIDI note numbers.
>>> ns = NoteSequence([([60, 64, 67], 4.0), ([62, 65, 69], 4.0)]) >>> ns[0] ([60, 64, 67], 4.0)
- class accompy.PatternSource(*args, **kwargs)[source]#
Bases:
ProtocolProvides musical patterns for a given style.
Example
>>> class MyPatternSource: ... def get_patterns(self, style: str) -> dict: ... return {'drums': [...], 'bass': [...], 'comp': [...]} ... def available_styles(self) -> list[str]: ... return ['swing', 'bossa']
- class accompy.RealtimeAccompaniment(config=None, *, on_event=None)[source]#
Bases:
objectReal-time accompaniment player (foundation for future work).
This class separates event scheduling from synthesis, enabling integration with real-time audio systems. Current implementation generates events; future versions will integrate with hum/pyo for actual audio synthesis.
Example (current usage):
>>> from accompy import AccompanimentConfig >>> config = AccompanimentConfig(tempo=120, style='swing') >>> player = RealtimeAccompaniment(config) >>> player.set_chords([('Dm7', 4), ('G7', 4), ('Cmaj7', 8)]) >>> events_iter = player.events() # Get event iterator >>> # Future: for event in events_iter: synth.play(event.note, event.velocity)
Future usage (with hum integration):
>>> from hum.pyo_util import Synth >>> def on_event(event: MidiEvent): ... # Send MIDI event to synth in real-time ... synth.send_note(event.note, event.velocity, event.duration) >>> player = RealtimeAccompaniment(config, on_event=on_event) >>> player.play()
- events()[source]#
Generate events for current chord progression.
Example
>>> player = RealtimeAccompaniment() >>> player.set_chords([('C', 4)]) >>> events = list(player.events()) >>> len(events) > 0 True
- play()[source]#
Play the accompaniment (future implementation).
This will integrate with a real-time synthesis backend (hum/pyo) to actually play audio. Current implementation is a placeholder.
- Raises:
NotImplementedError – Real-time playback not yet implemented
- Return type:
- set_chords(chords)[source]#
Update the chord progression.
- Parameters:
chords (
Any) – Chord progression in any supported format (string, Score, list of tuples, etc.)- Return type:
Example
>>> player = RealtimeAccompaniment() >>> player.set_chords("| Dm7 | G7 | Cmaj7 |") >>> player._score is not None True
- stop()[source]#
Stop playback (future implementation).
- Raises:
NotImplementedError – Real-time playback not yet implemented
- Return type:
- class accompy.Score(measures, title='Untitled', composer='', key='C', time_signature=(4, 4))[source]#
Bases:
objectA musical score containing chord events and metadata.
This is the domain model for chord progressions. It provides a unified representation regardless of input format (string, iReal URL, tuples, etc.).
Example
>>> score = Score.from_string("| C | Am | F | G |", time_signature=(4, 4)) >>> list(score.measures) [['C'], ['A-'], ['F'], ['G']]
- classmethod from_ireal_url(url)[source]#
Parse an iReal Pro URL into a Score.
- Example::
url = “irealb://Autumn%20Leaves=…” score = Score.from_ireal_url(url)
- Return type:
- classmethod from_string(chord_string, *, title='Untitled', key='C', time_signature=(4, 4))[source]#
Parse a chord string into a Score.
Supports formats:
Simple: “C Am F G” (space-separated, one chord per bar)
Bar lines: “| C | Am | F | G |”
Multi-chord bars: “| C Am | F G |” (chords split evenly)
iReal-style: “C-7 F7 | Bb^7 | Eh7 A7b9 |”
Example
>>> Score.from_string("| Dm7 | G7 | C^7 | % |").measures # % means repeat [['D-7'], ['G7'], ['C^7'], ['C^7']]
- Return type:
- class accompy.ScoreToWav(*args, **kwargs)[source]#
Bases:
ProtocolCallable that renders a
Scoreto a WAV file.Any function matching this signature can be used as a
score_to_wavengine ingenerate_wav()andgenerate_variations().
- class accompy.SynthesizerBackend(*args, **kwargs)[source]#
Bases:
ProtocolAudio synthesis backend.
Simpler protocol than AudioRenderer, focused just on synthesis. Used by the synthesis module.
- classmethod is_available()[source]#
Check if this backend’s dependencies are installed.
- Return type:
- Returns:
True if the backend can be used
- accompy.apply_skeleton(cs, skeleton)[source]#
Apply a rhythmic skeleton to a chord sequence.
The skeleton defines strike positions within each measure. Each strike plays whatever chord is active at that beat position. If a strike spans a chord boundary within a measure, it is split so the chord change is respected.
- Parameters:
- Return type:
ChordSequence
- Returns:
A new ChordSequence with chords expanded according to the skeleton.
Example
>>> from accompy.converters import ChordSequence >>> cs = ChordSequence([("Dm7", 2.0), ("G7", 2.0)]) >>> result = apply_skeleton(cs, "tresillo") >>> [(s, d) for s, d in result] [('Dm7', 1.5), ('Dm7', 0.5), ('G7', 1.0), ('G7', 1.0)]
- accompy.bass_pitch(root, chord_notes, pitch_offset)[source]#
The bass note a pattern’s
pitch_offsetplays over a chord.The chord’s root is moved to C2-B2, then the offset is resolved against the chord (
resolve_pitch_offset()), so a pattern’s “3rd” follows the chord’s quality.>>> bass_pitch(57, [57, 60, 64], 4), bass_pitch(48, [48, 52, 55], 4) (48, 40)
- Return type:
- accompy.check_dependencies()[source]#
Check which dependencies are available.
Example
>>> deps = check_dependencies() >>> 'midiutil' in deps True
- accompy.chord_events(chord_notes, *, style='swing', start_beat=0, duration=4, beats_per_bar=4, instruments=None, volumes=None, pattern_source=None)[source]#
The drum, bass and piano events
styleplays over one chord.This is one step of
generate_midi_events(), which calls it for every chord of a score:chord_notesare the chord’s MIDI notes, root first (what a chord resolver returns),start_beatwhere the chord starts anddurationhow many beats it lasts. It reads no tempo and keeps no state between chords.>>> [(e.time, e.channel, e.note) for e in chord_events([48, 52, 55], style="rock", ... duration=1)] [(0, 9, 36), (0, 9, 42), (0.5, 9, 42), (0, 0, 36), (0, 1, 60), (0, 1, 64), (0, 1, 67)]
- accompy.chord_to_notes(symbol)[source]#
Convert chord symbol to MIDI notes using the current default resolver.
This is the main entry point for chord resolution in accompy.
- Parameters:
symbol (
str) – Chord symbol (e.g., “Dm7”, “G7”)- Return type:
- Returns:
List of MIDI note numbers
Example
>>> notes = chord_to_notes("C") >>> len(notes) > 0 True
- accompy.chords_to_audio(chords, *, resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, tempo=120, sr=44100, output_path=None)[source]#
Convert chord string to audio.
This is the complete pipeline: parse -> resolve -> MIDI -> audio.
- Parameters:
chords (
str|ChordSequence) – Chord string or ChordSequenceresolver (
Optional[str]) – Chord resolver (‘pychord’, ‘music21’, ‘mingus’, ‘tonal’)midi_gen (
Optional[str]) – MIDI generator (‘pretty_midi’, ‘midiutil’, ‘mido’)audio_renderer (
Optional[str]) – Audio renderer (‘pretty_midi’, ‘fluidsynth’, ‘tonal’)tempo (
int) – BPMsr (
int) – Sample rateoutput_path (
Optional[str]) – Optional path to write WAV file
- Return type:
- Returns:
AudioData with waveform and sample rate
>>> audio = chords_to_audio("| C | Am | F | G |") >>> audio.write("output.wav")
- accompy.chords_to_midi(chords, *, resolver=None, midi_gen=None, tempo=120, output_path=None)[source]#
Convert chord string to MIDI data.
- Parameters:
chords (
str|ChordSequence) – Chord string or ChordSequenceresolver (
Optional[str]) – Resolver name (‘pychord’, ‘music21’, ‘mingus’, ‘tonal’)midi_gen (
Optional[str]) – MIDI generator name (‘pretty_midi’, ‘midiutil’, ‘mido’)tempo (
int) – BPMoutput_path (
Optional[str]) – Optional path to write MIDI file
- Return type:
- Returns:
MidiData object
>>> md = chords_to_midi("| C | Am | F | G |") >>> md.to_bytes()[:4] b'MThd'
- accompy.chords_to_notes(chords, *, resolver=None, tempo=120)[source]#
Convert chord string or ChordSequence to resolved MIDI notes.
- Parameters:
chords (
str|ChordSequence) – Chord string or ChordSequenceresolver (
Optional[str]) – Resolver name (‘pychord’, ‘music21’, ‘mingus’, ‘tonal’)tempo (
int) – BPM (used if chords is a string)
- Return type:
- Returns:
NoteSequence with MIDI note numbers
>>> ns = chords_to_notes("| C | Am |") >>> len(ns) 2 >>> all(0 <= n <= 127 for notes, _ in ns for n in notes) True
- accompy.chords_to_sequence(chords, *, parser=None, tempo=120, title='', key='C', time_signature=(4, 4))[source]#
Parse a chord string into a ChordSequence.
- Parameters:
- Return type:
- Returns:
ChordSequence with parsed chords
>>> cs = chords_to_sequence("| Dm7 | G7 | Cmaj7 |", tempo=140) >>> cs.symbols ['Dm7', 'G7', 'Cmaj7'] >>> cs.tempo 140
- accompy.comp_voicing(chord_notes)[source]#
The notes the piano plays for a chord: its first four notes moved into C4-B4.
A chord with no notes is voiced as a C major triad.
>>> comp_voicing([50, 53, 57, 60, 64]), comp_voicing([]) ([62, 65, 69, 60], [60, 64, 67])
- accompy.convert(source, target_type, *, via=None)[source]#
Convert source to target_type using the registered converter.
- Parameters:
- Return type:
- Returns:
Converted data of target_type
Example:
>>> # After converters are registered: >>> # audio = convert(chord_seq, AudioData)
- accompy.diagnose_issues()[source]#
Diagnose common setup issues and provide solutions.
Example:
from accompy.setup_utils import diagnose_issues for issue, desc, solution in diagnose_issues(): print(f"{issue}: {desc}") print(f"Solution: {solution}")
- accompy.ensure_score(chords, *, title='Untitled', key='C', time_signature=(4, 4))[source]#
Coerce common chord-progression formats into a
Score.Supported inputs:
Score: returned as-isstr: chord string (e.g."| C | Am | F | G |") OR iReal URL (irealbook://...)Iterable[tuple[str, int|float]]: list of(chord, beats)like inaccompanyIterable[str]: chord symbols, one per barlist[list[str]]: already-parsed measures
Notes
Score.measuresinaccompydoes not encode per-chord durations within a bar. For(chord, beats)inputs, durations not equal to whole bars are approximated by grouping chords into bars.
Examples
>>> ensure_score("| C | Am | F | G |", time_signature=(4, 4)).measures [['C'], ['A-'], ['F'], ['G']] >>> ensure_score([("F#m7b5", 4), ("B7", 4), ("Em", 8)], key="E").measures[:3] [['F#h7'], ['B7'], ['E-']]
- Return type:
- accompy.file_to_audio(filepath, *, output_path=None, n_repeats=1, transpose=0, resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, tempo=None, sr=44100)[source]#
Convert an iReal Pro HTML/URL file to audio.
Handles:
iReal Pro HTML files (exported from the app)
iReal Pro URL strings
Plain chord text files
Supports repeating the progression and transposing.
- Parameters:
filepath (
str) – Path to an iReal HTML file, or a chord text fileoutput_path (
str|None) – Where to write audio. If None, uses filepath with .wav extensionn_repeats (
int) – Number of times to repeat the progression (default 1)transpose (
int) – Semitones to transpose (positive=up, negative=down)tempo (
int|None) – Override BPM (None = use file’s tempo or 120)sr (
int) – Sample rate
- Return type:
- Returns:
AudioData
Example:
>>> file_to_audio("/path/to/song.html") >>> file_to_audio("/path/to/song.html", n_repeats=40) >>> file_to_audio("/path/to/song.html", transpose=5)
- accompy.file_to_midi(filepath, *, output_path=None, n_repeats=1, transpose=0, resolver=None, midi_gen=None, tempo=None)[source]#
Convert an iReal Pro HTML/URL file to MIDI.
Same as file_to_audio but outputs MIDI instead.
- Parameters:
- Return type:
- Returns:
MidiData
- accompy.generate_accompaniment(chords, *, style='swing', tempo=120, repeats=1, output_path=None, output_format=None, config=None, use_mma=True, backend=None, autoplay=False)[source]#
Generate an accompaniment audio file from a chord progression.
This is the main entry point for accompy. It generates backing tracks with bass, drums, and piano from chord progressions.
- Parameters:
chords (
Any) – Chord progression (string, Score, list of tuples, iReal URL)style (
Literal['swing','bossa','rock','ballad','funk','latin','waltz','blues']) – Musical style (swing, bossa, rock, ballad, funk, latin, waltz, blues)tempo (
int) – Tempo in BPMrepeats (
int) – Number of times to repeat the progressionoutput_path (
Union[str,Path,None]) – Where to save the file (None = temp file)output_format (
Optional[Literal['wav','mp3','flac','midi','mid']]) – Output format (wav, mp3, flac, midi)config (
Optional[AccompanimentConfig]) – Full configuration object (overrides other params if provided)use_mma (
bool) – If True and MMA available, use MMA backendbackend (
Optional[Literal['auto','mma','builtin']]) – Explicitly select backend (‘auto’, ‘mma’, ‘builtin’)autoplay (
bool) – If True, automatically play the generated audio
- Return type:
- Returns:
Path to the generated audio/MIDI file
Example
>>> from accompy import generate_accompaniment >>> path = generate_accompaniment("| C | Am | F | G |", style="bossa", tempo=140) >>> print(f"Generated: {path}")
Note
Requires FluidSynth and a SoundFont for audio rendering. For MIDI-only output, use output_format=”midi”.
- accompy.generate_events(chords, *, style='swing', repeats=1, time_signature=None, instruments=None, volumes=None, pattern_source=None, chord_resolver=None)[source]#
The note events the builtin backend plays for
chords, without writing a file.chordsis anythingaccompy.ensure_score()accepts (a chord string, an iReal URL, measures, chord symbols,(chord, beats)pairs, a Score);time_signatureapplies to the forms that do not carry one (default: the style’s, seestyle_time_signature(): 3/4 forwaltz, else 4/4). Times and durations are in beats: the events do not depend on tempo.repeatsdefaults to 1, as inaccompy.generate_accompaniment().>>> events = generate_events("| C | G |", style="bossa") >>> events[0] MidiEvent(time=0, channel=9, note=37, velocity=56, duration=0.25) >>> max(e.time for e in events) < 8 True
- accompy.generate_mma_wav(score, output_path, *, groove='Swing', tempo=120, repeats=1)#
Render a Score to WAV using MMA (Musical MIDI Accompaniment).
Accepts any valid MMA groove name (e.g.
"Bebop","GypsyJazz"). Runmma -Dgto list available grooves.- Parameters:
- Return type:
- Returns:
Path to the generated WAV file.
- Raises:
RuntimeError – If MMA is not installed or the groove is invalid.
- accompy.generate_variations(score, output_dir, *, keys=('C',), tempos=(120,), grooves=('Swing',), repeats=1, filename_template='{title}_{key}_{tempo}bpm_{groove}.wav', score_to_wav=None)[source]#
Batch-generate WAV files for many key / tempo / groove combinations.
Produces one WAV for each
(key, tempo, groove)triple (cycled from the shortest sequences). Useful for creating practice backing-track collections.- Parameters:
grooves (
Sequence[str]) – Groove / style names to cycle through.repeats (
int) – Number of repeats per file.filename_template (
str) – Template for filenames. Placeholders:{title},{key},{tempo},{groove}.score_to_wav (
Optional[ScoreToWav]) – Engine callable. Defaults tomma_score_to_wav().
- Return type:
- Returns:
List of Paths to successfully generated files.
Example:
>>> from accompy import Score, generate_variations >>> score = Score.from_string("| C6 | Do | C6/E | Fo |", key="C") >>> generate_variations( ... score, "/tmp/variations", ... keys=["C", "G", "F"], ... tempos=[100, 120], ... grooves=["Swing", "BossaNova"], ... ) >>> # With a custom engine: >>> from accompy.tools import make_converter_engine >>> engine = make_converter_engine(audio_renderer="fluidsynth") >>> generate_variations( ... score, "/tmp/variations", ... keys=["C", "G"], ... tempos=[100, 120], ... grooves=["Swing"], ... score_to_wav=engine, ... )
- accompy.generate_wav(score, output_path, *, groove='Swing', tempo=120, repeats=1, score_to_wav=None)[source]#
Generate a WAV file from a Score using a pluggable engine.
By default uses MMA (Musical MIDI Accompaniment). Pass a custom
score_to_wavcallable to use a different backend — for instance one built withmake_converter_engine().- Parameters:
groove (
str) – Groove / style name (interpretation depends on the engine).tempo (
int) – Tempo in BPM.repeats (
int) – Number of times to repeat the progression.score_to_wav (
Optional[ScoreToWav]) – Engine callable. Defaults tomma_score_to_wav().
- Return type:
- Returns:
Path to the generated WAV file.
Example:
>>> from accompy import Score, generate_wav >>> score = Score.from_string("| Dm7 | G7 | C^7 |") >>> generate_wav(score, "/tmp/test.wav", groove="BossaNova", tempo=140) PosixPath('/tmp/test.wav') >>> # With a custom engine: >>> from accompy.tools import make_converter_engine >>> engine = make_converter_engine(audio_renderer="fluidsynth") >>> generate_wav(score, "/tmp/test.wav", score_to_wav=engine, tempo=140)
- accompy.get_app_folder(*, folder_kind='data')[source]#
Return the app directory for folder_kind, creating it if needed.
- Return type:
- accompy.get_artifact_dir(kind)#
Return (and create) an artifact sub-directory for kind.
- Return type:
- accompy.get_chord_resolver()[source]#
Get the current default chord resolver.
Example
>>> resolver = get_chord_resolver() >>> notes = resolver("C") >>> len(notes) > 0 True
- accompy.get_config(name)#
Return a config file path, seeding from package data if missing.
- Return type:
- accompy.get_pattern_registry()[source]#
Get the global pattern registry, initializing if needed.
- Return type:
- Returns:
The global PatternRegistry instance
Example
>>> registry = get_pattern_registry() >>> 'swing' in registry True
- accompy.get_patterns(style)[source]#
Get all patterns for a given style.
- Return type:
- Returns:
Dict with ‘drums’, ‘bass’, ‘comp’ keys containing pattern lists
Example
>>> patterns = get_patterns("bossa") >>> drums = patterns["drums"][0] >>> drums.name 'bossa'
- accompy.get_resource(name)#
Return a user resource path, seeding from package data if missing.
- Return type:
- accompy.list_available_converters()[source]#
List all available converters organized by pipeline stage.
>>> info = list_available_converters() >>> 'parsers' in info True >>> 'resolvers' in info True
- accompy.list_skeletons(*, beats_per_measure=None, style=None)[source]#
List available skeleton keys, optionally filtered.
- Parameters:
- Return type:
- Returns:
List of skeleton key strings.
Examples
>>> "tresillo" in list_skeletons() True >>> all(RHYTHMIC_SKELETONS[k]["beats_per_measure"] == 3 ... for k in list_skeletons(beats_per_measure=3)) True
- accompy.load_resource_lines(name)[source]#
Read a resource file as a list of non-empty stripped lines.
- accompy.make_converter_engine(*, resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, sr=44100)[source]#
Create a
ScoreToWavengine from accompy’s converter pipeline.This wraps the
ChordSequence → NoteSequence → MidiData → AudioDataconverter chain into the same interface thatgenerate_wav()expects, so you can swap it in place of the default MMA engine.- Parameters:
resolver (
Optional[str]) – Chord resolver name (e.g."pychord","tonal").midi_gen (
Optional[str]) – MIDI generator name (e.g."pretty_midi","midiutil").audio_renderer (
Optional[str]) – Audio renderer name (e.g."fluidsynth","pretty_midi").soundfont (
Optional[str]) – Path to a SoundFont file (for FluidSynth-based renderers).sr (
int) – Sample rate.
- Return type:
- Returns:
A callable matching the
ScoreToWavprotocol.
Example:
>>> engine = make_converter_engine(audio_renderer="fluidsynth") >>> generate_wav(score, "/tmp/out.wav", score_to_wav=engine, tempo=120)
- accompy.midi_to_audio(midi_data, *, audio_renderer=None, soundfont=None, sr=44100, output_path=None)[source]#
Convert MidiData to audio.
- Parameters:
- Return type:
- Returns:
AudioData
>>> audio = midi_to_audio(some_midi_data)
- accompy.mma_score_to_wav(score, output_path, *, groove='Swing', tempo=120, repeats=1)[source]#
Render a Score to WAV using MMA (Musical MIDI Accompaniment).
Accepts any valid MMA groove name (e.g.
"Bebop","GypsyJazz"). Runmma -Dgto list available grooves.- Parameters:
- Return type:
- Returns:
Path to the generated WAV file.
- Raises:
RuntimeError – If MMA is not installed or the groove is invalid.
- accompy.parse_ireal_html(html_path)[source]#
Extract a Score from an iReal Pro HTML export file.
iReal Pro can export songs as HTML files containing an
irealb://link. This function reads the file, extracts that link, and parses it into aScore.- Parameters:
html_path (
str) – Path to the HTML file exported from iReal Pro.- Return type:
Score
- Returns:
A Score with measures, title, key, and time signature.
- Raises:
FileNotFoundError – If html_path does not exist.
ValueError – If no iReal URL is found in the HTML.
Example:
>>> score = parse_ireal_html("/path/to/song.html") >>> score.title 'Autumn Leaves'
- accompy.parse_ireal_url(url)[source]#
Parse an iReal Pro URL (
irealb://orirealbook://) into a Score.Decoding is
accompy.ireal.decode_ireal_url(); the Score is the first tune of the URL that has chords, each bar the list of its chords as written (iReal chord notation). RaisesValueErrorwhen no tune has chords.>>> score = parse_ireal_url("irealbook://Blues=Me=Swing=F=n=[T34F7 |Bb7 Bo7 |C7 Z") >>> score.measures, score.time_signature ([['F7'], ['Bb7', 'Bo7'], ['C7']], (3, 4))
- accompy.play_audio(audio_path)[source]#
Play an audio file using the system’s default audio player.
- Parameters:
- Return type:
- Returns:
True if playback started successfully, False otherwise
Example
>>> from accompy import play_audio >>> play_audio("/path/to/audio.wav")
- accompy.print_setup_instructions()[source]#
Print installation instructions for missing dependencies.
- accompy.register_skeleton(key, pattern, *, name='', beats_per_measure=None, styles=None)[source]#
Register a custom rhythmic skeleton.
- Parameters:
- Return type:
Example
>>> register_skeleton("my_groove", (1, 0.5, 0.5, 2), name="My Groove") >>> resolve_skeleton("my_groove") (1, 0.5, 0.5, 2)
- accompy.register_style(style, drums, bass, comp)[source]#
Register a custom style with the global registry.
- Parameters:
- Return type:
Example
>>> registry = get_pattern_registry() >>> register_style('my_funk', [my_drum_pattern], [my_bass_pattern], [])
- accompy.render_chords(chords, *, rhythmic_skeleton='whole_note', bpm=100, transpose=0, n_loops=None, max_seconds=None, ai_enhance=True, suno_mode='cover', prompt_template='{genre} backing track with {instruments}', genre='jazz', instruments=None, audio_weight=0.99, style_weight=0.51, weirdness=0.0, model='', instrumental=True, wait_for_completion=True, poll_interval=15.0, timeout=600.0, chords_to_midi_audio=None, audio_to_enhanced_audio=None, midi_store=None, midi_audio_store=None, enhanced_audio_store=None, resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, sr=44100)[source]#
Render chords to a high-quality audio file, optionally AI-enhanced.
- Parameters:
chords – Chord input — string (
"| Dm7 | G7 | C^7 |"), iReal URL,ChordSequence,Score, or list of(chord, beats)tuples.rhythmic_skeleton (
str|tuple[float,...]) – Restrike pattern within each measure.bpm (
int) – Tempo in beats per minute.transpose (
int) – Semitones to transpose (positive=up, negative=down).n_loops (
int|None) – Explicit number of loops. Mutually exclusive with max_seconds.max_seconds (
float|None) – Target maximum duration; computes loop count automatically. Defaults to 210 (3.5 min) when neither n_loops nor max_seconds is given.ai_enhance (
Union[bool,Callable,None]) –Truefor default Suno enhancement,False/Noneto skip, or a callable(audio_path, prompt, **kw) → bytes.suno_mode (
str) –"cover"(default, re-generates in style) or"extend".prompt_template (
str) – Template with{genre}and{instruments}placeholders.genre (
str) – Genre/style tags for the AI prompt.instruments (
list[str] |None) – Instrument list for the AI prompt. Defaults to["piano", "bass", "drums"].audio_weight (
float) – How much the source audio influences AI output (0–1).style_weight (
float) – How much the style prompt influences AI output (0–1).weirdness (
float) – Creative deviation for cover mode (0–1).model (
str) – Suno model version (e.g."V4_5").instrumental (
bool) – If True, generate without vocals.wait_for_completion (
bool) – If True, poll until AI generation is ready.poll_interval (
float) – Seconds between AI status checks.timeout (
float) – Max seconds to wait for AI completion.chords_to_midi_audio (
Optional[Callable]) – Override for the MIDI audio rendering step. Callable:(ChordSequence, **kw) → AudioData.audio_to_enhanced_audio (
Optional[Callable]) – Override for the AI enhancement step. Callable:(audio_path, prompt, **kw) → bytes.midi_store (
MutableMapping|None) – Optional store for MIDI files.None= don’t persist MIDI.midi_audio_store (
MutableMapping|None) – Store for rendered MIDI audio.None= default file store under~/.local/share/accompy/artifacts/midi_audio/.enhanced_audio_store (
MutableMapping|None) – Store for AI-enhanced audio.None= default file store under~/.local/share/accompy/artifacts/enhanced_audio/.sr (
int) – Sample rate for MIDI audio rendering.
- Return type:
- Returns:
Filesystem path to the final audio file.
- accompy.render_chords_batch(configs, **shared_kwargs)[source]#
Run
render_chords()for each config dict.Each dict in configs is merged with shared_kwargs (per-config values take priority over shared defaults).
- Parameters:
configs (
Iterable[dict]) – Iterable of dicts, each containing keyword arguments forrender_chords().**shared_kwargs – Default arguments applied to every config.
- Return type:
- Returns:
List of filesystem paths to the final audio files.
Example:
>>> from itertools import product >>> configs = [ ... dict(chords="| Dm7 | G7 | C^7 |", genre=g, bpm=b) ... for g, b in product(["jazz", "lofi"], [100, 120]) ... ] >>> paths = render_chords_batch(configs, ai_enhance=False)
- accompy.resolve_pitch_offset(*, root_pc, chord_pcs, target_offset)[source]#
Resolve a pitch offset against a chord.
The patterns use semitone offsets (0=root, 7=5th, etc.). When an offset represents a chord tone which varies by quality (e.g. 3rd), we prefer a matching chord tone from
chord_pcs.Examples
For a minor chord, a pattern might request offset 4 (“3rd”); this function will choose 3 if the chord contains a minor 3rd.
- Return type:
- accompy.resolve_skeleton(skeleton)[source]#
Resolve a skeleton specification to a tuple of durations.
Accepts:
A tuple or list of numbers (pass-through)
A skeleton key (e.g.,
"tresillo","whole_note")A skeleton name, case-insensitive (e.g.,
"Tresillo")A style string (e.g.,
"reggae") — returns the first match
- Return type:
- Returns:
Tuple of beat durations summing to the measure length.
- Raises:
KeyError – If the skeleton cannot be resolved.
Examples
>>> resolve_skeleton("whole_note") (4,) >>> resolve_skeleton("tresillo") (1.5, 1.5, 1) >>> resolve_skeleton((2, 2)) (2, 2) >>> resolve_skeleton("Dotted half + quarter") (3, 1)
- accompy.rhythm_to_audio(chords, *, skeleton='whole_note', resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, tempo=120, sr=44100, output_path=None)[source]#
Convert chords to audio using a rhythmic skeleton for restrike timing.
Same as
rhythm_to_midi()but renders all the way to audio.- Parameters:
- Return type:
- Returns:
AudioData with waveform and sample rate.
Example
>>> audio = rhythm_to_audio("| C | Am |", skeleton="half_notes")
- accompy.rhythm_to_midi(chords, *, skeleton='whole_note', resolver=None, midi_gen=None, tempo=120, output_path=None)[source]#
Convert chords to MIDI using a rhythmic skeleton for restrike timing.
The skeleton defines when chords are struck within each measure. Each chord is sustained for the skeleton’s duration at that beat position.
- Parameters:
chords (
str|ChordSequence) – Chord string (e.g.,"| Dm7 | G7 | Cmaj7 |") or ChordSequence.skeleton (
str|tuple[float,...]) – Skeleton key, name, style, or duration tuple. Defaults to"whole_note"(one strike per measure).resolver (
str|None) – Chord resolver name (e.g.,"pychord","tonal").midi_gen (
str|None) – MIDI generator name (e.g.,"pretty_midi","midiutil").tempo (
int) – BPM (used if chords is a string).output_path (
str|None) – Optional path to write MIDI file.
- Return type:
- Returns:
MidiData object.
Example
>>> md = rhythm_to_midi("| C | Am | F | G |", skeleton="tresillo") >>> md.to_bytes()[:4] b'MThd'
- accompy.select_patterns(patterns, beats_per_bar)[source]#
The
(drum, bass, comp)patterns the renderer plays from a style’s pattern lists.The drum pattern is the first one whose
beats_per_barmatches (else the first); bass and comping take the first of their list. A missing one isNone.>>> from accompy.patterns import get_patterns >>> [p.name for p in select_patterns(get_patterns("swing"), 4)] ['swing_basic', 'walking', 'swing_comp']
- Return type:
- accompy.set_chord_resolver(resolver)[source]#
Set the default chord resolver.
This enables global customization of chord-to-notes resolution.
- Parameters:
resolver (
Callable[[str],list[int]]) – A function that takes a chord symbol (str) and returns MIDI notes (list[int])- Return type:
Example
>>> def my_resolver(symbol: str) -> list[int]: ... # Custom chord voicing logic ... return [60, 64, 67] # C major triad >>> previous = get_chord_resolver() >>> set_chord_resolver(my_resolver) >>> chord_to_notes("Dm7") [60, 64, 67] >>> set_chord_resolver(previous) # put the default back: the setting is process-global
- accompy.setup_soundfont(force=False)[source]#
Download and configure a SoundFont file.
- Parameters:
force (
bool) – If True, download even if a SoundFont already exists- Return type:
- Returns:
True if successful, False otherwise
Example:
from accompy.setup_utils import setup_soundfont if setup_soundfont(): print("SoundFont configured successfully!")
- accompy.song_to_chord_sequence(song, *, bars_per_line=None, beats_per_chord=None, beats_per_bar=4, tempo=120)[source]#
Convert a songleaf-shaped
songto aChordSequence.- Parameters:
song (
Any) – Anything withtext,annotationsandmetaas songleaf’sSong.bars_per_line (
Optional[float]) – Bars each chord-carrying line lasts, shared by its chords.beats_per_chord (
Optional[float]) – Beats every chord lasts. Exclusive withbars_per_line.beats_per_bar (
int) – Beats in a bar (the time signature’s numerator).tempo (
int) – Tempo in BPM (the song’smeta["tempo"]wins when it is a number).
- Return type:
- Returns:
A ChordSequence whose
sectionsfollow the song’ssectionannotations (ranges over the chords), with the song’s title and key.- Raises:
ValueError – if both
bars_per_lineandbeats_per_chordare given, or either is not positive.
- accompy.tonal_resolver(symbol, *, transpose=-12)[source]#
Resolve chord symbol to MIDI notes using the tonal package (default).
The tonal package is lightweight and designed for music theory operations. It anchors chord roots around C4=60. We apply a default -12 semitone transpose to voice chords closer to C3=48 for better bass/piano range.
- Parameters:
- Return type:
- Returns:
List of MIDI note numbers
Example
>>> notes = tonal_resolver("Cmaj7") >>> len(notes) > 0 True
Note
Requires: pip install tonal See: thorwhalen/tonal
- accompy.transpose_chord(chord, semitones, *, use_flat=None)[source]#
Transpose a chord symbol by semitones.
Handles slash chords (e.g.
"C6/E").- Parameters:
chord (
str) – Chord symbol like"Am7","C6/E","G#o".semitones (
int) – Number of semitones.use_flat (
Optional[bool]) – Force flat/sharp spelling (seetranspose_note()).
- Return type:
Example
>>> transpose_chord("Am7", 2) 'Bm7' >>> transpose_chord("C6/E", 5) 'F6/A' >>> transpose_chord("G#o", -2, use_flat=True) 'Gbo'
- accompy.transpose_note(name, semitones, *, use_flat=None)[source]#
Transpose a single note name by semitones.
- Parameters:
- Return type:
Example
>>> transpose_note("C", 5) 'F' >>> transpose_note("A", -2) 'G' >>> transpose_note("C", 1, use_flat=True) 'Db'
- accompy.transpose_score(score, target_key)[source]#
Transpose a
Scoreto a new key.The spelling (sharp vs flat) is chosen automatically based on the target_key.
- Parameters:
- Return type:
Score
- Returns:
A new Score in the target key with an updated title.
Example
>>> from accompy import Score >>> s = Score.from_string("| C | Am | F | G |", key="C") >>> t = transpose_score(s, "G") >>> [m[0] for m in t.measures] ['G', 'E-', 'C', 'D']
- accompy.verify_and_setup(interactive=True, auto_fix=False)[source]#
Verify all dependencies and optionally auto-configure.
- Parameters:
- Return type:
- Returns:
Dict mapping dependency name to whether it’s available
Example
>>> from accompy.setup_utils import verify_and_setup >>> status = verify_and_setup(interactive=False) >>> if all(status.values()): ... print("Ready to use!")
Modules
Audio renderers — convert MidiData to AudioData. |
|
Core domain models for accompy. |
|
Chord sheet parsers — convert various text formats to ChordSequence. |
|
Chord symbol to MIDI notes resolution. |
|
Chord resolvers — convert chord symbols to MIDI note numbers. |
|
Core types for the chord-to-audio pipeline. |
|
Per-user data directory management for accompy. |
|
Decode iReal Pro URLs ( |
|
Main accompaniment generation module. |
|
MIDI generators — convert NoteSequence to MidiData. |
|
Pattern registry and access for accompany patterns. |
|
High-level pipeline API — one-call chord-to-audio conversion. |
|
Protocols defining extensibility contracts for accompy. |
|
Real-time accompaniment support (foundation). |
|
MIDI and MMA rendering backends for accompy. |
|
High-quality chord rendering pipeline — from chord charts to AI-enhanced audio. |
|
Rhythmic skeletons — duration-only measure patterns for simple accompaniment. |
|
Setup and configuration utilities for accompy. |
|
Songs as backing-track input: a |
|
Audio synthesis backends for accompy. |
|
Tools for generating accompaniment audio from Score objects. |
|
Utility functions for chord parsing and normalization. |
|
Backward-compatibility shim — wips modules have moved to accompy top level. |