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_accompaniment(chords, *[, style, ...])

Generate an accompaniment audio file from a chord progression.

generate_events(chords, *[, style, repeats, ...])

The note events the builtin backend plays for chords, without writing a file.

chord_events(chord_notes, *[, style, ...])

The drum, bass and piano events style plays over one chord.

select_patterns(patterns, beats_per_bar)

The (drum, bass, comp) patterns the renderer plays from a style's pattern lists.

pitch_classes(notes)

Return unique pitch classes (0-11) as a tuple.

resolve_pitch_offset(*, root_pc, chord_pcs, ...)

Resolve a pitch offset against a chord.

bass_pitch(root, chord_notes, pitch_offset)

The bass note a pattern's pitch_offset plays over a chord.

comp_voicing(chord_notes)

The notes the piano plays for a chord: its first four notes moved into C4-B4.

ensure_score(chords, *[, title, key, ...])

Coerce common chord-progression formats into a Score.

play_audio(audio_path)

Play an audio file using the system's default audio player.

check_dependencies()

Check which dependencies are available.

print_setup_instructions()

Print installation instructions for missing dependencies.

song_to_chord_sequence(song, *[, ...])

Convert a songleaf-shaped song to a ChordSequence.

convert(source, target_type, *[, via])

Convert source to target_type using the registered converter.

chords_to_sequence(chords, *[, parser, ...])

Parse a chord string into a ChordSequence.

chords_to_notes(chords, *[, resolver, tempo])

Convert chord string or ChordSequence to resolved MIDI notes.

chords_to_midi(chords, *[, resolver, ...])

Convert chord string to MIDI data.

chords_to_audio(chords, *[, resolver, ...])

Convert chord string to audio.

midi_to_audio(midi_data, *[, ...])

Convert MidiData to audio.

file_to_audio(filepath, *[, output_path, ...])

Convert an iReal Pro HTML/URL file to audio.

file_to_midi(filepath, *[, output_path, ...])

Convert an iReal Pro HTML/URL file to MIDI.

list_available_converters()

List all available converters organized by pipeline stage.

rhythm_to_midi(chords, *[, skeleton, ...])

Convert chords to MIDI using a rhythmic skeleton for restrike timing.

rhythm_to_audio(chords, *[, skeleton, ...])

Convert chords to audio using a rhythmic skeleton for restrike timing.

resolve_skeleton(skeleton)

Resolve a skeleton specification to a tuple of durations.

apply_skeleton(cs, skeleton)

Apply a rhythmic skeleton to a chord sequence.

register_skeleton(key, pattern, *[, name, ...])

Register a custom rhythmic skeleton.

list_skeletons(*[, beats_per_measure, style])

List available skeleton keys, optionally filtered.

parse_ireal_html(html_path)

Extract a Score from an iReal Pro HTML export file.

parse_ireal_url(url)

