an.music_library#

Acquire a licensed music library, with provenance: an’s bridge to foley (an#470, an#656).

The library itself lives in foley (foley.sources.music_library): the registry (incompetech, and the paid artlist and epidemic_sound, whose titles become wishlist rows), the direct and Wayback mirrors, the polite fetch with 429 / Retry-After resilience, the audio probe, the licence gate, the tracks table and the credit parser. an music add-library (an.music_cli) is its command:

an music add-library incompetech –titles-from usage.json –out audio/macleod

What stays here is what is an’s:

  • asset_source(), the bridge: one foley row (an AcquiredTrack, or its .row() read

    back from a tracks table) as an an.ir.assets.AssetSource, the provenance a sound in the project’s store carries. foley’s licence ids become an’s codes (license_code(), foley’s own mapping, foley.licensing.consumer_license_code: CC-BY-4.0 is cc-by-4.0; foley’s unknown, a paid library’s, is None, which an reads as UNKNOWN); the library’s own address is source_page_url; rights_verified, the mirror and a titles file’s metadata ride as extras.

  • acquire(), foley’s with an’s pause knob (seconds before a second request to one host), which becomes foley’s per-host rate.

  • add_track_to_sounds() (an#623): one acquired row’s verified file, cut, into the project’s sounds store with the row as its provenance, so a film uses the track without fetching it again (an music use).

The rest of foley’s surface the command and its tests use (MUSIC_LIBRARIES, tracks_table(), attribution_text(), titles_by_library(), and the tracks-table reader read_tracks_table() and LIST_SEPARATOR, an#731) is re-exported by name, and loaded on first use: import an never imports foley.

>>> license_code("CC-BY-4.0"), license_code("unknown")
('cc-by-4.0', None)
>>> src = asset_source({"title": "Sneaky Snitch", "library": "incompetech",
...                     "status": "acquired", "license": "CC-BY-4.0",
...                     "source_page_url": "https://incompetech.com/x.mp3",
...                     "rights_verified": True, "mirror": "wayback"})
>>> src.provider, src.id, src.license, src.source_page_url
('incompetech', 'Sneaky Snitch', 'cc-by-4.0', 'https://incompetech.com/x.mp3')
>>> src.model_extra
{'rights_verified': True, 'commercial_ok': True, 'mirror': 'wayback'}

Module Attributes

DFLT_PAUSE_S

a library is someone's website).

Functions

acquire(library, titles, *, out[, pause, config])

foley's acquire(), paced by pause.

add_track_to_sounds(store, key, track, files, *)

Put one acquired track in the sounds store under key (an#623).

asset_source(track)

One foley row as an's AssetSource.

attribution_text(rows)

The attribution blocks to paste under a video, one per track that has one (acquired or kept), blank-line separated, each once.

files_store(out)

out as a {file name: bytes} store: a mapping is used as it is; a folder becomes foley's file store over it (foley.stores.make_byte_store(), which makes the folder on its first write).

kept_digests(table)

{file: sha256} of the acquired or kept rows of a tracks table: what a rerun may keep.

kept_sources(table)

{file: {"sha256", "url", "mirror"}} of the acquired or kept rows of a tracks table: kept_digests() with where each file came from, so a kept row still says which URL and mirror served it (acquire(kept=...) takes either).

license_code(license_id)

foley's licence id as an's code: foley's consumer_license_code, the one mapping (an#729), imported on first use.

probe_verify(data, *[, probe, has_audio, suffix])

The duration of the audio data, in seconds.

read_tracks_table(text)

The rows of a tracks table (tracks_table()'s CSV text), as written; a byte-order mark an editor added (Excel does) is not part of the first column.

register_music_library(library, *[, replace])

Add library to MUSIC_LIBRARIES (replace to redefine one).

titles_by_library(description, *[, libraries])

The titles a video description credits, by library (default: the registered ones).

titles_from_json(text)

A titles file's JSON: a list of titles, or {title: {metadata}}.

track_row(text, title)

title's row in the tracks table text.

tracks_table(rows)

The tracks table as CSV text: TRACK_COLUMNS, then any metadata the rows carry, in name order (read_tracks_table() reads it back).

wayback(url)

The Internet Archive's raw copy of url (WAYBACK_RAW).

Classes

AcquiredTrack(title, library, status, license)

One row of the tracks table: a title, what became of it, and its provenance.

MusicLibrary(name, author[, license_url, ...])

One library: who made it, under which licence, and where a title's file is.

Exceptions

DroppedColumnsWarning

A tracks-table row named columns that set nothing, and AcquiredTrack.from_row() dropped them.

MusicLibraryError

A library, a title or a file that cannot be used, and why.

MusicToolMissing

A tool every title needs is missing: the batch stops before it starts.

class an.music_library.AcquiredTrack(title, library, status, license, file=None, sha256=None, duration_s=None, url=None, mirror=None, page_url=None, credited_by=(), metadata=dict(), error=None)[source]#

Bases: SerializableMixin

One row of the tracks table: a title, what became of it, and its provenance.

url is the URL that served the bytes (a mirror’s), mirror that mirror’s name, page_url the library’s own address for the title; credited_by the videos that credit it and metadata a titles file’s other fields (feel, genre, …).

classmethod from_row(row, *, libraries=None)[source]#

The track a tracks-table row records: the inverse of row().

row is a row() dict (or one read back from JSON), or a line of the table (read_tracks_table(): every cell text, an empty one nothing). Its library is looked up in libraries (default MUSIC_LIBRARIES) and its licence rebuilt from it (track_license()), never read from the row. The row’s licence cells (LICENSE_COLUMNS) must still say what the library states now: a cell someone edited, or a library re-registered under other terms since the table was written, is refused rather than silently widened or narrowed.

A column outside TRACK_COLUMNS is metadata, as the table wrote it (a list or mapping a titles file gave comes back as its cell’s text). A column a titles file may not set (a downstream provenance field such as cost_usd or cacheable, a licence flag) is dropped with a DroppedColumnsWarning: it never sets anything.

Raises:

MusicLibraryError – For a row with a key that is not text, a blank title, no library or status, a status not in STATUSES, a library that is not registered, a duration_s that is not a finite number, or licence cells that differ from the library’s (naming them).

Return type:

AcquiredTrack

row()[source]#

The row as the tracks table writes it: flat and JSON-safe (a list joined by ``; ``, a mapping as JSON).

Return type:

dict[str, Any]

an.music_library.DFLT_PAUSE_S: float = 2.0#

a library is someone’s website).

Type:

Seconds before a second request to one host (foley’s default pace

exception an.music_library.DroppedColumnsWarning[source]#

Bases: UserWarning

A tracks-table row named columns that set nothing, and AcquiredTrack.from_row() dropped them.

class an.music_library.MusicLibrary(name, author, license_url=None, track_url=None, attribution='"{title}" {author}', author_url=None, aliases=(), file_name=<function safe_file_name>)[source]#

Bases: object

One library: who made it, under which licence, and where a title’s file is.

license_url is the URL of its Creative Commons licence, read by license_id_from_cc_url(); None makes the library PAID (its titles become wishlist rows, never downloads; track_url is then unused). track_url is the title -> URL rule (title_url() builds one from a template). attribution is a template over {title}, {author} and {license_url}. aliases are the names a video description credits it by (From Epidemic Sound:, Kevin MacLeod (incompetech.com)); file_name the name a title is saved under.

attribution_for(title)[source]#

The library’s attribution for title, from its template.

Return type:

str

file_name(*, suffix='.mp3')#

title as a file name: NFC, path separators as -, no leading dot.

>>> safe_file_name("AC/DC"), safe_file_name("../../escape")
('AC-DC.mp3', '-..-escape.mp3')
Return type:

str

property license_id: str#

The foley licence id its licence URL maps to ('unknown' when paid).

property paid: bool#

Whether the library has no free licence (wishlist rows only).

property rights_verified: bool#

Whether foley recognises the licence outright (never for a paid library).

exception an.music_library.MusicLibraryError[source]#

Bases: ValueError

A library, a title or a file that cannot be used, and why.

exception an.music_library.MusicToolMissing[source]#

Bases: RuntimeError

A tool every title needs is missing: the batch stops before it starts.

an.music_library.acquire(library, titles, *, out, pause=2.0, config=None, **kwargs)[source]#

foley’s acquire(), paced by pause.

pause is the seconds before a second request to one host (0: no pause), foley’s rate unless config states its own. config and every other keyword (fetch, mirrors, verify, kept, intended_use, clock, sleep, …) go to foley as they are. Bridge the rows with asset_source().

Raises:

MusicLibraryError – For a negative pause, and whatever foley’s acquire refuses.

Return type:

list[AcquiredTrack]

an.music_library.add_track_to_sounds(store, key, track, files, *, start=None, duration=None, fade_out=None, description='')[source]#

Put one acquired track in the sounds store under key (an#623).

track is foley’s AcquiredTrack, or its tracks-table row (a tracks.csv line, track_row(): its licence is rebuilt from the library’s registry, AcquiredTrack.from_row), and files the library folder as {file name: bytes} (files_store(out)). The file it names is checked against its sha256, cut with an.sound_fetch.cut_to_wav() (start, duration, fade_out, as an sounds add takes them) and stored with the track as its AssetSource (asset_source()) plus the cut, the file’s digest as file_sha256, so an credits lists the music with its licence. Nothing is fetched again: the site may be the one that refused scripts.

Raises:

MusicLibraryError – For a track that holds no file (not acquired or kept, or no file/sha256), a file missing from files, one whose bytes do not match the recorded digest, or an unknown library.

Return type:

Any

an.music_library.asset_source(track)[source]#

One foley row as an’s AssetSource.

track is a foley AcquiredTrack or its .row() (as a tracks table reads back), which is rebuilt first (AcquiredTrack.from_row, an#731): its licence comes from the library’s registry, and a licence cell that says otherwise is REFUSED, so an edited row cannot grant rights. library is the provider, title the id, the licence id an’s code (license_code()); url (the mirror that served the bytes), source_page_url (the library’s own address), the licence URL, author, attribution and sha256 keep their names. The acquisition’s own columns (ROW_ONLY) stay in the table; every other column (rights_verified, commercial_ok, mirror, credited_by, a titles file’s metadata) rides as an extra; a column named like one of the source’s own fields (cost_usd, cacheable, id, …) is dropped, never trusted. Empty cells are dropped. The licence’s creator_url is the author_url and whether its terms let the bytes be kept as cacheable.

Return type:

AssetSource

an.music_library.attribution_text(rows)[source]#

The attribution blocks to paste under a video, one per track that has one (acquired or kept), blank-line separated, each once.

Each block is foley.provenance.credits.attribution_line() of the row’s licence: the library’s own wording, verbatim.

>>> from foley.sources.music_library import MUSIC_LIBRARIES, track_license
>>> lic = track_license(MUSIC_LIBRARIES["incompetech"], "A")
>>> print(attribution_text([AcquiredTrack("A", "incompetech", ACQUIRED, lic)] * 2))
"A" Kevin MacLeod (incompetech.com)
Licensed under Creative Commons: By Attribution 4.0 License
http://creativecommons.org/licenses/by/4.0/
Return type:

str

an.music_library.files_store(out)[source]#

out as a {file name: bytes} store: a mapping is used as it is; a folder becomes foley’s file store over it (foley.stores.make_byte_store(), which makes the folder on its first write).

Return type:

MutableMapping[str, bytes]

an.music_library.kept_digests(table)[source]#

{file: sha256} of the acquired or kept rows of a tracks table: what a rerun may keep. table is tracks_table()’s CSV text, or the rows themselves (AcquiredTrack or their row() dicts, read back from JSON).

Return type:

dict[str, str]

an.music_library.kept_sources(table)[source]#

{file: {"sha256", "url", "mirror"}} of the acquired or kept rows of a tracks table: kept_digests() with where each file came from, so a kept row still says which URL and mirror served it (acquire(kept=...) takes either).

Return type:

dict[str, dict[str, Any]]

an.music_library.license_code(license_id)[source]#

foley’s licence id as an’s code: foley’s consumer_license_code, the one mapping (an#729), imported on first use.

>>> license_code("CC0-1.0"), license_code("unknown"), license_code(None)
('cc0-1.0', None, None)
Return type:

str | None

an.music_library.probe_verify(data, *, probe=None, has_audio=None, suffix='.mp3')[source]#

The duration of the audio data, in seconds.

The bytes are written to a temporary file named with suffix (from a pipe, ffprobe reports no duration). has_audio(path) -> True | False | None must say True (default has_audio_stream(); None, “cannot tell”, is a refusal), then probe(path) -> seconds | None reads the length (default default_probe()).

>>> probe_verify(b"ID3...", probe=lambda path: 61.5, has_audio=lambda path: True)
61.5
>>> probe_verify(b"<html>403</html>", probe=lambda path: 3.0,
...              has_audio=lambda path: False)
Traceback (most recent call last):
...
foley.sources.music_library.libraries.MusicLibraryError: the file has no audio stream
>>> probe_verify(b"ID3...", probe=lambda path: None, has_audio=lambda path: True)
Traceback (most recent call last):
...
foley.sources.music_library.libraries.MusicLibraryError: the file has no readable duration (not audio)
Raises:

MusicLibraryError – When the file is empty, has no audio stream (or one cannot be confirmed), or has no readable duration.

Return type:

float

an.music_library.read_tracks_table(text)[source]#

The rows of a tracks table (tracks_table()’s CSV text), as written; a byte-order mark an editor added (Excel does) is not part of the first column.

>>> read_tracks_table("\ufefftitle,library\r\nA,incompetech\r\n")
[{'title': 'A', 'library': 'incompetech'}]
Raises:

MusicLibraryError – For a header that names a column twice, or a line with more cells than the header has columns (naming its line).

Return type:

list[dict[str, str]]

an.music_library.register_music_library(library, *, replace=False)[source]#

Add library to MUSIC_LIBRARIES (replace to redefine one).

A free library is checked for one licence right only, keeping the files (cache_bytes_ok); the uses a production makes of them are gated per title by acquire() (intended_use).

A library’s name is also its live-source name (foley.add_from(name, ...)), so it may not be the name of a source another foley.sources module declares, or one registered directly (openverse, freesound, a fal_* endpoint, …): that library would silently take the source over, or silently never become one.

Raises:
  • MusicLibraryError – If the name is taken (and not replace), or a free library has no track_url rule or a licence that does not allow keeping the files (a ShareAlike / NoDerivatives licence, refused on purpose; a licence URL foley cannot read; a licence whose flags say no).

  • SourceNameCollision – If the name is another module’s source name.

Return type:

None

an.music_library.titles_by_library(description, *, libraries=None)[source]#

The titles a video description credits, by library (default: the registered ones).

A line naming a library (by name or alias, with From/Music by/ Music: and a parenthetical allowed around it) opens its block, and each following line is a title until a blank line; a timestamp, a Song:/Track: label, quotes and bullets are stripped, and links and licence lines skipped. The attribution form ("Title" Kevin MacLeod (incompetech.com)) credits its title wherever it stands.

>>> text = '''Music:
... From Epidemic Sound:
... - 0:00 Night Owl
... - Song: "Morning Light"
... https://www.epidemicsound.com/
...
... "Sneaky Snitch" Kevin MacLeod (incompetech.com)
... Licensed under Creative Commons: By Attribution 4.0 License'''
>>> titles_by_library(text)
{'epidemic_sound': ['Night Owl', 'Morning Light'], 'incompetech': ['Sneaky Snitch']}
Return type:

dict[str, list[str]]

an.music_library.titles_from_json(text)[source]#

A titles file’s JSON: a list of titles, or {title: {metadata}}.

>>> titles_from_json('["A", "B"]'), titles_from_json('{"A": {"feel": "Bright"}}')
(['A', 'B'], {'A': {'feel': 'Bright'}})
Raises:

MusicLibraryError – If text is not JSON, or not one of those two shapes.

Return type:

Union[list[str], dict[str, dict[str, Any]]]

an.music_library.track_row(text, title)[source]#

title’s row in the tracks table text.

Raises:

MusicLibraryError – When no row has that title, naming the ones there are.

Return type:

dict[str, str]

an.music_library.tracks_table(rows)[source]#

The tracks table as CSV text: TRACK_COLUMNS, then any metadata the rows carry, in name order (read_tracks_table() reads it back).

Return type:

str

an.music_library.wayback(url)[source]#

The Internet Archive’s raw copy of url (WAYBACK_RAW).

>>> wayback("https://example.org/a.mp3")
'https://web.archive.org/web/2id_/https://example.org/a.mp3'
Return type:

str