Metadata-Version: 2.5
Name: trackparse
Version: 0.8.0
Summary: Spec-driven parser for music track titles and tracklists: artists, feat, remixes, versions, junk, positions, times.
Project-URL: Homepage, https://4matic.github.io/trackparse/
Project-URL: Documentation, https://4matic.github.io/trackparse/start/getting-started/
Project-URL: Repository, https://github.com/4matic/trackparse
Project-URL: Issues, https://github.com/4matic/trackparse/issues
Project-URL: Changelog, https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md
Project-URL: Specification, https://github.com/4matic/trackparse/blob/main/spec/SPEC.md
Author: Maksim Maksimov
License-Expression: MIT
License-File: LICENSE
Keywords: artist,featuring,id3,metadata,music,parser,remix,title,track,youtube
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# trackparse

[![PyPI](https://img.shields.io/pypi/v/trackparse?logo=pypi&logoColor=white)](https://pypi.org/project/trackparse/)
[![Python versions](https://img.shields.io/pypi/pyversions/trackparse?logo=python&logoColor=white)](https://pypi.org/project/trackparse/)
[![tests](https://img.shields.io/github/actions/workflow/status/4matic/trackparse/python.yml?branch=main&label=tests&logo=github)](https://github.com/4matic/trackparse/actions/workflows/python.yml)
[![license](https://img.shields.io/badge/license-MIT-blue)](https://github.com/4matic/trackparse/blob/main/LICENSE)

**[Documentation](https://4matic.github.io/trackparse/)** · **[Getting started](https://4matic.github.io/trackparse/start/getting-started/)** · **[API reference](https://4matic.github.io/trackparse/reference/parse/)** · **[Playground](https://4matic.github.io/trackparse/playground/)** · **[Changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md)**

**Turn messy track names into structured data: who made it, who's featured, who remixed it, and
what's just noise.**

```text
01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]
```

Most title parsers split that into `"Wilkinson ft. Becky Hill & Tom Cane"` and
`"Afterglow (Sub Focus VIP Remix)"` and stop. Others "clean" it and throw the feat and the remix
away. trackparse keeps all of it. Everything it recognizes goes into a field, and anything it
doesn't recognize stays in the title, word for word
([try it in the playground](https://4matic.github.io/trackparse/playground/#track=01.%20Wilkinson%20ft.%20Becky%20Hill%20%26%20Tom%20Cane%20-%20Afterglow%20%28Sub%20Focus%20VIP%20Remix%29%20%5BOfficial%20Video%5D)).

This is the Python port of [trackparse](https://github.com/4matic/trackparse). Its behaviour is
defined by a [shared spec](https://4matic.github.io/trackparse/reference/spec/) and pinned
by [13,565 fixtures](https://4matic.github.io/trackparse/project/testing/). It passes all of them, and for every fixture input its output is byte-identical
to the [JavaScript, Rust, Go and C packages](#other-languages).

- Python 3.9 to 3.14
- No dependencies
- [Typed](#typing) (`py.typed`), immutable results
- [Never raises](#errors) on `str` input

## Install

```sh
pip install trackparse
# or
uv add trackparse
```

## Quick start

**Docs:** [Getting started](https://4matic.github.io/trackparse/start/getting-started/)

```python
from trackparse import format_track, parse

track = parse(
    "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]"
)

[f"{a.name} ({a.role})" for a in track.artists]
# ['Wilkinson (primary)', 'Becky Hill (featured)', 'Tom Cane (featured)']
track.title  # 'Afterglow'
track.full_title  # 'Afterglow (Sub Focus VIP Remix)'
track.versions[0].type  # 'remix'
track.versions[0].artists[0].name  # 'Sub Focus'
track.versions[0].modifiers  # ('vip',)
track.junk  # (Junk(raw='Official Video', kind='video'),)
track.position  # Position(raw='01', number=1)
track.mode  # 'youtube'

format_track(track, joiners="canonical")
# 'Wilkinson feat. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix)'
```

[`to_dict()`](#to_dict-and-from_dict) returns the spec's JSON form, with the same camelCase keys the JS
package uses:

```python
import json

print(json.dumps(track.to_dict(), indent=2))
```

<details>
<summary>Output</summary>

```json
{
  "input": "01. Wilkinson ft. Becky Hill & Tom Cane - Afterglow (Sub Focus VIP Remix) [Official Video]",
  "mode": "youtube",
  "position": { "raw": "01", "number": 1 },
  "timestamp": null,
  "artists": [
    { "name": "Wilkinson", "role": "primary", "joiner": null, "source": "artist" },
    { "name": "Becky Hill", "role": "featured", "joiner": "ft.", "source": "artist" },
    { "name": "Tom Cane", "role": "featured", "joiner": "&", "source": "artist" }
  ],
  "title": "Afterglow",
  "fullTitle": "Afterglow (Sub Focus VIP Remix)",
  "versions": [
    {
      "type": "remix",
      "raw": "Sub Focus VIP Remix",
      "artists": [{ "name": "Sub Focus", "role": "remixer", "joiner": null, "source": "version" }],
      "modifiers": ["vip"],
      "descriptor": null,
      "year": null,
      "unknownArtist": false,
      "delimiter": "("
    }
  ],
  "year": null,
  "label": null,
  "flags": { "explicit": false, "clean": false, "unknownArtist": false, "unknownTitle": false },
  "junk": [{ "raw": "Official Video", "kind": "video" }],
  "warnings": []
}
```

(Reformatted for width; the keys and values are exactly what `to_dict()` returns.)

</details>

## API

**Docs:** [Other functions](https://4matic.github.io/trackparse/reference/functions/)

```python
parse(input, *, mode="auto", uploader=None, known_artists=(), split_and="auto", keywords=None) -> ParsedTrack
parse_artists(input, *, <same options>) -> list[Artist]
format_track(track, *, feat="source", feat_marker=None, joiners="original",
             versions="all", producers=True, position=False, label=True) -> str
normalize(input) -> str
all_artists(track) -> list[Artist]
create_parser(**options) -> Parser   # Parser.parse(...), Parser.parse_artists(...)
SPEC_VERSION, __version__

# from trackparse.tracklist
parse_tracklist(text, *, mode="tracklist", known_artists=(), keywords=None, split_and="auto",
                audio_seconds=None, marker_words=()) -> Tracklist
apply_edits(text, edits, *, <same options>) -> EditResult
```

Each function has a section below and one in the [API reference](https://4matic.github.io/trackparse/reference/functions/),
where every example has a Python tab. The tracklist functions are under [Tracklists](#tracklists).

### `parse(input, **options)`

**Docs:** [parse and ParsedTrack](https://4matic.github.io/trackparse/reference/parse/) · [Options](https://4matic.github.io/trackparse/reference/options/)

Parses one track string, running [rules R1 to R9](https://4matic.github.io/trackparse/reference/spec/#r1-normalization) of the
spec in order.

| Option | Default | |
|---|---|---|
| [`mode`](https://4matic.github.io/trackparse/guides/modes/) | `"auto"` | `"clean"`, `"youtube"`, `"filename"`, `"tracklist"`, or `"auto"` to detect from the string. See [Modes](#modes) |
| [`uploader`](https://4matic.github.io/trackparse/guides/modes/#the-uploader-fallback) | `None` | YouTube channel name, used as the artist when there's no separator (`- Topic` and `VEVO` are dropped) |
| [`known_artists`](https://4matic.github.io/trackparse/guides/artists/#knownartists) | `()` | Names that are never split. There is no built-in list |
| [`split_and`](https://4matic.github.io/trackparse/guides/artists/#and-is-special) | `"auto"` | `"auto"` splits on `and` only after a comma or semicolon (`A, B and C`), so `Simon and Garfunkel` stays whole. Also `"always"`, `"never"` |
| [`keywords`](https://4matic.github.io/trackparse/reference/options/#keywords) | `None` | Extra vocabulary, added to the built-in lists (see below) |

```python
[a.name for a in parse("Chase & Status - Baddadan").artists]
# ['Chase', 'Status']
[a.name for a in parse("Chase & Status - Baddadan", known_artists=["Chase & Status"]).artists]
# ['Chase & Status']

[a.name for a in parse("Simon and Garfunkel - Mrs. Robinson", split_and="always").artists]
# ['Simon', 'Garfunkel']
```

`keywords` is a dict with any of these keys ([your own words](https://4matic.github.io/trackparse/guides/versions/#your-own-words)):

| Key | Type | |
|---|---|---|
| `version_heads` | `dict[str, VersionType]` | Word that sets a version type (`{"rerub": "rework"}`) |
| `descriptors` | `list[str]` | Words kept as a version's `descriptor` |
| `genres` | `list[str]` | Genre words |
| `junk` | `dict[str, JunkKind]` | Phrase to junk kind (`{"some label rip": "label"}`) |
| `feat_markers` | `list[str]` | Extra feat markers |

```python
parse("Artist - Song [Some Label Rip]").title
# 'Song [Some Label Rip]'
parse("Artist - Song [Some Label Rip]", keywords={"junk": {"some label rip": "label"}}).junk
# (Junk(raw='Some Label Rip', kind='label'),)
```

### `ParsedTrack`

**Docs:** [ParsedTrack fields](https://4matic.github.io/trackparse/reference/parse/#parsedtrack)

| Attribute | Type | |
|---|---|---|
| `input` | `str` | The original string, untouched |
| `mode` | `"clean" \| "youtube" \| "filename" \| "tracklist"` | Resolved mode |
| `position` | `Position \| None` | Track number: `Position(raw='01', number=1)` |
| `timestamp` | `Timestamp \| None` | Leading cue time: `[12:34]` gives `Timestamp(raw='12:34', seconds=754)` |
| `artists` | `tuple[Artist, ...]` | Primary, featured and producer credits. Remixers live in `versions` |
| `title` | `str` | Clean title. Brackets it doesn't recognize stay in |
| `full_title` | `str` | `title` with the versions re-attached |
| `versions` | `tuple[Version, ...]` | Remixes and other versions, left to right |
| `year` | `int \| None` | From `(2015)` or `- 2015` |
| `label` | `str \| None` | Record [label after a spaced bullet](https://4matic.github.io/trackparse/guides/junk-and-flags/#labels-after-a-bullet): `Stigma • VISION` gives `'VISION'` |
| `flags` | `Flags` | `explicit`, `clean`, `unknown_artist`, `unknown_title` |
| `junk` | `tuple[Junk, ...]` | What was taken out, each with a `kind` |
| `warnings` | `tuple[Warning, ...]` | Heuristics that fired |

`label` is declared last in the dataclass, with the default `None`, so code that builds a
`ParsedTrack` by position keeps working; `to_dict()` writes it after `year`, as in JSON.

`Artist(name, role, joiner, source)`:

- `role` is `"primary"`, `"featured"`, `"remixer"` or `"producer"`.
- `joiner` is the text before the name as written (`"&"`, `","`, `"ft."`, `"prod. by"`), or `None`
  for the first name in a list.
- `source` is where the credit came from: `"artist"` (left of the dash), `"title"` (right of it)
  or `"version"`.

`Version(type, raw, artists, modifiers, descriptor, year, unknown_artist, delimiter)`:

```python
parse("Pendulum - Watercolour (Extended VIP Mix)").versions[0]
# Version(type='vip', raw='Extended VIP Mix', artists=(), modifiers=('extended',),
#         descriptor=None, year=None, unknown_artist=False, delimiter='(')

parse("Queen - Bohemian Rhapsody (Live at Wembley 1986)").versions[0]
# Version(type='live', raw='Live at Wembley 1986', artists=(), modifiers=(),
#         descriptor='at Wembley', year=1986, unknown_artist=False, delimiter='(')
```

- `VersionType` ([the 27 types](https://4matic.github.io/trackparse/guides/versions/#the-27-types)): `remix`, `bootleg`, `vip`, `edit`, `flip`, `refix`, `rework`, `mashup`, `blend`,
  `dub`, `mix`, `extended`, `radio`, `club`, `original`, `instrumental`, `acapella`, `live`,
  `acoustic`, `remaster`, `demo`, `reprise`, `cover`, `version`, `spedUp`, `slowed`, `nightcore`.
- `JunkKind` ([junk kinds](https://4matic.github.io/trackparse/reference/parse/#junk-kinds)): `video`, `audio`, `lyrics`, `quality`, `promo`,
  `platform`, `label`, `genre`, `other`, `note`. The kind `label` is a label name in brackets
  (`[NCS Release]`); `note` is text after a second bullet, next to the `label` attribute.
- `Warning`: see [Warnings](#warnings).

These are plain strings, typed as `Literal` aliases (see [Typing](#typing)).

### `to_dict()` and `from_dict()`

**Docs:** [Serializing to JSON](https://4matic.github.io/trackparse/reference/parse/#serializing-to-json)

Every result class has `to_dict()`, which returns plain dicts and lists matching
[`parsed-track.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/parsed-track.schema.json)
(`fullTitle`, `unknownArtist`, ...). With `json.dumps(track.to_dict(), separators=(",", ":"),
ensure_ascii=False)` the bytes are the same as `JSON.stringify(parse(s))` in JS. The single-track classes
(`ParsedTrack`, `Artist`, ...) also have a `from_dict()` classmethod that goes the other way:

```python
from trackparse import ParsedTrack

ParsedTrack.from_dict(track.to_dict()) == track  # True
```

### `parse_artists(input, **options)`

**Docs:** [parseArtists](https://4matic.github.io/trackparse/reference/functions/#parseartistsinput-options) · [Artists and credits](https://4matic.github.io/trackparse/guides/artists/)

Splits a bare artist string (no title) ([R10](https://4matic.github.io/trackparse/reference/spec/#r10-parseartists)). Takes the same options as `parse`.

```python
from trackparse import parse_artists

[f"{a.name}:{a.role}" for a in parse_artists("Sub Focus, Wilkinson & Dimension feat. Kojo")]
# ['Sub Focus:primary', 'Wilkinson:primary', 'Dimension:primary', 'Kojo:featured']
```

### `format_track(track, **options)`

**Docs:** [format](https://4matic.github.io/trackparse/reference/functions/#formattrack-options) · [Formatting](https://4matic.github.io/trackparse/guides/formatting/)

Renders a track back to a string ([format options](https://4matic.github.io/trackparse/reference/options/#format-options),
[R11](https://4matic.github.io/trackparse/reference/spec/#r11-format)).

| Option | Default | |
|---|---|---|
| `feat` | `"source"` | Where featured artists go: `"source"` (where they were), `"artist"`, `"title"` (`(feat. X)` after the title) or `"omit"` |
| `feat_marker` | `None` | Marker for featured artists, such as `"featuring"` |
| `joiners` | `"original"` | `"original"` keeps the joiners as written. `"canonical"` writes `and` as `&`, `vs` as `vs.` and every feat marker as `feat.` |
| `versions` | `"all"` | `"all"` or `"none"` |
| `producers` | `True` | Include `(prod. ...)` credits |
| `position` | `False` | Include the track number (`01. `) |
| `label` | `True` | Include the label after a spaced bullet (` • VISION`) |

```python
from trackparse import format_track, parse

t = parse("01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)")

format_track(t)  # 'Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)'
format_track(t, feat="title", joiners="canonical")
# 'Wilkinson - Afterglow (feat. Becky Hill) (Sub Focus Remix)'
format_track(t, feat="omit", versions="none")  # 'Wilkinson - Afterglow'
format_track(t, feat_marker="featuring")
# 'Wilkinson featuring Becky Hill - Afterglow (Sub Focus Remix)'
format_track(t, position=True)  # '01. Wilkinson ft. Becky Hill - Afterglow (Sub Focus Remix)'

l = parse("Noisia - concussion • VISION • VISION RADIO RELOAD")
format_track(l)  # 'Noisia - concussion • VISION'
format_track(l, label=False)  # 'Noisia - concussion'
```

### `normalize(input)`

**Docs:** [normalize](https://4matic.github.io/trackparse/reference/functions/#normalizeinput)

The Unicode cleanup every function runs first: NFC, zero-width spaces, BOM and soft hyphens
removed, fullwidth brackets, smart quotes and dash variants mapped to ASCII, whitespace collapsed
([R1](https://4matic.github.io/trackparse/reference/spec/#r1-normalization)). Running it twice changes nothing.

```python
from trackparse import normalize

normalize("Noisia\u200b – Stigma （VIP）")
# 'Noisia - Stigma (VIP)'
```

### `all_artists(track)`

**Docs:** [allArtists](https://4matic.github.io/trackparse/reference/functions/#allartiststrack)

Credits plus every remixer, deduplicated ([R9](https://4matic.github.io/trackparse/reference/spec/#r9-assembly-and-dedup)).

```python
from trackparse import all_artists

[(a.name, a.role) for a in all_artists(track)]
# [('Wilkinson', 'primary'), ('Becky Hill', 'featured'), ('Tom Cane', 'featured'), ('Sub Focus', 'remixer')]
```

### `create_parser(**options)`

**Docs:** [createParser](https://4matic.github.io/trackparse/reference/functions/#createparseroptions)

Compiles the options once, for many calls. Per-call options are merged over the parser's: a value
passed per call replaces the base one (`known_artists` included), `None` leaves it alone, and
`keywords` dicts are merged.

```python
from trackparse import create_parser

parser = create_parser(
    known_artists=["Chase & Status", "Camo & Krooked"],
    keywords={"version_heads": {"rerub": "rework"}},
)
parser.parse("Chase & Status x Camo & Krooked - Track (Alix Perez Rerub)").versions[0].type
# 'rework'
```

### `SPEC_VERSION`

**Docs:** [SPEC_VERSION](https://4matic.github.io/trackparse/reference/functions/#spec_version)

The version of the [spec](https://4matic.github.io/trackparse/reference/spec/) this build implements. It equals `__version__`: the PyPI package, the npm
package, the Rust crate, the Go module, the C library and the spec are released together and
always share one version number.

## Modes

**Docs:** [Modes](https://4matic.github.io/trackparse/guides/modes/) · [R2 in the spec](https://4matic.github.io/trackparse/reference/spec/#r2-mode-prelude)

| Mode | For | Adds |
|---|---|---|
| `clean` | Store metadata, tags | Only a spaced dash separates artist and title |
| [`youtube`](https://4matic.github.io/trackparse/guides/modes/#youtube-mode) | Video titles, scrobbles | Pipe segments, `"Title" by Artist`, `Artist: "Title"`, unspaced dashes, trailing junk, uploader fallback |
| [`filename`](https://4matic.github.io/trackparse/guides/modes/#filename-mode) | Files | Strips the extension, `_` becomes a space, `01-Track` numbering |
| [`auto`](https://4matic.github.io/trackparse/guides/modes/#how-auto-decides) | Anything | `filename` for known extensions, `youtube` when it sees junk, pipes or platform suffixes, `clean` otherwise |
| [`tracklist`](https://4matic.github.io/trackparse/guides/modes/#tracklist-mode) | One line of a tracklist | The first spaced dash always separates; `_-_` too. Never picked by `auto` |

```python
t = parse('"Numb" by Linkin Park', mode="youtube")
[a.name for a in t.artists], t.title, t.warnings
# (['Linkin Park'], 'Numb', ('bySplit',))

t = parse("07_Burial_-_Archangel.mp3")
t.mode, [a.name for a in t.artists], t.title, t.position
# ('filename', ['Burial'], 'Archangel', Position(raw='07', number=7))

parse("Shelter", mode="youtube", uploader="Porter Robinson").artists
# (Artist(name='Porter Robinson', role='primary', joiner=None, source='artist'),)
```

Try [`"Numb" by Linkin Park` in youtube mode](https://4matic.github.io/trackparse/playground/#track=%22Numb%22%20by%20Linkin%20Park&mode=youtube) or
[`07_Burial_-_Archangel.mp3`](https://4matic.github.io/trackparse/playground/#track=07_Burial_-_Archangel.mp3) in the playground.

## Warnings

**Docs:** [Warnings](https://4matic.github.io/trackparse/reference/warnings/)

The parser never fails, but it says when it had to guess. `track.warnings` is a tuple of strings,
empty when every decision was unambiguous.

| Warning | Means |
|---|---|
| [`noSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=noSeparator) | No artist/title separator was found. The whole string is the title |
| [`ambiguousSeparator`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousSeparator) | A two-part pipe title with no dash was read as artist and title |
| [`unspacedDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unspacedDashSplit) | Split at a dash without spaces around it |
| [`asymmetricDashSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=asymmetricDashSplit) | Split at a dash with a space on one side only |
| [`bySplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=bySplit) | Read `"Title" by Artist` |
| [`quotedTitleSplit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=quotedTitleSplit) | Took a quoted span as the title and the text before it as the artist |
| [`ambiguousMixCredit`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=ambiguousMixCredit) | `<Name> Mix` was read as a remix, but the name is long enough to be a style |
| [`unbalancedBrackets`](https://4matic.github.io/trackparse/reference/warnings/#track-warnings:~:text=unbalancedBrackets) | A bracket was opened and never closed |

```python
t = parse("Around the World")
t.artists, t.title, t.warnings
# ((), 'Around the World', ('noSeparator',))

parse("Noisia - Stigma (VIP").warnings
# ('unbalancedBrackets',)
```

Tracklists have their own [warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings), with line numbers. They are listed
under [Tracklists](#tracklists).

## Tracklists

**Docs:** [Tracklists](https://4matic.github.io/trackparse/guides/tracklists/) · [Editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/) · [Tracklist API](https://4matic.github.io/trackparse/reference/tracklist/) · [Warnings](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings)

`trackparse.tracklist` parses a whole tracklist, one entry per line, and checks it. Each entry
keeps its line exactly as written plus its own line ending, so `"".join(e.raw + e.eol for e in
tl.entries)` is always the input, CRLF or not.

```python
from trackparse.tracklist import apply_edits, parse_tracklist

text = "\r\n".join(
    [
        "Hour 2",
        "48:20 Noisia - Stigma",
        "52:47 Mefjus & Kasra - Bandwagon (Phace Remix)",
        "56:05 Black Sun Empire - ID",
        "59:31 Alix Perez - Fade Away",
        "01:03:10 Interview with Hybris",
        "01:07:44 Imanu - Sacrifice",
        "00:11:02 Current Value feat. Teddy Killerz - Payload",  # typo for 01:11:02
        "01:15:36 Hybris - Spinning Top",
    ]
)

tl = parse_tracklist(text)

[e.kind for e in tl.entries]
# ['header', 'track', 'track', 'track', 'track', 'marker', 'track', 'track', 'track']

e = tl.entries[2]
e.time  # TimeValue(raw='52:47', seconds=3167)
e.parts  # Parts(lead='', time='52:47', gap=' ', rest='Mefjus & Kasra - Bandwagon (Phace Remix)')
[a.name for a in e.track.artists], e.track.title, e.track.versions[0].type
# (['Mefjus', 'Kasra'], 'Bandwagon', 'remix')
tl.entries[3].track.flags.unknown_title  # True (the ID)

tl.warnings
# (TracklistWarning(code='no-start-at-zero', line=2, severity='info', suggestion=None),
#  TracklistWarning(code='time-out-of-order', line=8, severity='warning',
#                   suggestion=Suggestion(line=8, raw='01:11:02', seconds=4262)))

tl.stats
# Stats(lines=9, tracks=7, markers=1, timed=8, first_time=2900, last_time=4536)
```

The [suggestion](https://4matic.github.io/trackparse/reference/warnings/#suggestions) exists because exactly one time, one digit away from `00:11:02`,
fits between its neighbors. With several candidates or none, `suggestion` is `None`.
[Open this list in the playground](https://4matic.github.io/trackparse/playground/#list=Hour%202%0A48%3A20%20Noisia%20-%20Stigma%0A52%3A47%20Mefjus%20%26%20Kasra%20-%20Bandwagon%20%28Phace%20Remix%29%0A56%3A05%20Black%20Sun%20Empire%20-%20ID%0A59%3A31%20Alix%20Perez%20-%20Fade%20Away%0A01%3A03%3A10%20Interview%20with%20Hybris%0A01%3A07%3A44%20Imanu%20-%20Sacrifice%0A00%3A11%3A02%20Current%20Value%20feat.%20Teddy%20Killerz%20-%20Payload%0A01%3A15%3A36%20Hybris%20-%20Spinning%20Top).

`apply_edits` takes a list of dicts with the [spec's keys](https://4matic.github.io/trackparse/reference/tracklist/#edits) (`op`, `line`, `seconds`, `lines`, `from`,
`after`, `text`, `rest`) and only rewrites the lines they name:

```python
fix = tl.warnings[1].suggestion
r = apply_edits(
    text,
    [
        {"op": "set-time", "line": fix.line, "seconds": fix.seconds},
        {"op": "shift", "seconds": 45, "from": 5},
    ],
)

r.changed  # (5, 6, 7, 8, 9)
r.warnings  # (EditWarning(code='style-upgraded', edit=1, line=5),)
r.text.split("\r\n")[4]  # '01:00:16 Alix Perez - Fade Away'  (was 59:31)

apply_edits(text, [{"op": "shift", "seconds": -3000, "lines": [2, 3]}]).warnings
# (EditWarning(code='time-clamped', edit=0, line=2),)
```

A rewritten time keeps its line's style: `52:47` stays `MM:SS`, and a time that crosses the hour
gets hours like the rest of the list, with a `style-upgraded` warning. A time pushed below zero
stops at zero and warns `time-clamped`. A bad edit changes nothing and warns `edit-invalid`
([edit warnings](https://4matic.github.io/trackparse/reference/warnings/#edit-warnings), [editing tracklists](https://4matic.github.io/trackparse/guides/editing-tracklists/#times-keep-their-style)).

Both functions take the keyword [options](https://4matic.github.io/trackparse/reference/options/#tracklist-options) `mode` (default `"tracklist"`), `known_artists`,
`split_and` and `keywords`, as `parse` does, plus `audio_seconds` (the length of the audio, which
turns on the `time-after-audio-end` check) and `marker_words` (extra words that make a line a
marker):

```python
parse_tracklist(
    "00:00 Noisia - Stigma\n1:02:03 Mefjus - Suicide Bassline", audio_seconds=3600
).warnings
# (TracklistWarning(code='time-after-audio-end', line=2, severity='warning', suggestion=None),)
```

| Result | Fields |
|---|---|
| `Tracklist` | `spec_version`, `entries`, `warnings`, `stats` |
| `TracklistEntry` | `line` (1-based), `kind` (`track`, `marker`, `header`, `link`, `note`, `blank`), `eol`, `raw`, `parts`, `time`, `track` (`ParsedTrack` or `None`), `layered` (the track text after any time starts with `w/`) |
| `Parts` | `lead`, `time`, `gap`, `rest`, joined they give `raw` |
| `TracklistWarning` | `code`, `line`, `severity` (`info` or `warning`), `suggestion` |
| `TimeValue` | `raw`, `seconds` (`entry.time`, or `None` on untimed lines) |
| `Suggestion` | `line`, `raw`, `seconds` (`warning.suggestion`, or `None`) |
| `Stats` | `lines`, `tracks`, `markers`, `timed`, `first_time`, `last_time` |
| `EditResult` | `text`, `changed`, `warnings` (`EditWarning(code, edit, line)`) |

Lists pasted with list bullets or Markdown emphasis (`* 14:21 Artist - Title`,
`**[**14:21**] Artist - Title**`) read like plain lines; the decoration stays in `raw` and `parts`.
A line whose track text (after any time) starts with `w/` is `layered`: a track played over the
previous one
([Markdown](https://4matic.github.io/trackparse/guides/tracklists/#markdown),
[layered tracks](https://4matic.github.io/trackparse/guides/tracklists/#layered-tracks)).

[Warning codes](https://4matic.github.io/trackparse/reference/warnings/#tracklist-warnings): `time-missing`, `time-out-of-order`, `time-duplicate`, `no-start-at-zero`,
`time-after-audio-end` (needs `audio_seconds`), `invalid-time`, `position-gap`,
`position-duplicate`, `line-unparsed`. Edits: `set-time {line, seconds}`, `shift {seconds, lines? | from?}`
(all timed lines when neither is given), `sort-by-time {}`, `set-rest {line, rest}`,
`insert {after, text}` (`after: 0` inserts at the top), `delete {line}`. The
[Tracklist API reference](https://4matic.github.io/trackparse/reference/tracklist/) explains each one,
and the rules are in
[R13 of the spec](https://4matic.github.io/trackparse/reference/spec/#r13-tracklists).
`to_dict()` gives the camelCase JSON from
[`tracklist.schema.json`](https://github.com/4matic/trackparse/blob/main/spec/schema/tracklist.schema.json),
byte-identical to the JS package's output.

Every line is parsed with [`mode="tracklist"`](https://4matic.github.io/trackparse/guides/tracklists/#tracklist-mode), where the
first spaced dash always separates artist and title. `parse()` accepts it too:

```python
parse("Electrosoul System - Liquid Metal").junk
# (Junk(raw='Liquid Metal', kind='genre'),)
parse("Electrosoul System - Liquid Metal", mode="tracklist").title
# 'Liquid Metal'
```

## Errors

Parsing is total ([R0.8](https://4matic.github.io/trackparse/reference/spec/#r0-portability)): any `str` gives a complete `ParsedTrack`, `""` included, and `parse_tracklist`
and `apply_edits` return for any text. An option of the wrong type or with an unknown value is
ignored and the default is used. `apply_edits` reports a bad edit as an `edit-invalid` warning and
leaves the text alone.

The one exception is the input itself: passing something that isn't a `str` raises `TypeError`.

```python
parse(None)
# TypeError: parse() expects str input, got NoneType
```

Recognition is done by hand-written scanners, so there is no regex backtracking. A
10,000-code-point input parses in well under a second, and the test suite enforces a 1 s ceiling.

## Typing

**Docs:** [Types](https://4matic.github.io/trackparse/reference/parse/#types) · [Tracklist types](https://4matic.github.io/trackparse/reference/tracklist/#types)

The package ships `py.typed` and passes `mypy --strict`.

- `ParsedTrack`, `Artist`, `Version`, `Junk`, `Flags`, `Position` and `Timestamp` are frozen
  dataclasses with snake_case attributes, and so are the tracklist results in
  `trackparse.tracklist`. Sequences are tuples, so results are immutable and hashable: they can go
  in sets or be used as dict keys.
- Version types, junk kinds, warnings, roles and modes are plain strings, typed as `Literal`
  aliases: `VersionType`, `JunkKind`, `Warning`, `ArtistRole`, `ArtistSource`, `Mode`,
  `ModeOption`, `VersionDelimiter`. `trackparse.tracklist` adds `EntryKind`, `Eol`, `Severity`,
  `TracklistWarningCode` and `EditWarningCode`.
- Option dicts have `TypedDict` types (`ParseOptions`, `KeywordOptions`, `FormatOptions`).
  Tracklist edits are plain dicts.

## How it is tested

**Docs:** [How it's tested](https://4matic.github.io/trackparse/project/testing/)

- 13,565 shared fixtures: 1,280 written by hand and 12,285 generated from the rules. Every output
  is also validated against the JSON Schema.
- Property tests with [Hypothesis](https://hypothesis.works) for the spec's invariants: no
  exception on any string, `normalize` is idempotent, whitespace and dash noise doesn't change
  the result, and `parse(format_track(parse(s)))` round-trips.
- CI runs the suite on Python 3.9 to 3.14, and runs the fixtures again against the built wheel.
- [`compare-ports.mjs`](https://github.com/4matic/trackparse/blob/main/scripts/compare-ports.mjs)
  runs every fixture input through the JavaScript package, this package, the Rust crate, the Go
  module and the C library and diffs the complete JSON output. The difference count is zero.

## Versioning

**Changelog:** [python/CHANGELOG.md](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md)

The package version is the spec version ([`SPEC_VERSION`](#spec_version)); every release is on
[PyPI](https://pypi.org/project/trackparse/). While it is 0.x, a release that changes
the output for some input bumps the minor version, and a patch release only fixes bugs. If you
store parsed results, pin the minor version (`trackparse~=0.6.0` stays on 0.6.x) and read the
changelog before moving up.

## Other languages

**Docs:** [Ports](https://4matic.github.io/trackparse/project/ports/)

The same parser exists for JavaScript, Rust, Go and C. All five implement one spec, pass the same
fixtures, are released together under one version number, and return identical JSON for every
fixture input. You can parse in one language and read the result in another.

| Language | Package | Install | Docs |
|---|---|---|---|
| JavaScript / TypeScript | [trackparse on npm](https://www.npmjs.com/package/trackparse) | `npm install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/js/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/js/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) |
| Python | [trackparse on PyPI](https://pypi.org/project/trackparse/) | `pip install trackparse` | [README](https://github.com/4matic/trackparse/blob/main/python/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md) · [API](https://4matic.github.io/trackparse/reference/parse/) |
| Rust | [trackparse on crates.io](https://crates.io/crates/trackparse) | `cargo add trackparse` | [README](https://github.com/4matic/trackparse/blob/main/rust/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/rust/CHANGELOG.md) · [API on docs.rs](https://docs.rs/trackparse) |
| Go | [github.com/4matic/trackparse/go](https://pkg.go.dev/github.com/4matic/trackparse/go) | `go get github.com/4matic/trackparse/go` | [README](https://github.com/4matic/trackparse/blob/main/go/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/go/CHANGELOG.md) · [API on pkg.go.dev](https://pkg.go.dev/github.com/4matic/trackparse/go) |
| C / C++ | [C library and C++ header](https://github.com/4matic/trackparse/blob/main/c/README.md) | CMake FetchContent from the [release tarball](https://github.com/4matic/trackparse/releases), or the amalgamation (from 0.7.1) | [README](https://github.com/4matic/trackparse/blob/main/c/README.md) · [changelog](https://github.com/4matic/trackparse/blob/main/c/CHANGELOG.md) · [header](https://github.com/4matic/trackparse/blob/main/c/include/trackparse.h) |

## Limitations

**Docs:** [Limitations and roadmap](https://4matic.github.io/trackparse/project/roadmap/)

- `parse()` takes one track string. Whole tracklists go through `trackparse.tracklist`, which reads
  start times only: no durations, trailing times or time ranges.
- Catalog numbers, key and BPM are not fields. They stay in the title. A record label is a field
  only after a spaced bullet (`Stigma • VISION`), and a bullet inside a title (`Song • Part 2`) is
  read as a label too.
- There is no artist database. Pass `known_artists` for names that contain a joiner
  (`Earth, Wind & Fire`).

## Development

From `python/` in the [repository](https://github.com/4matic/trackparse), with
[uv](https://docs.astral.sh/uv/):

```sh
uv sync
uv run python scripts/gen_data.py --check  # spec/data codegen is up to date
uv run ruff check . && uv run ruff format --check .
uv run mypy --strict src
uv run pytest                              # every shared fixture, properties, API
uv run python scripts/conformance.py       # pass rate per fixture file and per rule
```

Modules mirror the JS reference one to one (`_scanner.py` is `scanner.ts`, and so on) and cite the
same spec rule IDs. Behaviour changes start in the spec, not here: see
[AGENTS.md](https://github.com/4matic/trackparse/blob/main/AGENTS.md).

## Links

- [Documentation](https://4matic.github.io/trackparse/), with every example in JavaScript, Python,
  Rust, Go and C, and a [playground](https://4matic.github.io/trackparse/playground/) that runs the
  parser in your browser
- [Spec](https://github.com/4matic/trackparse/blob/main/spec/SPEC.md) and its
  [changelog](https://github.com/4matic/trackparse/blob/main/spec/CHANGELOG.md)
- [Changelog](https://github.com/4matic/trackparse/blob/main/python/CHANGELOG.md)
- [Project README](https://github.com/4matic/trackparse#readme)
- [GitHub repository](https://github.com/4matic/trackparse)
- [npm package](https://www.npmjs.com/package/trackparse) · [Rust crate](https://crates.io/crates/trackparse) · [Go module](https://pkg.go.dev/github.com/4matic/trackparse/go) · [C library](https://github.com/4matic/trackparse/blob/main/c/README.md)

## License

[MIT](https://github.com/4matic/trackparse/blob/main/LICENSE)