Parse an iReal Pro URL (irealb:// or irealbook://) into a Score.

transpose_score(score, target_key)

Transpose a Score to a new key.

transpose_chord(chord, semitones, *[, use_flat])

Transpose a chord symbol by semitones.

transpose_note(name, semitones, *[, use_flat])

Transpose a single note name by semitones.

generate_wav(score, output_path, *[, ...])

Generate a WAV file from a Score using a pluggable engine.

generate_mma_wav(score, output_path, *[, ...])

Alias for mma_score_to_wav().

mma_score_to_wav(score, output_path, *[, ...])

Render a Score to WAV using MMA (Musical MIDI Accompaniment).

make_converter_engine(*[, resolver, ...])

Create a ScoreToWav engine from accompy's converter pipeline.

generate_variations(score, output_dir, *[, ...])

Batch-generate WAV files for many key / tempo / groove combinations.

render_chords(chords, *[, ...])

Render chords to a high-quality audio file, optionally AI-enhanced.

render_chords_batch(configs, **shared_kwargs)

Run render_chords() for each config dict.

get_patterns(style)

Get all patterns for a given style.

get_pattern_registry()

Get the global pattern registry, initializing if needed.

register_style(style, drums, bass, comp)

Register a custom style with the global registry.

verify_and_setup([interactive, auto_fix])

Verify all dependencies and optionally auto-configure.

setup_soundfont([force])

Download and configure a SoundFont file.

diagnose_issues()

Diagnose common setup issues and provide solutions.

print_diagnostic_report()

Print a comprehensive diagnostic report.

chord_to_notes(symbol)

Convert chord symbol to MIDI notes using the current default resolver.

get_chord_resolver()

Get the current default chord resolver.

set_chord_resolver(resolver)

Set the default chord resolver.

tonal_resolver(symbol, *[, transpose])

Resolve chord symbol to MIDI notes using the tonal package (default).

get_app_folder(*[, folder_kind])

Return the app directory for folder_kind, creating it if needed.

get_resource(name)

Return a user resource path, seeding from package data if missing.

get_config(name)

Return a config file path, seeding from package data if missing.

get_artifact_dir(kind)

Return (and create) an artifact sub-directory for kind.

load_resource_text(name)

Read a resource file as text.

load_resource_lines(name)

Read a resource file as a list of non-empty stripped lines.

load_resource_json(name)

Read a resource file as JSON.

Classes

Score(measures[, title, composer, key, ...])

A musical score containing chord events and metadata.

ChordEvent(symbol[, beats])

A chord at a specific position in the progression.

AccompanimentConfig([style, tempo, repeats, ...])

Configuration for accompaniment generation.

MidiEvent(time, channel, note, velocity, ...)

A single MIDI event.

ChordSequence(chords[, title, key, tempo, ...])

Ordered sequence of (chord_symbol, duration_beats) pairs with metadata.

NoteSequence(notes[, tempo, time_signature])

Ordered sequence of (midi_notes, duration_beats) with metadata.

MidiData([bytes_, pretty_midi_obj, tempo, ...])

Container for MIDI data — either as bytes or as a pretty_midi object.

AudioData(waveform[, sr])

Container for audio data — numpy array + sample rate.

ConverterRegistry()

Registry mapping (source_type, target_type) to named converter functions.

ScoreToWav(*args, **kwargs)

Callable that renders a Score to a WAV file.

DrumPattern(name, beats_per_bar, hits)

A drum pattern for one or more measures.

BassPattern(name, notes)

A bass pattern template.

CompingPattern(name, hits)

A piano/guitar comping (accompaniment) pattern.

DrumHit(beat, drum, velocity)

A single drum hit in a pattern.

NoteEvent(beat, pitch_offset, duration, velocity)

A melodic note event for bass or other instruments.

ChordResolver(*args, **kwargs)

Convert chord symbols to MIDI note numbers.

PatternSource(*args, **kwargs)

Provides musical patterns for a given style.

SynthesizerBackend(*args, **kwargs)

Audio synthesis backend.

RealtimeAccompaniment([config, on_event])

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: object

Configuration 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']

tempo#

Beats per minute

Type:

int

repeats#

Number of times to play through the form

Type:

int

instruments#

Which instruments to include

Type:

dict[str, bool]

volumes#

Relative volume for each instrument (0.0-1.0)

Type:

dict[str, float]

soundfont#

Path to SoundFont file for synthesis

Type:

Optional[Path]

sample_rate#

Audio sample rate

Type:

int

output_format#

Output file format

Type:

Literal['wav', 'mp3', 'flac', 'midi']

chord_resolver#

Optional custom chord resolution function

Type:

Optional[Any]

pattern_source#

Optional custom pattern provider

Type:

Optional[Any]

synthesis_backend#

Optional custom synthesis backend

Type:

Optional[Any]

with_overrides(**kwargs)[source]#

Create a new config with specified overrides.

This enables immutable updates to configuration.

Example

>>> config = AccompanimentConfig(tempo=120)
>>> fast_config = config.with_overrides(tempo=180)
>>> config.tempo, fast_config.tempo
(120, 180)
Return type:

AccompanimentConfig

class accompy.AudioData(waveform, sr=44100)[source]#

Bases: object

Container for audio data — numpy array + sample rate.

>>> import numpy as np
>>> ad = AudioData(waveform=np.zeros(44100), sr=44100)
>>> ad.duration_seconds
1.0
to_wav_bytes()[source]#

Convert to WAV file bytes.

Return type:

bytes

write(path)[source]#

Write audio to a WAV file. Returns the path.

Return type:

str

class accompy.BassPattern(name, notes)[source]#

Bases: object

A 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: object

A 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: Protocol

Convert 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: object

Ordered 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
property durations: list[float]#

Just the durations, without symbols.

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)]
Return type:

list[tuple[str, float]]

sections: list[tuple[str, int, int]]#

(label, start, stop) where chords[start:stop] are the section’s chords (see section_chords()).

Type:

Song structure, when the source has it

property symbols: list[str]#

Just the chord symbols, without durations.

to_score()[source]#

Convert to an accompy Score for pattern-based accompaniment.

Example

>>> cs = ChordSequence([("Dm7", 4.0), ("G7", 4.0)])
>>> score = cs.to_score()
>>> len(score)
2
class accompy.CompingPattern(name, hits)[source]#

Bases: object

A piano/guitar comping (accompaniment) pattern.

name#

Pattern identifier

Type:

str

hits#

Sequence of (beat, duration, velocity) tuples

Type:

Sequence[tuple[float, float, int]]

class accompy.ConverterRegistry[source]#

Bases: object

Registry 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:

Callable

list_converters(source_type, target_type)[source]#

List available converter names for a type pair.

Return type:

list[str]

list_pairs()[source]#

List all registered (source, target) type name pairs.

Return type:

list[tuple[str, str]]

register(source_type, target_type, func, *, name='', is_default=False)[source]#

Register a converter function.

Parameters:
  • source_type (type) – The input type

  • target_type (type) – The output type

  • func (Callable) – The converter function (source -> target)

  • name (str) – Name for this converter (defaults to func.__name__)

  • is_default (bool) – If True, make this the default converter for this pair

Return type:

None

set_default(source_type, target_type, name)[source]#

Change the default converter for a type pair.

Return type:

None

class accompy.DrumHit(beat, drum, velocity)[source]#

Bases: object

A single drum hit in a pattern.

beat#

Beat position (0-based within measure)

Type:

float

drum#

MIDI note number for the drum sound

Type:

int

velocity#

Hit velocity (0-127)

Type:

int

class accompy.DrumPattern(name, beats_per_bar, hits)[source]#

Bases: object

A drum pattern for one or more measures.

Example

>>> pattern = DrumPattern("rock", 4, [DrumHit(0, KICK, 100)])
>>> pattern.beats_per_bar
4
at_tempo(tempo)[source]#

Return pattern duration in seconds at a given tempo.

Return type:

float

class accompy.MidiData(bytes_=None, pretty_midi_obj=None, tempo=120, time_signature=(4, 4))[source]#

Bases: object

Container 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
to_bytes()[source]#

Get MIDI as bytes, converting from pretty_midi if needed.

Return type:

bytes

to_pretty_midi()[source]#

Get as pretty_midi.PrettyMIDI, converting from bytes if needed.

write(path)[source]#

Write MIDI to a file. Returns the path.

Return type:

str

class accompy.MidiEvent(time, channel, note, velocity, duration)[source]#

Bases: object

A single MIDI event.

Used for event-based MIDI generation that enables both batch file creation and future real-time streaming.

time#

Event time in beats

Type:

float

channel#

MIDI channel (0-15)

Type:

int

note#

MIDI note number (0-127)

Type:

int

velocity#

Note velocity (0-127)

Type:

int

duration#

Note duration in beats

Type:

float

