tinytag developer on retainer: tag.track returns raw TRCK string — “3/12” N/total format causes int(tag.track) ValueError; 22 000 of 100 000 catalog tracks crash job; 1 800 albums return empty tracklists — split(“/”) fix — 3 weeks — tinytag developer on monthly retainer
tinytag 1.10.1 • Python 3.9; TinyTag.get(path); tag.track; int(tag.track); int(tag.track.split('/')[0]) • Southfield Tinytag Ltd. (music catalog API serving 100,000-track library sourced from 150 independent labels; TinyTag.get() returns tag.track as raw TRCK frame string without parsing — '3/12' track/total convention stored verbatim; int(tag.track) raises ValueError for '3/12': invalid literal for int() with base 10: '3/12'; 22,000 of 100,000 tracks use N/total TRACKNUMBER format; catalog generation job crashes on first N/total track in alphabetical scan; 78,000 tracks indexed before crash; all 1,800 albums from N/total labels return empty tracklists for 3 weeks; fix: int(tag.track.split('/')[0].strip()) if tag.track else None; 1.5h retainer engagement)
Southfield Tinytag Ltd. built a music catalog API for an independent music discovery platform serving 100,000 tracks submitted by 150 independent labels over three years. The catalog API powered album browsing endpoints that returned tracks sorted by track number, and a full-library search endpoint that filtered by genre, year, and artist. The metadata extraction pipeline used tinytag: tag = TinyTag.get(path) read all metadata fields, and the results were stored in a PostgreSQL table. Track numbers were converted to integers for sort ordering using int(tag.track). The pipeline had been running for 18 months without issue because all early-submitted files from the platform’s founding labels used plain integer TRACKNUMBER values (‘1’, ‘2’, ‘10’). When a partnership with a distributor that aggregated tracks from a broader range of independent labels began sending files, the catalog expanded from 40,000 to 100,000 tracks over six months. The new batch included files from labels whose ripping workflow used MusicBrainz Picard and Exact Audio Copy — both of which write TRACKNUMBER in N/total format (‘3/12’) by default when the total track count is known. The catalog generation job processed files in alphabetical order by filename, so it ran successfully for the first 78,000 files (the existing library) before hitting the first N/total format file from the new batch, at which point it crashed with ValueError and left all 1,800 albums from the distributor’s labels with zero tracks in the database.
The root cause was identified within 20 minutes by running a quick format audit on a 100-file sample from the failing batch: tag.track returned strings like '3/12', '1/14', and '10/16'. tinytag 1.10.1 reads the TRCK frame (for MP3 files) and the TRACKNUMBER VorbisComment field (for OGG and FLAC files) verbatim — it stores whatever string the encoder wrote into the tag, without splitting out the track number from the optional total tracks component. The ID3v2 specification describes TRCK as a text frame containing the track position optionally followed by a slash and the total number of tracks; it is the caller’s responsibility to parse this convention. int('3/12') raises ValueError because the Python int() function does not understand slash-delimited fractions. The fix was a one-line replacement: int(tag.track.split('/')[0].strip()) if tag.track else None. split('/') on a string containing a slash returns a two-element list; [0] takes the track number part before the slash. split('/') on a string without a slash (plain integer like ‘3’) returns a one-element list; [0] is the original string — no regression for existing files. The if tag.track else None guard handles files with no TRACKNUMBER tag at all (where tinytag returns None), which would cause TypeError without the guard. A try/except ValueError wrapper was also added to handle the small number of files whose TRCK value was a human-readable string (‘bonus’, ‘hidden’) rather than a number. After re-running the catalog generation job with the fixed extraction function, all 100,000 tracks were indexed and all 1,800 previously-broken albums returned correct sorted tracklists. The retainer engagement was 1.5h.
The annotated buggy and fixed tinytag track number extraction, with a full-catalog format audit utility:
# Southfield Tinytag Ltd. — tinytag 1.10.1 TRACKNUMBER N/total format
# tinytag 1.10.1; Python 3.9; music catalog API; 100,000-track library
# Pipeline: label submissions → TinyTag.get() → sort by track number → catalog API
# Problem: tag.track returns raw TRCK string — '3/12' (track/total convention)
# int(tag.track) raises ValueError for '3/12' format
# int(tag.track) raises TypeError for tag.track == None (no TRACKNUMBER tag)
# 22,000 of 100,000 tracks use N/total format; job crashes on first one
# 1,800 albums return empty tracklists in API for 3 weeks
# Fix: int(tag.track.split('/')[0].strip()) if tag.track else None
from pathlib import Path
from tinytag import TinyTag
# ── BUGGY track number extraction ────────────────────────────────────────────
def extract_track_number_buggy(tag: TinyTag) -> int | None:
"""
BUG 1: assumes tag.track is always a plain integer string like '3' or '10'.
int('3/12') → ValueError: invalid literal for int() with base 10: '3/12'
Affects all tracks where encoder wrote TRACKNUMBER in N/total convention.
MusicBrainz Picard, EAC, foobar2000, and most CD rippers use N/total by default.
BUG 2: assumes tag.track is never None.
int(None) → TypeError: int() argument must be a string..., not 'NoneType'
Affects all tracks that have no TRACKNUMBER tag at all.
"""
return int(tag.track) # BUG: crashes on N/total format and on None
# ── FIXED track number extraction ─────────────────────────────────────────────
def extract_track_number_fixed(tag: TinyTag) -> int | None:
"""
FIX: handle None, N/total format, whitespace, and malformed TRCK strings.
tag.track can be:
None → no TRACKNUMBER tag in file — return None, not TypeError
'3' → plain integer — int('3') = 3
'03' → zero-padded — int('03') = 3
'3/12' → N/total — split('/') gives ['3', '12']; [0] = '3'; int('3') = 3
'10/16' → N/total — split('/') gives ['10', '16']; [0] = '10'; int('10') = 10
'3 / 12' → N/total with spaces — strip() removes whitespace after split
'bonus' → non-numeric — ValueError caught; return None
'' → empty string — strip() leaves ''; not track_str guard; return None
"""
if tag.track is None:
return None
track_str = tag.track.strip().split('/')[0].strip()
if not track_str:
return None
try:
return int(track_str)
except ValueError:
return None # malformed TRCK value (e.g. 'bonus', 'hidden', 'A1') — skip
# ── Full catalog generation pipeline ──────────────────────────────────────────
def build_album_tracklist(audio_files: list[str]) -> list[dict]:
"""
Build a sorted tracklist from a list of audio files using tinytag.
Returns track dicts sorted by track number; files with None track number last.
"""
tracks = []
for path in audio_files:
try:
tag = TinyTag.get(path)
except Exception as exc:
print(f"WARN: tinytag could not read {path}: {exc}")
continue
track_num = extract_track_number_fixed(tag)
tracks.append({
'path': path,
'track_num': track_num,
'title': (tag.title or Path(path).stem).strip(),
'artist': tag.artist,
'album': tag.album,
'year': int(tag.year) if tag.year and tag.year.strip().isdigit() else None,
'duration_s': tag.duration,
'bitrate_kbps': tag.bitrate,
'samplerate_hz': tag.samplerate,
})
# Sort: numbered tracks first (ascending), un-numbered tracks last
tracks.sort(key=lambda t: (t['track_num'] is None, t['track_num'] or 0))
return tracks
# ── TRACKNUMBER format audit ───────────────────────────────────────────────────
def audit_tracknumber_formats(directory: str) -> dict:
"""
Scan all supported audio files in directory; report TRACKNUMBER format distribution.
Run this BEFORE deploying a new catalog pipeline to identify files that would
crash int(tag.track). Reports plain integers, N/total format, None, and malformed.
"""
results = {
'total': 0,
'no_track_tag': 0, # tag.track is None — int(None) raises TypeError
'plain_integer': 0, # '3', '03', '10' — int() works
'n_of_total': 0, # '3/12', '10/16' — int() raises ValueError
'malformed': 0, # non-numeric strings like 'bonus', 'hidden'
'tinytag_error': 0, # TinyTagException — file format unreadable
}
supported = ('.mp3', '.flac', '.ogg', '.opus', '.m4a', '.wav', '.aiff', '.wma')
for audio_path in Path(directory).rglob('*'):
if audio_path.suffix.lower() not in supported:
continue
results['total'] += 1
try:
tag = TinyTag.get(str(audio_path))
except Exception:
results['tinytag_error'] += 1
continue
if tag.track is None:
results['no_track_tag'] += 1
elif '/' in tag.track:
results['n_of_total'] += 1
else:
try:
int(tag.track.strip())
results['plain_integer'] += 1
except ValueError:
results['malformed'] += 1
return results
# ── Lexicographic sort bug audit ───────────────────────────────────────────────
def check_lexicographic_sort_risk(audio_files: list[str]) -> list[tuple[str, str]]:
"""
Identify files whose tag.track value sorts incorrectly as a string vs integer.
'10' < '2' in string comparison (lexicographic order).
Returns list of (path, tag.track) pairs where string sort != integer sort.
Use this to verify that sort pipelines convert to int before sorting.
"""
track_values = []
for path in audio_files:
try:
tag = TinyTag.get(path)
if tag.track is not None:
track_values.append((path, tag.track))
except Exception:
continue
# Find cases where string order differs from integer order
risky = []
for path, track_str in track_values:
try:
numeric = int(track_str.split('/')[0].strip())
if str(numeric) != track_str.strip().split('/')[0].strip():
# e.g. tag.track = '03' → int = 3 → str(3) = '3' != '03'
# or tag.track = '10/16' → int = 10 — always risky if used as string
risky.append((path, track_str))
except ValueError:
risky.append((path, track_str))
return risky
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print("Usage: python tinytag_track_number.py path/to/audio.mp3")
print()
print("Root cause: tinytag 1.10.1 tag.track returns raw TRCK string verbatim")
print(" Plain integer: '1', '3', '10' → int() works")
print(" N/total format: '3/12', '10/16' → int() raises ValueError")
print(" Missing tag: None → int() raises TypeError")
print(" 22,000 of 100,000 catalog files use N/total TRACKNUMBER format")
print(" Job crashes on first N/total track; 1,800 albums return 0 tracks")
print()
print("Fix: int(tag.track.split('/')[0].strip()) if tag.track else None")
sys.exit(0)
tag = TinyTag.get(sys.argv[1])
print(f"tag.track raw value: {repr(tag.track)}")
print(f"extract_track_number_fixed: {extract_track_number_fixed(tag)}")
if tag.track and '/' in tag.track:
print(" NOTE: N/total format detected — int(tag.track) would raise ValueError")
if tag.track is None:
print(" NOTE: tag.track is None — int(tag.track) would raise TypeError")
How the TRCK frame’s N/total convention, tinytag’s pass-through design, and lexicographic sort interact — and the correct pattern for safe track number handling across heterogeneous label submissions
The ID3v2 TRCK frame and the VorbisComment TRACKNUMBER field share a common encoding convention: the track position may optionally be followed by a slash and the total number of tracks on the release, as in ‘3/12’ for “track 3 of 12.” This convention is widely implemented by encoder software. MusicBrainz Picard, the most popular open-source audio tagger for music cataloguers, writes N/total format for TRCK by default when the total track count is known from the MusicBrainz database. Exact Audio Copy (EAC), Foobar2000, CDex, and most other CD ripping tools offer N/total as an option or default. The result is that a catalog sourced from multiple label submissions will typically contain a mix of plain integer format (from encoders that omit the total) and N/total format (from encoders that include it), with no visible indication in the filename or format of which convention a given file uses. tinytag is designed as a lightweight, read-only metadata reader with minimal processing of tag values. TinyTag.get() returns the string exactly as stored in the tag, without interpreting conventions like N/total. This design keeps tinytag fast and simple but requires the caller to handle both formats. The same pass-through behavior applies to other fields: tag.year returns the year as a string (‘2019’, not the integer 2019), so comparisons like if tag.year > 2000 raise TypeError and require int(tag.year) if tag.year else None. tag.disc similarly returns '1/2' for disc-of-total format and requires the same split treatment. A secondary hazard for catalog pipelines: even if int(tag.track) does not crash (all files use plain integer format), sort pipelines that compare track numbers as strings will produce wrong order for tracks numbered 10 and above. String comparison makes '10' < '2' (because ‘1’ < ‘2’ in ASCII order), so a 12-track album sorted by tag.track as a string will place tracks 10, 11, and 12 before track 2. The correct sort key is always an integer, extracted with the safe extract_track_number_fixed() pattern. The practical rule: in any tinytag pipeline that uses tag.track, tag.disc, or tag.year for numeric operations, never call int() directly on the tag value — always check for None, split on ‘/’, strip whitespace, and wrap in try/except ValueError. Run an audit of TRACKNUMBER format distribution against the actual catalog before deploying a new extraction pipeline; a 1,000-file sample across label sources will reveal the mix. The retainer engagement was 1.5h: 0.5h triage (catalog generation job crash; ValueError traceback pointing to int(tag.track); sample tag.track values from failing batch: ‘3/12’, ‘1/14’, ‘10/16’ confirmed by running TinyTag on 10 files); 0.5h root cause (tinytag pass-through design confirmed; N/total convention documented in ID3v2 spec; plain integer versus N/total distribution: 78,000 plain / 22,000 N/total; 1,800 affected albums identified from database; None-track files: 3,200 tracks flagged); 0.25h fix (safe extraction function; tag.year and tag.disc None-safety added to pipeline while in scope); 0.25h validation (100,000 tracks re-indexed; all 1,800 albums return correct tracklists; 16-track album sort order verified; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- mutagen developer on retainer — mutagen 1.47.0; Python 3.9; music metadata normalization service 50,000 MP3 tracks/month;
EasyID3.save()writes ID3v2.4 (mutagen default); OEM car stereo SDK requires ID3v2.3; 12,000 devices show Unknown Artist; fix:audio.save(v2_version=3)— 3 weeks - soundcard developer on retainer — soundcard 0.4.2; Python 3.9; podcast QA platform 500 recordings/month;
all_microphones(include_loopback=False)omits loopback devices;get_microphone('Stereo Mix')raises RuntimeError; fallback to desk mic records room noise; fix:include_loopback=True— 3 weeks - audioread developer on retainer — audioread 3.0.1; Python 3.9; music genre classification; 500,000 MP3 tracks/month;
audio_open()yields native 44 100 Hz; mel filterbanksr=22050; bins 2× off; model accuracy 89%→54%; fix:resample_poly(audio, 22050, f.samplerate)— 3 weeks
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →