pytakt.text module

This module defines functions for text format scores that are readable and can be evaluated in Python.

showtext(score, rawmode=False, time='measures', resolution=480, limit=2000000.0, bar0len=None, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, timereprfunc=None) None

This function displays the contents of the score in a Python-evaluatable text, with notes, rests, and other information in chronological order for each track. This display contains all the information the score has. By default, each line displays a note, rest, ctrl, tempo, timesig, keysig, sysex, and other command, along with the measure number and number of ticks in the measure. This text can be eval’d to generate a score compatible with the original (although the structure of the score will generally be different).

Parameters:
  • score (Score) – Input score

  • rawmode (bool, optional) –

    If True, events are displayed on each line instead of commands. In this mode (raw mode), for a score read from a standard MIDI file with pair_note_events=False as shown below, converting it to text and then eval’ing it will reproduce the exactly same score, except for the attribute information of the Tracks object.

    >>> buf = io.StringIO()
    >>> score = readsmf('a.mid', pair_note_events=False)
    >>> score.showtext(rawmode=True, file=buf)
    >>> print(list(score) == list(eval(buf.getvalue())))
    True
    

  • time (str, optional) –

    One of the followings which determines the format of the time displayed at the beginning of each line.

    • ’measures’ (default): displays the measure number and ticks within the measure.

    • ’mbt’: displays measure number, beat number, and ticks within the beat.

    • ’ticks’: displays ticks from the beginning of the score.

    • ’all’: displays all the values displayed by ‘mbt’ and ‘ticks’.

    • ’none’: no display.

  • resolution (int or float, optional) – Specifies ticks per quarter note in the display.

  • limit (ticks, optional) – Limits the length of the score. For details on limit, see the same name argument of Score.stream().

  • bar0len (ticks, optional) – Specifies the length of the initial measure (Bar 0). Affects only time display at the beginning of each line.

  • file (file object) – Specifies the file object to output to. The default is sys.stdout (standard output).

  • timereprfunc (function) – Specifies the function to convert a time value to a string. By default, it is set to the ‘repr’ function for the raw mode and frac_time_repr() otherwise.

writepyfile(score, filename, rawmode=False, time='measures', resolution=480, limit=2000000.0, bar0len=None, end_score_args={}) None

Output the text converted by showtext() to a file with a header and footer. This file is executable as a Python program, and when executed, it can play the score, show the score content, and convert it to a standard MIDI or JSON file, as shown in the example below.

>>> score.writepyfile(‘sample.py’)
>>> <Ctrl-D>
$ python sample.py
Usage: /usr/bin/python sample.py (play|show|write) [WRITE_FILE] [PARAM=VALUE ..]
$ python sample.py play  # Play the score. Parameters, if any, are passed to play().
$ python sample.py show velocity=True  # Show the piano roll. Parameters are passed to show().
$ python sample.py write sample.mid “encoding=’sjis’”  # Write to SMF. Parameters are passed to writesmf().
$ python sample.py write sample.json indent=4  # If the file name extension is ‘.json’, it is written to a JSON file. Parameters are passed to writejson().
Parameters:
  • filename (str) – name of output file (‘-’ for standard output)

  • end_score_args (dict, optional) – additional arguments passed to the end_score function

The meaning of the other arguments is the same as showtext().

evalpyfile(filename, supply_tempo=True) Score

Execute a Python file containing the ‘#pytakt’ signature and end_score() (which can be generated by writepyfile() or written by a user) and return the score described in it.

Caution: This function executes the contents of a file as a Python program, and therefore poses a significant security risk. Use extreme caution when applying this function to files obtained from outside such as the Internet.

Parameters:
  • filename (str) – file name

  • supply_tempo (bool or float, optional) – If True, a tempo event of the value specified in the default_tempo argument of end_score() is supplied if there is no tempo event at time 0. If a valid tempo value (BPM) is specified, a tempo event of that value is inserted if there is no tempo event at time 0. If False, no tempo event is added.

Returns:

The score passed as an argument to end_score(). This score object has the additional attributes ‘default_tempo’, ‘smf_format’, and ‘smf_resolution’, whose values are set to the values of the default_tempo, format, and resolution arguments of end_score().

end_score(score, default_tempo=125.0, format=1, resolution=480) None

Depending on the command line arguments when Python is invoked, this function plays, displays, or outputs the contents of score to a file. This function is intended to be used for final processing in a Python file that describes a score. Files generated by writepyfile() will have this function at the end. See writepyfile() for the usage of command line arguments.

Parameters:
  • score (Score) – the output score

  • default_tempo (float or int, optional) – Specifies the tempo when there is no tempo event at time 0.

  • format (int, optional) – Specifying the SMF format by one of the integers 0, 1, and 2. This is referenced when writing to SMF with the write operation.

  • resolution (int, optional) – Specifies the resolution (ticks per quarter note) in SMF. This is referenced when writing to SMF with the write operation.

writejson(score, filename, **kwargs) None

Writes the contents of score to Pytakt’s original file in JSON format. Reading this file with readjson() yields an object that is equivalent to the original (i.e., true when compared with ‘==’). It cannot be used if score contains objects other than those of the classes below.

int, float, str, bool, None, Fraction, Pitch, Interval, Key, list, tuple, dict (each key must be a string), bytes, bytearray, Event and its subclasses, EventList, Tracks, and Chord

Scores, except for EventStreams, usually consist of only the above objects, so this function is useful for saving score information to a file. It has the advantage over standard MIDI files in that it can include information about enharmonics, both notated and played times, and additional event attributes.

Parameters:
  • filename – Output filename (‘-’ for standard output)

  • kwargs – Other arguments passed to json.dump

Examples

>>> writejson(note(C4), '-', indent=4)
{
    "__event_list__": true,
    "duration": 480,
    "events": [
        {
            "__event__": "NoteEvent",
            "t": 0,
            "n": {
                "__pitch__": "C4"
            },
            "L": 480,
            "v": 80,
            "nv": null,
            "tk": 1,
            "ch": 1
        }
    ]
}>>>
>>> s = mml("C C# Db> D")
>>> writejson(s, 'a.json')
>>> s == readjson('a.json')
True
readjson(filename) Score

Reads a file in JSON format written by writejson() and returns the object described.

Parameters:

filename – Input file name (‘-’ for standard input)

showsummary(score, default_tempo=125.0) None

Displays summary information about the score, including length, number of measures, pitch range, and number of events.

Parameters:
  • score (Score) – Input score

  • default_tempo (float) – If there is a section at the beginning of the score with no tempo events, the tempo of that section is assumed to be this value.