class accompy.NoteEvent(beat, pitch_offset, duration, velocity)[source]#

Bases: object

A melodic note event for bass or other instruments.

beat#

Beat position within measure

Type:

float

pitch_offset#

Offset from chord root in semitones (0=root, 7=5th, etc.)

Type:

int

duration#

Note duration in beats

Type:

float

velocity#

Note velocity (0-127)

Type:

int

class accompy.NoteSequence(notes, tempo=120, time_signature=(4, 4))[source]#

Bases: object

Ordered 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: Protocol

Provides 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']
available_styles()[source]#

List all available style names.

Return type:

list[str]

Returns:

List of style names

get_patterns(style)[source]#

Get patterns for a style.

Parameters:

style (str) – Style name (e.g., “swing”, “bossa”, “rock”)

Return type:

dict[str, list]

Returns:

Dict with ‘drums’, ‘bass’, ‘comp’ keys containing pattern lists

class accompy.RealtimeAccompaniment(config=None, *, on_event=None)[source]#

Bases: object

Real-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.

Yields:

MidiEvent – MidiEvent objects in chronological order

Return type:

Iterator[MidiEvent]

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:

None

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:

None

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:

None

class accompy.Score(measures, title='Untitled', composer='', key='C', time_signature=(4, 4))[source]#

Bases: object

A 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:

Score

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:

Score

to_chord_sequence(*, tempo=120)[source]#

Convert Score to a ChordSequence (from the converter pipeline).

Each chord gets a duration proportional to its share of the bar.

Example

>>> score = Score.from_string("| Dm7 | G7 | C^7 |")
>>> cs = score.to_chord_sequence(tempo=160)
>>> len(cs)
3
class accompy.ScoreToWav(*args, **kwargs)[source]#

Bases: Protocol

Callable that renders a Score to a WAV file.

Any function matching this signature can be used as a score_to_wav engine in generate_wav() and generate_variations().

class accompy.SynthesizerBackend(*args, **kwargs)[source]#

Bases: Protocol

Audio 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:

bool

Returns:

True if the backend can be used

render_to_bytes(midi_path, *, sample_rate=44100)[source]#

Render a MIDI file to PCM bytes (for streaming).

Parameters:
  • midi_path (Path) – Path to MIDI file

  • sample_rate (int) – Audio sample rate

Return type:

bytes

Returns:

Raw PCM audio bytes

render_to_file(midi_path, output_path, *, sample_rate=44100)[source]#

Render a MIDI file to audio.

Parameters:
  • midi_path (Path) – Path to MIDI file

  • output_path (Path) – Where to save audio

  • sample_rate (int) – Audio sample rate

Return type:

Path

Returns:

Path to the created audio file

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:
  • cs – A ChordSequence (from accompy.converters).

  • skeleton (Union[str, tuple, Sequence]) – Skeleton key, name, style, or duration tuple.

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_offset plays 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:

int

accompy.check_dependencies()[source]#

Check which dependencies are available.

Return type:

dict[str, bool]

Returns:

Dict mapping dependency name to availability status

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 style plays over one chord.

This is one step of generate_midi_events(), which calls it for every chord of a score: chord_notes are the chord’s MIDI notes, root first (what a chord resolver returns), start_beat where the chord starts and duration how 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)]
Return type:

list[MidiEvent]

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:

list[int]

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 ChordSequence

  • resolver (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’)

  • soundfont (Optional[str]) – Path to SoundFont file

  • tempo (int) – BPM

  • sr (int) – Sample rate

  • output_path (Optional[str]) – Optional path to write WAV file

Return type:

AudioData

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 ChordSequence

  • resolver (Optional[str]) – Resolver name (‘pychord’, ‘music21’, ‘mingus’, ‘tonal’)

  • midi_gen (Optional[str]) – MIDI generator name (‘pretty_midi’, ‘midiutil’, ‘mido’)

  • tempo (int) – BPM

  • output_path (Optional[str]) – Optional path to write MIDI file

