Metadata-Version: 2.5
Name: binary-tidal-py
Version: 0.1.3
Summary: tidalpy: programmatic Tidal catalog and download library for tidal_transfer
Project-URL: Homepage, https://git.binarycollective.de/binary/binary-tidal-py
Project-URL: Repository, https://git.binarycollective.de/binary/binary-tidal-py
Keywords: audio,downloader,library,music,tidal
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Topic :: Utilities
Requires-Python: >=3.12
Requires-Dist: defusedxml<1,>=0.7.1
Requires-Dist: mutagen<2,>=1.47
Requires-Dist: pycryptodome<4,>=3.20
Requires-Dist: pydantic<3,>=2.9
Requires-Dist: requests<3,>=2.32
Provides-Extra: socks
Requires-Dist: pysocks<2,>=1.7; extra == 'socks'
Description-Content-Type: text/markdown

# binary-tidal-py (`tidalpy`)

Programmatic Tidal catalog and download **library** — a clean restart
of the proven core from
[Tidal-Media-Downloader](https://git.binarycollective.de/binary/Tidal-Media-Downloader),
with all the CLI baggage dropped.

It is a library, not a tool: a real-time search UI, an indexer, a
player, a Django/Celery sync job, a plain download script — each one
gets the same small, structured, in-process API. The hard parts of
Tidal are inside the library: two parallel catalog APIs, the
quality-downgrade chain, rate limiting with retry and a queryable
adaptive pace (`client.rate_limit_status()`), atomic file writes.

[Documentation](https://tidalpy.natz.club) ·
[AGENTS.md](AGENTS.md) (design contracts + port plan)

## What it is

- A Python **library**, not a CLI: `TidalClient` + injected `Config`,
  no global state (Django multi-worker / Celery prefork safe).
- **Every audio collection**: tracks, albums, playlists, mixes — and
  full **artists** (the discography lands in per-album folders, TMD
  parity).
- **Catalog and real-time search**: full search with a best-match
  row, the keystroke suggest endpoint, the genre "Discover" browse,
  user playlists, track credits — uniform render-ready rows
  (kind/id/title/link plus the catalog's garnish badges, e.g.
  `release_date`, `audio_modes`, `pay_to_stream`, `explicit`),
  per-market `country`, JSON-safe dicts or typed models. The query
  family shares the download family's cancellation surface:
  `client.cancel()` stays client-wide, and every registered op
  takes a per-op `cancel_event` — a search UI can run alongside a
  download on ONE client (set the stale search's event on the next
  keystroke).
- **Ids- and keys-first fetching**: `tracks_by_ids` / `albums_by_ids`
  / `artists_by_ids` / `playlists_by_ids` (one catalog call per 50),
  plus `track_by_isrc` / `album_by_upc` and their bulk siblings for
  hosts that hold ids, ISRCs, or barcodes instead of links. Any
  link-accepting method (`resolve`, `metadata`, `stream`,
  `download`) also takes a kind-qualified fragment —
  `track/12345` instead of the full URL — which resolves in one
  catalog call, no probing.
- **Playback before bytes**: `client.playback(url)` resolves what
  will be played — delivered quality, codec, rate/depth, preview
  flag, the expiring CDN link — without streaming a single byte.
- **Per-item failure isolation**: collection downloads survive broken
  items and return a structured `DownloadReport`; `resolve_many`
  gives the same isolation to the pre-flight of a link blob (one
  JSON-safe row per URL, machine failure codes).
- **Per-track parallelism**: `download(..., track_workers=N)` fetches
  a collection's tracks on N workers with one shared rate limiter
  and index-order events — the same per-item isolation (a broken
  item can never take the pool down), cancellation drains the
  not-yet-started slots as "cancelled".
- **Reference-parity resilience**: an OAuth client registry with
  per-client quality support (`clients_for`), the 4022
  refresh-before-clear ladder for stale logins, and a deterministic
  stale-snapshot recovery ladder (id → ISRC → exact composite
  predicate) that revives dead playlist/album items instead of
  marking them broken.
- **Resume & skip-existing**: `.part` files, trusted only for the
  same source (the source identity recorded in `.part.source.json`
  defeats a same-size different rendition), atomic promotion, a
  failed HEAD never forces a re-download, colliding track names get
  deterministic `(position)` suffixes instead of overwriting.
- **Two I/O modes**: disk (library writes files) or **streaming**
  (`client.stream(url)` yields plaintext audio bytes — the host does
  the file I/O, e.g. S3 multipart upload).
- **Multiple writers, one library**: `lock_output_dir` (in
  `tidalpy.output_lock`) serializes separate *processes* writing the
  same output tree — a web worker and a desktop app, a
  double-dispatched Celery pair — with an atomic dotfile lock,
  staleness detection, and queued waiting with a typed timeout.
- **Prefork-safe by construction**: locks re-create on pid change
  (`ForkSafeLock`), the transport rebuilds its HTTP session in the
  forked child, and the token record is a per-child private copy —
  a client built in the parent process stays usable in every child.
- **Log-safe by construction**: signed CDN URLs and bearer
  credentials are redacted at the error boundary (every
  `TidalError` message is clean at construction) and available as a
  `logging` filter for the host's own lines (`RedactionFilter`).
- **Metadata first-class**: `client.lyrics(url)`, `client.metadata(url)`,
  `client.list_items(url, deep=True)` — a pre-flight report with the
  resolved codec, expected path and on-disk state per item; tags
  carry composer credit, ISRC, copyright, ReplayGain and (optionally)
  embedded lyrics and cover art; `client.retag(url)` re-applies the
  tag pass to an existing library (zero media traffic for the files
  already on disk).
- **Post-download encode**: `client.transcode(src, dst, preset=...)`
  re-encodes a finished file with a fixed ffmpeg argument matrix —
  the five CDJ presets (`universal`, `xdj700`, `cdj2000`,
  `cdj2000nxs2`, `cdj3000`), tags preserved (`-map_metadata 0`), the
  destination swapped atomically, the source never touched.
- **TMD-parity naming templates**: `track_format` supports
  `{number} {artist} {artists} {title} {explicit} {album} {year}
  {quality} {id} {duration} {duration_seconds}`, `album_format`
  supports `{artist} {album} {title} {year} {flag} {id} {quality}
  {type} {release_date} {number_of_tracks} {number_of_volumes}`,
  `playlist_format` supports `{title} {id}` — all opt-in
  placeholders, the delivered quality in the file name makes a
  silent downgrade visible.
- **Models that know their own links**: `track.link` / `album.link` /
  `artist.link` / `playlist.link` (and `Resource.link`) build the
  canonical URLs, pinned to round-trip through `parse_tidal_url`;
  `album.year` and `track.key_label` are free card/DJ ergonomics.
- **Validated, immutable, typed**: `Config` is a pydantic model
  (bad values fail fast with `ConfigError`), the API ships `py.typed`.
- Standard `logging` only; progress is a callback of JSON-safe dicts.

## Quick start

```python
from tidalpy import Config, Quality, TidalClient

client = TidalClient(Config(token_path="~/.tidalpy/token.json"))
if not client.auth_status()["logged_in"]:
    auth = client.start_device_login()
    print("approve at", auth.verification_url)
    client.finish_device_login(auth, timeout=300)

report = client.download(
    "https://tidal.com/album/155243",
    quality=Quality.LOSSLESS,
    on_progress=lambda e: print(e["stage"], e.get("bytes")),
)
print(report.ok, [i.status for i in report.items])

# or, host-owned file I/O (no disk in the library):
with client.stream("https://tidal.com/track/12345678") as media:
    for chunk in media.chunks():
        upload_to_s3(chunk)

# artists and lyrics:
client.download("https://tidal.com/artist/64518")  # discography, per-album folders
client.artist_albums("https://tidal.com/artist/64518")  # discography as dicts
client.lyrics("https://tidal.com/track/68883384")  # {"lyrics", "subtitles"}, "" values when none

# and a real-time search box: autocomplete as the user types
# (same row shape as search, so one renderer covers both):
client.autocomplete("radio")            # -> [{"kind", "id", "title", "artist", ...}]
result = client.search("radiohead", item_type="album", limit=5)
for row in result["items"]:             # kind/id build https://tidal.com/<kind>/<id>
    print(row["title"], row["id"])
client.search_all("radiohead", item_type="album")  # all pages, merged (indexers)
client.search_albums("radiohead", prefer_atmos=True)  # an artist's discography, Atmos twins inserted
```

## Requirements

- Python >= 3.12
- `ffmpeg`/`ffprobe` on `PATH` for the remux/verification options
  (optional — turn them off via `Config` if absent)

## Develop

```bash
uv sync --group dev

# the verification one-liner (must be green before committing)
uv run ruff check . && uv run black --check . && \
uv run isort --check-only . && uv run flake8 . && \
uv run mypy src/tidalpy && uv run pytest

# documentation (deployed at https://tidalpy.natz.club)
uv run sphinx-build -b html -W docs docs/_build/html

# live e2e (needs a real token; skipped otherwise)
TIDALPY_LIVE_TOKEN=... uv run pytest tests/test_live_e2e.py -v
```

All four linters (black, isort, ruff, flake8) and the test suite
(coverage >= 90%) must pass. CI: `.forgejo/workflows/ci.yml`
(lint + test + docs); publishing: `.forgejo/workflows/publish.yml`
(tag `vX.Y.Z` → Forgejo package registry + release).

## Releasing

A pushed `vX.Y.Z` tag **is** the release — the tag name owns the
version, and the tag's tree must carry it (the published dists and
the docs build read it from `pyproject.toml`). Master pushes never
release:

```bash
# on master, with the full gate green:
uv version 0.1.0          # aligns pyproject.toml with the tag
git commit -am "chore: 0.1.0"
git tag v0.1.0
git push origin master v0.1.0
```

The tag-triggered publish workflow re-aligns `pyproject.toml` with
the tag (`uv version` — a no-op for a well-formed release, a
fail-fast on a non-semver `v*` tag), builds, publishes to the
Forgejo package registry, and creates the Forgejo release.
Conventional commits are kept (for a later changelog integration);
nothing bumps from them for now.

## Docs container (Coolify)

The Sphinx site ships as a static nginx container; every page's
footer shows the build's identity — the version plus the short hash
of the commit the site was built from (`vX.Y.Z-<shorthash>`, the
hash whenever it is known):

```bash
docker build -f docs/Dockerfile -t tidalpy-docs .
docker run --rm -p 8080:80 tidalpy-docs
```

`docs/docker-compose.yml` is a ready-made service definition for
Coolify (Dockerfile service, port 80). On a webhook deploy Coolify
wires the commit the site was built from into the `GIT_COMMIT`
build arg from `CI_COMMIT_SHA`; the version comes from
`pyproject.toml` in the build context. See
[docs/README.md](docs/README.md) for the container, the footer, and
local builds.
