parse and ParsedTrack
import { parse } from "trackparse";
parse(input: string, options?: ParseOptions): ParsedTrackfrom trackparse import parse
parse(input: str, *, mode="auto", uploader=None, known_artists=(), split_and="auto", keywords=None) -> ParsedTrackuse trackparse::{parse, parse_with};
pub fn parse(input: &str) -> ParsedTrackpub fn parse_with(input: &str, options: &ParseOptions) -> ParsedTrackimport "github.com/4matic/trackparse/go"
func Parse(input string) Trackfunc ParseWith(input string, options ParseOptions) Track#include <trackparse.h>
trackparse_track *trackparse_parse(const char *s, size_t len);trackparse_track *trackparse_parse_with(const char *s, size_t len, const trackparse_parse_options *o);void trackparse_track_free(trackparse_track *t);parse never fails on a string. Any string gives a ParsedTrack, the empty string included, and
unknown or malformed options fall back to their defaults. What differs between the languages:
- JavaScript (
trackparseon npm): never throws on a string. - Python (
trackparseon PyPI): raisesTypeErrorifinputisn't astr(parse() expects str input, got int), and nothing else. - Rust: takes
&str, returns the value itself (noResult), and never panics. Useparsefor the defaults andparse_withto pass options. - Go: takes a
string, returns theTrackitself (noerror), and never panics. UseParsefor the defaults andParseWithto pass options. Bytes that are not valid UTF-8 are read as U+FFFD, one per maximal invalid sequence, as Rust'sString::from_utf8_lossyand the browser'sTextDecoderdo. - C (one header,
trackparse.h): takes UTF-8 as a pointer and a byte length, and returns atrackparse_track *that you free withtrackparse_track_free. PassTRACKPARSE_NUL_TERMINATEDas the length for a C string; with an explicit length, U+0000 is read as a character like any other. Invalid UTF-8 is read as U+FFFD with the same rule as Go and Rust.trackparse_parse_withtakes an options handle, andNULLthere means the defaults. The only failure is running out of memory, reported asNULL; no input makes it crash.
The time grows with the length of the input, and a track string is short. If you parse text
that someone else controls, on a server for example, cap its length first: a few thousand
characters is far more than any real title needs. A very long
knownArtists name makes a long input slower still,
so cap those names too if they come from outside.
The options are on the Options page. The other functions
(parseArtists, format, createParser) are under
Other functions, and the output model is
defined in the spec. To see the whole result for any
input, paste it into the playground
and open its JSON view.
ParsedTrack
Section titled “ParsedTrack”Every key is always present.
interface ParsedTrack { input: string; mode: Mode; position: Position | null; // { raw: string; number: number } timestamp: Timestamp | null; // { raw: string; seconds: number } artists: Artist[]; title: string; fullTitle: string; versions: Version[]; year: number | null; label: string | null; // the record label after a spaced bullet flags: Flags; // { explicit, clean, unknownArtist, unknownTitle } junk: Junk[]; // { raw: string; kind: JunkKind } warnings: Warning[];}@dataclass(frozen=True)class ParsedTrack: input: str mode: Mode position: Optional[Position] # Position(raw: str, number: int) timestamp: Optional[Timestamp] # Timestamp(raw: str, seconds: int) artists: tuple[Artist, ...] title: str full_title: str versions: tuple[Version, ...] year: Optional[int] flags: Flags # Flags(explicit, clean, unknown_artist, unknown_title) junk: tuple[Junk, ...] # Junk(raw: str, kind: JunkKind) warnings: tuple[Warning, ...] label: Optional[str] = None # last, so positional construction keeps workingpub struct ParsedTrack { pub input: String, pub mode: Mode, pub position: Option<Position>, // Position { raw: String, number: u32 } pub timestamp: Option<Timestamp>, // Timestamp { raw: String, seconds: u64 } pub artists: Vec<Artist>, pub title: String, pub full_title: String, pub versions: Vec<Version>, pub year: Option<u32>, pub label: Option<String>, pub flags: Flags, // Flags { explicit, clean, unknown_artist, unknown_title } pub junk: Vec<Junk>, // Junk { raw: String, kind: JunkKind } pub warnings: Vec<Warning>,}type Track struct { Input string Mode Mode Position *Position // Position{Raw string; Number int} Timestamp *Timestamp // Timestamp{Raw string; Seconds int} Artists []Artist Title string FullTitle string Versions []Version Year *int Label *string Flags Flags // Flags{Explicit, Clean, UnknownArtist, UnknownTitle bool} Junk []Junk // Junk{Raw string; Kind JunkKind} Warnings []Warning}typedef struct trackparse_track { trackparse_str input; trackparse_mode mode; const trackparse_position *position; /* { trackparse_str raw; int number; } */ const trackparse_timestamp *timestamp; /* { trackparse_str raw; int seconds; } */ const trackparse_artist *artists; size_t artists_count; trackparse_str title; trackparse_str full_title; const trackparse_version *versions; size_t versions_count; const int *year; trackparse_flags flags; /* { explicit_, clean, unknown_artist, unknown_title } */ const trackparse_junk *junk; /* { raw, kind, kind_name } */ size_t junk_count; const trackparse_warning *warnings; size_t warnings_count; const trackparse_str *label; /* NULL when there is none; last, for the ABI */} trackparse_track;flags.explicit_ has a trailing underscore because explicit is a C++ keyword; the JSON key is
explicit. label was added after the other members so the struct only grew at its end; in JSON it
comes between year and flags.
The table below uses the JavaScript and JSON names. Python has the same fields as attributes of a
frozen dataclass, in snake_case (full_title, flags.unknown_artist), with tuples instead of
arrays and None instead of null. Rust has a struct
(ParsedTrack) with the same snake_case names as public
fields: Vec<T> for arrays, Option<T> where the table says null, and enums for mode, roles,
kinds and warnings. Go has a Track struct with exported CamelCase fields (FullTitle,
Flags.UnknownArtist): slices for arrays, pointers where the table says null, and typed strings
for mode, roles, kinds and warnings. C has a read-only trackparse_track struct with the same
snake_case names as members: a pointer and a _count member for arrays (versions,
versions_count), pointers that are NULL where the table says null, C enums for mode,
roles, kinds and warnings, and trackparse_str for strings (a ptr and a len; ptr is also
NUL-terminated, so printf("%s") works on text without U+0000). The track owns everything it
points to, so nothing in it outlives trackparse_track_free.
| Field | Type | Description |
|---|---|---|
input |
string |
The original string, untouched (not normalized) |
mode |
"clean" | "youtube" | "filename" | "tracklist" |
The mode that ran (R2) |
position |
{ raw: string, number: number } | null |
Track number. raw is the digits as written ("01") (R4) |
timestamp |
{ raw: string, seconds: number } | null |
Leading cue time, "1:02:03" → 3723 (R4) |
artists |
Artist[] |
Primary, featured and producer credits. Remixers are in versions |
title |
string |
The clean title. Brackets it doesn't recognize stay in (R8) |
fullTitle |
string |
title with the versions put back in their original brackets (R9.4) |
versions |
Version[] |
Remixes and versions, left to right |
year |
number | null |
From (2015) or - 2015, the first in text order (R9.6) |
label |
string | null |
The record label after a spaced bullet: Stigma • VISION → "VISION". As written, no lookup. Not the junk kind label (R8.7) |
flags |
{ explicit, clean, unknownArtist, unknownTitle } |
All booleans (R5.4, R8.6) |
junk |
{ raw: string, kind: JunkKind }[] |
What was taken out because it is not part of the track's identity (noise, promo text, platform names, a bracketed label, notes after a label), with its kind (R5.1) |
warnings |
Warning[] |
Which heuristics fired. See Warnings |
The guides show each field at work: Modes for mode,
Junk, flags and prefixes for position, timestamp, year,
label, flags and junk, Artists and credits for artists, and
Versions and remixes for versions.
Artist
Section titled “Artist”{ name: string; role: ArtistRole; joiner: string | null; source: ArtistSource }Artist(name: str, role: ArtistRole, joiner: Optional[str], source: ArtistSource)pub struct Artist { pub name: String, pub role: ArtistRole, pub joiner: Option<String>, pub source: ArtistSource }type Artist struct { Name string; Role Role; Joiner *string; Source Source }typedef struct trackparse_artist { trackparse_str name; trackparse_role role; const trackparse_str *joiner; /* NULL for the first name */ trackparse_source source;} trackparse_artist;| Field | Values |
|---|---|
role |
primary, featured, remixer, producer |
joiner |
the text before the name as written ("&", ",", "ft.", "prod. by"), or null for the first name in a list |
source |
artist (left of the dash), title (right of it), version (inside a version) |
&, x and vs. are joiners, not roles. Everyone they join is primary. In Rust, role and
source are ArtistRole::Primary,
ArtistSource::Artist and so on; in Go they are
trackparse.RolePrimary, trackparse.SourceArtist and so
on; in C they are TRACKPARSE_ROLE_PRIMARY, TRACKPARSE_SOURCE_ARTIST and so on, and
trackparse_role_name() and trackparse_source_name() give the spec's strings. The splitting rules are R7.
Artists and credits has examples.
Version
Section titled “Version”{ type: VersionType; raw: string; artists: Artist[]; modifiers: VersionType[]; descriptor: string | null; year: number | null; unknownArtist: boolean; delimiter: "(" | "[" | "{" | "-";}Version( type: VersionType, raw: str, artists: tuple[Artist, ...], modifiers: tuple[str, ...], descriptor: Optional[str], year: Optional[int], unknown_artist: bool, delimiter: VersionDelimiter,)pub struct Version { pub version_type: VersionType, pub raw: String, pub artists: Vec<Artist>, pub modifiers: Vec<String>, pub descriptor: Option<String>, pub year: Option<u32>, pub unknown_artist: bool, pub delimiter: VersionDelimiter,}type Version struct { Type VersionType Raw string Artists []Artist Modifiers []string Descriptor *string Year *int UnknownArtist bool Delimiter Delimiter}typedef struct trackparse_version { trackparse_version_type type; trackparse_str type_name; trackparse_str raw; const trackparse_artist *artists; size_t artists_count; const trackparse_str *modifiers; size_t modifiers_count; const trackparse_str *descriptor; const int *year; bool unknown_artist; trackparse_delimiter delimiter;} trackparse_version;| Field | |
|---|---|
type |
one of 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 |
raw |
the text inside the brackets, as written |
artists |
remixers (role remixer, source version) |
modifiers |
type words that didn't become the type: Extended VIP Mix → vip, ["extended"] |
descriptor |
leftover words: "Taylor's", "at Wembley", "D'n'B" |
year |
a year inside the version: Remastered 2015 → 2015 |
unknownArtist |
true for ID Remix and the like |
delimiter |
the bracket it was in, or - for a dash suffix |
Python uses unknown_artist. Rust uses unknown_artist and version_type, because type is a
reserved word, and delimiter is VersionDelimiter::Paren,
Square, Curly or Dash. Go uses Type (a VersionType), UnknownArtist
and the Delimiter constants DelimiterParen, DelimiterSquare,
DelimiterCurly and DelimiterDash. C uses type (a trackparse_version_type) and type_name
(the spec's string, which differs from trackparse_version_type_name(type) only for a type that
keywords introduced), unknown_artist, and the
delimiters TRACKPARSE_DELIMITER_PAREN, _BRACKET, _BRACE and _DASH. The version rules are
R5.7.
Versions and remixes explains how the type is chosen.
Junk kinds
Section titled “Junk kinds”video, audio, lyrics, quality, promo, platform, label, genre, other, note.
Examples are in Junk, flags and prefixes.
Three things are called a label or a note, and they are different:
- the field
labelis the record label after a spaced bullet (Stigma • VISION→"VISION"); - the junk kind
labelis a label name in brackets,[NCS Release], and leaves the fieldnull; - the junk kind
noteis a segment after a second bullet (• VISION RADIO RELOAD), while the tracklist entry kindnoteis a whole tracklist line without a time that is not a header, a link or blank. The vocabulary is inspec/data. In Rust the kind is the enumJunkKind(JunkKind::Videoand so on), in Go the typed stringJunkKind(trackparse.JunkKindVideoand so on), in C the enumtrackparse_junk_kind(TRACKPARSE_JUNK_VIDEOand so on) plus the stringkind_name.
Serializing to JSON
Section titled “Serializing to JSON”All five packages write the same JSON, byte for byte, on every fixture input. The keys are the
camelCase ones of the spec (fullTitle, unknownArtist), also in Python, Rust, Go and C.
import { parse } from "trackparse";
const track = parse("Noisia - Stigma (2015)");
JSON.stringify(track);// '{"input":"Noisia - Stigma (2015)","mode":"clean","position":null,"timestamp":null,"artists":[{"name":"Noisia","role":"primary","joiner":null,"source":"artist"}],"title":"Stigma","fullTitle":"Stigma","versions":[],"year":2015,"label":null,"flags":{"explicit":false,"clean":false,"unknownArtist":false,"unknownTitle":false},"junk":[],"warnings":[]}'The result is a plain object, so JSON.stringify is all you need, and JSON.parse gives the
object back.
import jsonfrom trackparse import ParsedTrack, parse
track = parse("Noisia - Stigma (2015)")
json.dumps(track.to_dict(), separators=(",", ":"), ensure_ascii=False)# '{"input":"Noisia - Stigma (2015)","mode":"clean","position":null,"timestamp":null,"artists":[{"name":"Noisia","role":"primary","joiner":null,"source":"artist"}],"title":"Stigma","fullTitle":"Stigma","versions":[],"year":2015,"label":null,"flags":{"explicit":false,"clean":false,"unknownArtist":false,"unknownTitle":false},"junk":[],"warnings":[]}'
ParsedTrack.from_dict(track.to_dict()) == track # TrueParsedTrack, Artist, Version, Junk, Flags, Position and Timestamp are frozen
dataclasses. Sequences are tuples, so results are immutable and hashable: you can put them in sets
or use them as dict keys. to_dict() gives the spec's JSON shape as a dict, and from_dict() goes
the other way. The separators and ensure_ascii arguments above make json.dumps write the
same bytes as JavaScript.
use trackparse::{parse, ParsedTrack};
let track = parse("Noisia - Stigma (2015)");
track.to_json();// "{\"input\":\"Noisia - Stigma (2015)\",\"mode\":\"clean\",\"position\":null,\"timestamp\":null,\"artists\":[{\"name\":\"Noisia\",\"role\":\"primary\",\"joiner\":null,\"source\":\"artist\"}],\"title\":\"Stigma\",\"fullTitle\":\"Stigma\",\"versions\":[],\"year\":2015,\"label\":null,\"flags\":{\"explicit\":false,\"clean\":false,\"unknownArtist\":false,\"unknownTitle\":false},\"junk\":[],\"warnings\":[]}"
// with the `serde` feature and serde_json:let json = serde_json::to_string(&track).unwrap();json == track.to_json(); // trueserde_json::from_str::<ParsedTrack>(&json).unwrap() == track; // trueThe results are plain structs that derive Debug, Clone, PartialEq and Eq. Each has
to_json(), which writes the spec's JSON as a compact string and needs no feature and no extra
dependency. With the optional serde feature (cargo add trackparse --features serde) the result
types, the options and the tracklist Edit implement Serialize and Deserialize with the same
keys, so serde_json writes the same text and reads it back.
import ( "encoding/json" "fmt" "reflect"
"github.com/4matic/trackparse/go")
track := trackparse.Parse("Noisia - Stigma (2015)")
data, _ := json.Marshal(track)fmt.Println(string(data))// {"input":"Noisia - Stigma (2015)","mode":"clean","position":null,"timestamp":null,"artists":[{"name":"Noisia","role":"primary","joiner":null,"source":"artist"}],"title":"Stigma","fullTitle":"Stigma","versions":[],"year":2015,"label":null,"flags":{"explicit":false,"clean":false,"unknownArtist":false,"unknownTitle":false},"junk":[],"warnings":[]}
var back trackparse.Trackerr := json.Unmarshal(data, &back)fmt.Println(err, reflect.DeepEqual(back, track)) // <nil> trueThe results are plain structs with exported fields. Every result type has a
MarshalJSON method
that writes the spec's JSON, the same bytes as JSON.stringify in JavaScript, so
encoding/json needs no struct tags or options. Track also has
UnmarshalJSON, which reads
that JSON back. Nullable fields are pointers (*Position, *int), and json.Marshal writes them
as null when they are nil.
#include <trackparse.h>
trackparse_track *track = trackparse_parse("Noisia - Stigma (2015)", TRACKPARSE_NUL_TERMINATED);
trackparse_string *json = trackparse_track_to_json(track);printf("%s\n", json->str.ptr);// {"input":"Noisia - Stigma (2015)","mode":"clean","position":null,"timestamp":null,"artists":[{"name":"Noisia","role":"primary","joiner":null,"source":"artist"}],"title":"Stigma","fullTitle":"Stigma","versions":[],"year":2015,"label":null,"flags":{"explicit":false,"clean":false,"unknownArtist":false,"unknownTitle":false},"junk":[],"warnings":[]}trackparse_string_free(json);trackparse_track_free(track);trackparse_track_to_json returns a trackparse_string with the exact bytes JSON.stringify
writes in JavaScript. You own it: free it with trackparse_string_free. There is one function
per result type: trackparse_artists_to_json, trackparse_tracklist_to_json and
trackparse_edit_result_to_json. The installed library writes JSON but does not read it, so
there is no from_json; read the JSON with the JSON library you already use.
Tracklist results serialize the same way: JSON.stringify(list), tl.to_dict(),
list.to_json(), json.Marshal(list) and trackparse_tracklist_to_json(list). See the Tracklist API
and the JSON section of the tracklist guide.
All of these are exported from trackparse as TypeScript types:
ParsedTrack, Artist, ArtistRole, ArtistSource, Version, VersionType,
VersionDelimiter, Junk, JunkKind, Flags, Position, Timestamp, Warning, Mode,
ModeOption, ParseOptions, KeywordOptions, FormatOptions, and Parser, the type
createParser returns.
The package ships py.typed and passes mypy --strict. These are exported from trackparse:
- dataclasses:
ParsedTrack,Artist,Version,Junk,Flags,Position,Timestamp; Literalaliases:ArtistRole,ArtistSource,VersionType,VersionDelimiter,JunkKind,Warning,Mode,ModeOption;TypedDicts for options:ParseOptions,KeywordOptions,FormatOptions;Parser, the classcreate_parserreturns.
All of these are exported from the crate root (use trackparse::…):
- structs with public fields:
ParsedTrack,Artist,Version,Junk,Flags,Position,Timestamp; - enums:
ArtistRole,ArtistSource,VersionType,VersionDelimiter,JunkKind,Warning,Mode. Each hasas_str()(the spec's name, whichDisplayprints too),from_name(),FromStr(its error isUnknownName) andALL; - options:
ParseOptions,KeywordOptions,FormatOptions, with the enumsModeOption,SplitAnd,FeatPlacement,JoinerStyleandVersionsOption; Parser. Every result type hasto_json().
use trackparse::VersionType;
VersionType::SpedUp.as_str(); // "spedUp"VersionType::from_name("remix"); // Some(Remix)"bootleg".parse::<VersionType>(); // Ok(Bootleg)VersionType::ALL.len(); // 27Most of these enums are #[non_exhaustive], because a later spec version can add a version type or
a warning. A match on them needs a _ arm. The full API is on
docs.rs.
All of these are exported from the package (import "github.com/4matic/trackparse/go", package
name trackparse):
- structs with exported fields:
Track,Artist,Version,Junk,Flags,Position,Timestamp; - typed strings:
Role,Source,VersionType,Delimiter,JunkKind,Warning,Mode. Each has a constant per value (trackparse.RolePrimary,trackparse.VersionTypeSpedUp) and a function that returns all values in the spec's order as a new slice (AllRoles(),AllVersionTypes()). The value is the spec's name, sofmtprints it as is and a plain conversion reads one; - options:
ParseOptions,Keywords(withVersionHeadandJunkPhrase),FormatOptions, with the typed stringsSplitAnd,FeatPlacement,JoinerStyleandVersionsOption; Parser, the typeNewParserreturns. Every result type hasMarshalJSON.
fmt.Println(trackparse.VersionTypeSpedUp) // spedUpfmt.Println(trackparse.VersionType("remix") == trackparse.VersionTypeRemix) // truefmt.Println(len(trackparse.AllVersionTypes())) // 27A later spec version can add a version type or a warning, so a switch on these needs a
default case. The full API is on
pkg.go.dev.
All of these are declared in trackparse.h:
- read-only result structs:
trackparse_track,trackparse_artist,trackparse_artists(the listtrackparse_parse_artistsreturns),trackparse_version,trackparse_junk,trackparse_flags,trackparse_position,trackparse_timestamp,trackparse_str, andtrackparse_string(an owned string fromtrackparse_format,trackparse_normalizeor a_to_jsonfunction); - enums:
trackparse_role,trackparse_source,trackparse_version_type,trackparse_delimiter,trackparse_junk_kind,trackparse_warning,trackparse_mode. Each has a_name()function that returns the spec's name, andtrackparse_mode,trackparse_version_typeandtrackparse_junk_kindalso have_from_name(); - opaque option handles:
trackparse_parse_options(which also holds the keywords) andtrackparse_format_options, with the enumstrackparse_split_and,trackparse_feat,trackparse_joinersandtrackparse_versions; trackparse_parser, the handletrackparse_parser_newreturns.
printf("%s\n", trackparse_version_type_name(TRACKPARSE_VERSION_SPED_UP)); // spedUptrackparse_version_type vt;if (trackparse_version_type_from_name("remix", TRACKPARSE_NUL_TERMINATED, &vt)) { printf("%d\n", vt == TRACKPARSE_VERSION_REMIX); // 1}printf("%d\n", TRACKPARSE_VERSION_TYPE_COUNT); // 27The values of each enum are in the spec's order, so the last one plus one is the count. A later
spec version can add a version type or a warning, so a switch on these needs a default case.
The JSON shape is also published as a JSON Schema,
parsed-track.schema.json.
See also
Section titled “See also”- Options: everything
parseaccepts. - Other functions:
parseArtists,format,normalize,allArtists,createParser. - Warnings: every warning and how to check for it.
- Tracklist API:
parseTracklistandapplyEdits. - What it understands: results for real inputs.