Return type:

MidiData

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 ChordSequence

  • resolver (Optional[str]) – Resolver name (‘pychord’, ‘music21’, ‘mingus’, ‘tonal’)

  • tempo (int) – BPM (used if chords is a string)

Return type:

NoteSequence

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:
  • chords (str) – Chord string in any supported format

  • parser (Optional[str]) – Parser name (‘auto_detect’, ‘plain_text’, ‘chordpro’, ‘musicgen_chord’)

  • tempo (int) – BPM (default 120)

  • title (str) – Song title

  • key (str) – Key signature

  • time_signature (tuple[int, int]) – Time signature tuple

Return type:

ChordSequence

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])
Return type:

list[int]

accompy.convert(source, target_type, *, via=None)[source]#

Convert source to target_type using the registered converter.

Parameters:
  • source (Any) – The source data

  • target_type (type) – The desired output type

  • via (str | None) – Optional converter name (uses default if None)

Return type:

Any

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.

Return type:

List[Tuple[str, str, str]]

Returns:

List of (issue, description, solution) tuples

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-is

  • str: chord string (e.g. "| C | Am | F | G |") OR iReal URL (irealbook://...)

  • Iterable[tuple[str, int|float]]: list of (chord, beats) like in accompany

  • Iterable[str]: chord symbols, one per bar

  • list[list[str]]: already-parsed measures

Notes

  • Score.measures in accompy does 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:

Score

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 file

  • output_path (str | None) – Where to write audio. If None, uses filepath with .wav extension

  • n_repeats (int) – Number of times to repeat the progression (default 1)

  • transpose (int) – Semitones to transpose (positive=up, negative=down)

  • resolver (str | None) – Chord resolver backend

  • midi_gen (str | None) – MIDI generator backend

  • audio_renderer (str | None) – Audio renderer backend

  • soundfont (str | None) – Path to SoundFont file

  • tempo (int | None) – Override BPM (None = use file’s tempo or 120)

  • sr (int) – Sample rate

Return type:

AudioData

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:
  • filepath (str) – Path to an iReal HTML file, or a chord text file

  • output_path (str | None) – Where to write MIDI. If None, uses filepath with .mid extension

  • n_repeats (int) – Number of times to repeat the progression

  • transpose (int) – Semitones to transpose

  • resolver (str | None) – Chord resolver backend

  • midi_gen (str | None) – MIDI generator backend

  • tempo (int | None) – Override BPM

Return type:

MidiData

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 BPM

  • repeats (int) – Number of times to repeat the progression

  • output_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 backend

  • backend (Optional[Literal['auto', 'mma', 'builtin']]) – Explicitly select backend (‘auto’, ‘mma’, ‘builtin’)

  • autoplay (bool) – If True, automatically play the generated audio

Return type:

Path

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.

chords is anything accompy.ensure_score() accepts (a chord string, an iReal URL, measures, chord symbols, (chord, beats) pairs, a Score); time_signature applies to the forms that do not carry one (default: the style’s, see style_time_signature(): 3/4 for waltz, else 4/4). Times and durations are in beats: the events do not depend on tempo. repeats defaults to 1, as in accompy.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
Return type:

list[MidiEvent]

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"). Run mma -Dg to list available grooves.

Parameters:
  • score (Score) – A Score with chord measures.

  • output_path (Union[str, Path]) – Destination WAV file path.

  • groove (str) – MMA groove name (case-sensitive).

  • tempo (int) – Tempo in BPM.

  • repeats (int) – Number of times to repeat the progression.

Return type:

Path

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:
  • score (Score) – Base Score (will be transposed per key).

  • output_dir (Union[str, Path]) – Directory for output files.

  • keys (Sequence[str]) – Keys to transpose to.

  • tempos (Sequence[int]) – Tempos in BPM to cycle through.

  • 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 to mma_score_to_wav().

Return type:

list[Path]

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_wav callable to use a different backend — for instance one built with make_converter_engine().

Parameters:
  • score (Score) – A Score with chord measures.

  • output_path (Union[str, Path]) – Destination WAV file path.

  • 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 to mma_score_to_wav().

Return type:

Path

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:

Path

accompy.get_artifact_dir(kind)#

Return (and create) an artifact sub-directory for kind.

Return type:

Path

accompy.get_chord_resolver()[source]#

Get the current default chord resolver.

Return type:

Callable[[str], list[int]]

Returns:

The active chord resolution function

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:

Path

accompy.get_pattern_registry()[source]#

Get the global pattern registry, initializing if needed.

Return type:

PatternRegistry

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:

dict

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:

Path

accompy.list_available_converters()[source]#

List all available converters organized by pipeline stage.

Return type:

dict[str, list[str]]

Returns:

Dict mapping stage names to lists of converter names.

>>> 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:
  • beats_per_measure (float | None) – Filter to skeletons matching this measure length.

  • style (str | None) – Filter to skeletons associated with this style.

Return type:

list[str]

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_json(name)[source]#

Read a resource file as JSON.

accompy.load_resource_lines(name)[source]#

Read a resource file as a list of non-empty stripped lines.

Return type:

list[str]

accompy.load_resource_text(name)[source]#

Read a resource file as text.

Return type:

str

accompy.make_converter_engine(*, resolver=None, midi_gen=None, audio_renderer=None, soundfont=None, sr=44100)[source]#

Create a ScoreToWav engine from accompy’s converter pipeline.

This wraps the ChordSequence → NoteSequence → MidiData → AudioData converter chain into the same interface that generate_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:

ScoreToWav

Returns:

A callable matching the ScoreToWav protocol.

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:
  • midi_data (MidiData) – MidiData object

  • audio_renderer (Optional[str]) – Audio renderer name

  • soundfont (Optional[str]) – Path to SoundFont file

  • sr (int) – Sample rate

  • output_path (Optional[str]) – Optional path to write WAV file

Return type:

AudioData

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"). Run mma -Dg to list available grooves.

Parameters:
  • score (Score) – A Score with chord measures.

  • output_path (Union[str, Path]) – Destination WAV file path.

  • groove (str) – MMA groove name (case-sensitive).

  • tempo (int) – Tempo in BPM.

  • repeats (int) – Number of times to repeat the progression.

Return type:

Path

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 a Score.

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:

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:// or irealbook://) 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). Raises ValueError when 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.pitch_classes(notes)[source]#

Return unique pitch classes (0-11) as a tuple.

Return type:

tuple[int, ...]

accompy.play_audio(audio_path)[source]#

Play an audio file using the system’s default audio player.

Parameters:

audio_path (Union[str, Path]) – Path to the audio file

Return type:

bool

Returns:

True if playback started successfully, False otherwise

Example

>>> from accompy import play_audio
>>> play_audio("/path/to/audio.wav")
accompy.print_diagnostic_report()[source]#

Print a comprehensive diagnostic report.

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:
  • key (str) – Unique string key for the skeleton.

  • pattern (tuple) – Tuple of beat durations.

  • name (str) – Human-readable name (defaults to key).

  • beats_per_measure (float | None) – Measure length in beats (defaults to sum of pattern).

  • styles (list[str] | None) – List of associated style strings.

Return type:

None

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:
  • style (str) – Style name

  • drums (list) – List of DrumPattern objects

  • bass (list) – List of BassPattern objects

  • comp (list) – List of CompingPattern objects

Return type:

None

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]) – True for default Suno enhancement, False/None to 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/.

  • resolver (str | None) – Chord resolver backend name.

  • midi_gen (str | None) – MIDI generator backend name.

  • audio_renderer (str | None) – Audio renderer backend name.

  • soundfont (str | None) – Path to a SoundFont file.

  • sr (int) – Sample rate for MIDI audio rendering.

Return type:

str

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 for render_chords().

  • **shared_kwargs – Default arguments applied to every config.

Return type:

list[str]

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:

int

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:

tuple

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:
  • chords (str | ChordSequence) – Chord string or ChordSequence.

  • skeleton (str | tuple[float, ...]) – Skeleton key, name, style, or duration tuple.

  • resolver (str | None) – Chord resolver name.

  • midi_gen (str | None) – MIDI generator name.

  • audio_renderer (str | None) – Audio renderer name.

  • soundfont (str | None) – Path to SoundFont file.

  • tempo (int) – BPM.

  • sr (int) – Sample rate.

  • output_path (str | None) – Optional path to write WAV file.

Return type:

AudioData

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:

MidiData

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_bar matches (else the first); bass and comping take the first of their list. A missing one is None.

>>> from accompy.patterns import get_patterns
>>> [p.name for p in select_patterns(get_patterns("swing"), 4)]
['swing_basic', 'walking', 'swing_comp']
Return type:

tuple

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:

None

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:

bool

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 song to a ChordSequence.

Parameters:
  • song (Any) – Anything with text, annotations and meta as songleaf’s Song.

  • 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 with bars_per_line.

  • beats_per_bar (int) – Beats in a bar (the time signature’s numerator).

  • tempo (int) – Tempo in BPM (the song’s meta["tempo"] wins when it is a number).

Return type:

ChordSequence

Returns:

A ChordSequence whose sections follow the song’s section annotations (ranges over the chords), with the song’s title and key.

Raises:

ValueError – if both bars_per_line and beats_per_chord are 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:
  • symbol (str) – Chord symbol (e.g., “Dm7”, “G7”, “Cmaj7”)

  • transpose (int) – Semitone offset to apply (default: -12)

Return type:

list[int]

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 (see transpose_note()).

Return type:

str

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:
  • name (str) – Note name like "C", "Eb", "F#".

  • semitones (int) – Number of semitones (positive = up, negative = down).

  • use_flat (Optional[bool]) – Force flat (True) or sharp (False) spelling. None (default) uses flats for downward transposition.

Return type:

str

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 Score to a new key.

The spelling (sharp vs flat) is chosen automatically based on the target_key.

Parameters:
  • score – A Score instance.

  • target_key (str) – Target key, e.g. "Eb", "G", "F#".

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:
  • interactive (bool) – If True, prompt user for permission before making changes

  • auto_fix (bool) – If True and interactive=False, automatically fix issues without prompting

Return type:

Dict[str, bool]

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

Audio renderers — convert MidiData to AudioData.

base

Core domain models for accompy.

chord_parsers

Chord sheet parsers — convert various text formats to ChordSequence.

chord_resolution

Chord symbol to MIDI notes resolution.

chord_resolvers

Chord resolvers — convert chord symbols to MIDI note numbers.

converters

Core types for the chord-to-audio pipeline.

data_access

Per-user data directory management for accompy.

ireal

Decode iReal Pro URLs (irealb:// and irealbook://) into tunes and bars.

main

Main accompaniment generation module.

midi_generators

MIDI generators — convert NoteSequence to MidiData.

patterns

Pattern registry and access for accompany patterns.

pipeline

High-level pipeline API — one-call chord-to-audio conversion.

protocols

Protocols defining extensibility contracts for accompy.

realtime

Real-time accompaniment support (foundation).

renderers

MIDI and MMA rendering backends for accompy.

rendering

High-quality chord rendering pipeline — from chord charts to AI-enhanced audio.

rhythmic_skeletons

Rhythmic skeletons — duration-only measure patterns for simple accompaniment.

setup_utils

Setup and configuration utilities for accompy.

songs

Songs as backing-track input: a songleaf Song becomes a ChordSequence.

synthesis

Audio synthesis backends for accompy.

tools

Tools for generating accompaniment audio from Score objects.

util

Utility functions for chord parsing and normalization.

wips

Backward-compatibility shim — wips modules have moved to accompy top level.