foley.sources.music_library#
Acquire a licensed music library, with provenance: verified files, a tracks table, attribution.
A production that scores itself from free libraries writes the same script each
time: turn the titles a channel credits into download URLs, fetch them politely,
check each file is audio, record where it came from and under which licence, and
collect the attribution lines the licence asks for. acquire() is that script:
from foley.sources.music_library import acquire, attribution_text, tracks_table
rows = acquire("incompetech", ["Sneaky Snitch"], out="audio/macleod")
open("audio/macleod/tracks.csv", "w").write(tracks_table(rows))
print(attribution_text(rows))
A library is data (
MusicLibrary,MUSIC_LIBRARIES,register_music_library()):incompetech(Kevin MacLeod, CC BY 4.0) andthe paid
artlistandepidemic_sound, whose titles become wishlist rows.Licences come from foley’s SSOT: each row’s
LicenseRecordis built from the library’s licence URL byfoley.licensing.license_id_from_cc_url()(track_license()) and gatedby
foley.licensing.refusal_reason()foracquire’sintended_use(default: commercial publishing) before anything is fetched; a refused title is arefusedrow. A paid library claims no rights.Fetching is foley’s: a
Transportwrapped per host byfoley.sources.resilience.resilient()(pace,429/Retry-After, breaker), with the library’s own server then the Internet Archive’s raw copy as mirrors (direct(),wayback());probe_verify()checks each file has an audio stream and a length, with foley’s media probes.Rows are portable (
AcquiredTrack):.row()is flat and JSON-safe,tracks_table()writes them as CSV,read_tracks_table()reads it back(an editor’s byte-order mark dropped) and
AcquiredTrack.from_rowturns a row into its track again, the licence rebuilt from the registry, never the row’s cells (which must agree with it; a column that sets nothing is dropped with aDroppedColumnsWarning).held_rows()are those whose file is held, andkept_digests()(orkept_sources(), with each file’s URL) what a rerun keeps, so it fetches onlywhat it lacks. A titles file’s metadata may not name a row’s column, a licence flag, or a downstream provenance field (
foley.provenance.rights.PROVENANCE_FIELDS).Each free library is also a live retrieve source of its own name (#212):
foley.add_from("incompetech", query="Sneaky Snitch")(a title, a list of titles, or a credits description) puts each title through the licence gate under the call’s intent andingest_one(), giving by-valueSoundRecordrows with their attribution, and a run manifest. The config is built from the library (library_source_config(), declared as the callableconfig.SOURCE_CONFIGS, so a library registered at runtime is a source on the next discovery); the adapter (MusicLibraryAdapter) runs the same mirror chain andverifyasacquire(). A paid library is not a source.
Stdlib only at import; requests loads on the first real download.
>>> lib = MUSIC_LIBRARIES["incompetech"]
>>> lib.track_url("Sneaky Snitch")
'https://incompetech.com/music/royalty-free/mp3-royaltyfree/Sneaky%20Snitch.mp3'
>>> track_license(lib, "Sneaky Snitch").license_id
'CC-BY-4.0'
Functions
|
Download |
|
The attribution blocks to paste under a video, one per track that has one (acquired or kept), blank-line separated, each once. |
|
The URL itself: the library's own server. |
|
|
|
|
|
The acquired or kept rows (with a file and a digest) of a tracks table, as row dicts: |
|
|
|
|
|
The |
|
The default |
|
The name a row records for |
|
|
|
|
|
|
Whether |
|
|
The duration of the audio |
|
The rows of a tracks table ( |
|
Add |
Raise |
|
|
|
|
The |
|
The titles a video description credits, by library (default: the registered ones). |
|
A titles file's JSON: a list of titles, or |
|
The |
|
The tracks table as CSV text: |
|
The Internet Archive's raw copy of |
Classes
|
One free music library as a retrieve source (a |
|
One row of the tracks table: a title, what became of it, and its provenance. |
|
One library: who made it, under which licence, and where a title's file is. |
Exceptions
A tracks-table row named columns that set nothing, and |
|
A library, a title or a file that cannot be used, and why. |
|
A tool every title needs is missing: the batch stops before it starts. |
- class foley.sources.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:
SerializableMixinOne row of the tracks table: a title, what became of it, and its provenance.
urlis the URL that served the bytes (a mirror’s),mirrorthat mirror’s name,page_urlthe library’s own address for the title;credited_bythe videos that credit it andmetadataa titles file’s other fields (feel,genre, …).- classmethod from_row(row, *, libraries=None)[source]#
The track a tracks-table
rowrecords: the inverse ofrow().rowis arow()dict (or one read back from JSON), or a line of the table (read_tracks_table(): every cell text, an empty one nothing). Itslibraryis looked up inlibraries(defaultMUSIC_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_COLUMNSis 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 ascost_usdorcacheable, a licence flag) is dropped with aDroppedColumnsWarning: 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, aduration_sthat is not a finite number, or licence cells that differ from the library’s (naming them).- Return type:
- exception foley.sources.music_library.DroppedColumnsWarning[source]#
Bases:
UserWarningA tracks-table row named columns that set nothing, and
AcquiredTrack.from_row()dropped them.
- class foley.sources.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:
objectOne library: who made it, under which licence, and where a title’s file is.
license_urlis the URL of its Creative Commons licence, read bylicense_id_from_cc_url();Nonemakes the library PAID (its titles become wishlist rows, never downloads;track_urlis then unused).track_urlis thetitle -> URLrule (title_url()builds one from a template).attributionis a template over{title},{author}and{license_url}.aliasesare the names a video description credits it by (From Epidemic Sound:,Kevin MacLeod (incompetech.com));file_namethe name a title is saved under.- attribution_for(title)[source]#
The library’s attribution for
title, from its template.- Return type:
- file_name(*, suffix='.mp3')#
titleas 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:
- exception foley.sources.music_library.MusicLibraryError[source]#
Bases:
ValueErrorA library, a title or a file that cannot be used, and why.
- exception foley.sources.music_library.MusicToolMissing[source]#
Bases:
RuntimeErrorA tool every title needs is missing: the batch stops before it starts.
- foley.sources.music_library.acquire(library, titles, *, out, fetch=None, transport=None, mirrors=(<function direct>, <function wayback>), verify=<function probe_verify>, kept=None, intended_use=IntendedUse(commercial=True, publish=True, redistribute_standalone=False, will_train=False, can_attribute=True, revenue_usd=0, allow_voice_or_trademark=False, territory=None), libraries=None, config=None, clock=<built-in function monotonic>, sleep=<built-in function sleep>)[source]#
Download
titlesoflibraryintoout, verified, one row each.titlesis a list, or{title: metadata}whose metadata (credited_by: the videos that credit it; a catalogue’sfeel,genre, …) rides on the row.libraryis aMusicLibraryor a name inlibraries(defaultMUSIC_LIBRARIES).Each title’s licence is put through
foley.licensing.refusal_reason()forintended_usefirst (fail-closed: an error in the gate is a refusal); a refused title is arefusedrow and is not fetched. The others are fetched from each ofmirrorsin turn until one gives bytesverifyaccepts.fetch(url -> bytes) replaces the HTTP path, paced per host by the config’srate; otherwise the files come throughtransport(default:requests) wrapped by foley’s resilience layer per host; that path honoursfoley.offline().configis laid overMUSIC_LIBRARY_HTTP;clock/sleeptime the waits.keptis{file name: sha256}a previous run recorded (kept_digests()), or{file name: {"sha256", "url", "mirror"}}(kept_sources(), whoseurlandmirrorthe kept row keeps): a file inoutwith that digest is kept, any other is fetched again. A paid library downloads nothing and returns wishlist rows.- Raises:
MusicLibraryError – For an unknown library, titles of the wrong shape, metadata that restates the row, two titles saved as one file, or a
keptvalue that is neither a digest nor a mapping with one.MusicToolMissing – When
verifyis the default and no probe can run (before anything is downloaded).ValueError – When both
fetchandtransportare given.
- Return type:
- foley.sources.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:
- foley.sources.music_library.direct(url)[source]#
The URL itself: the library’s own server.
>>> direct("https://example.org/a.mp3") 'https://example.org/a.mp3'
- Return type:
- foley.sources.music_library.fetch_audio(url, *, http, config=None)[source]#
url’s bytes, asked for with the config’s user agent.A body over
max_bytesis refused by its declaredContent-Lengthbeforeresp.contentis touched, and by its length after (a server may declare none, or lie). foley’sTransportreturns a whole response, so withrequests_transport()the body is already in memory when the header is read: the header check spares the copy, not the download. A streaming transport, which would stop atmax_bytes, is a follow-up.- Raises:
MusicLibraryError – On a non-200 answer, a
text/*page (an error page served with 200), a body overconfig['max_bytes'], or one shorter than its declaredContent-Length(a cut download, which a probe of its header alone would still accept).- Return type:
- foley.sources.music_library.files_store(out)[source]#
outas 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:
- foley.sources.music_library.held_rows(table)[source]#
The acquired or kept rows (with a file and a digest) of a tracks table, as row dicts:
tableistracks_table()’s CSV text (read_tracks_table()) or the rows themselves (AcquiredTrackor theirrow()dicts).
- foley.sources.music_library.kept_digests(table)[source]#
{file: sha256}of the acquired or kept rows of a tracks table: what a rerun may keep.tableistracks_table()’s CSV text, or the rows themselves (AcquiredTrackor theirrow()dicts, read back from JSON).
- foley.sources.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).
- foley.sources.music_library.library_source_config(library)[source]#
The
SOURCE_CONFIGof the freelibrary.- Raises:
MusicLibraryError – If
libraryis paid (a paid library is not a source).- Return type:
- foley.sources.music_library.make_fetch(*, transport=None, config=None, clock=<built-in function monotonic>, sleep=<built-in function sleep>)[source]#
The default
url -> bytes:fetch_audio()overpolite_transport()(configlaid overMUSIC_LIBRARY_HTTP).
- foley.sources.music_library.mirror_name(mirror)[source]#
The name a row records for
mirror(its function name).>>> mirror_name(wayback) 'wayback'
- Return type:
- foley.sources.music_library.music_library(library, *, libraries=None)[source]#
libraryitself, or the registered library of that name.- Raises:
MusicLibraryError – If no library of that name is registered (naming those that are).
- Return type:
- foley.sources.music_library.music_library_config(config=None)[source]#
configlaid overMUSIC_LIBRARY_HTTP(top-level keys: aretryorrategiven replaces the default one whole).>>> music_library_config({"rate": {"per_min": 6}})["rate"], music_library_config()["max_bytes"] ({'per_min': 6}, 67108864)
- Return type:
- foley.sources.music_library.polite_transport(transport=None, *, config=None, clock=<built-in function monotonic>, sleep=<built-in function sleep>)[source]#
transport(defaultrequests_transport()) with a resilient wrapper per host, built fromconfig(see the module docstring).Left unwrapped when the active runtime turns
http_resilienceoff.- Return type:
- foley.sources.music_library.probe_available()[source]#
Whether
probe_verify()’s probes can run here:ffprobeonPATH, or both mixing’s video probe with anffmpeg(the length) andsoundfile(the audio stream).- Return type:
- foley.sources.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 | Nonemust sayTrue(defaulthas_audio_stream();None, “cannot tell”, is a refusal), thenprobe(path) -> seconds | Nonereads the length (defaultdefault_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:
- foley.sources.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:
- foley.sources.music_library.register_music_library(library, *, replace=False)[source]#
Add
librarytoMUSIC_LIBRARIES(replaceto 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 byacquire()(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 anotherfoley.sourcesmodule declares, or one registered directly (openverse,freesound, afal_*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 notrack_urlrule 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:
- foley.sources.music_library.require_probe()[source]#
Raise
MusicToolMissingunlessprobe_available().- Return type:
- foley.sources.music_library.safe_file_name(title, *, suffix='.mp3')[source]#
titleas 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:
- foley.sources.music_library.title_url(template)[source]#
The
title -> URLrule that puts the URL-quoted title intemplate’s{title}.>>> title_url("https://x.org/music/{title}.mp3")("Night Owl") 'https://x.org/music/Night%20Owl.mp3'
- foley.sources.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, aSong:/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']}
- foley.sources.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'}})
- foley.sources.music_library.track_license(library, title, *, page_url=None, sha256=None)[source]#
The
LicenseRecordoftitlefromlibrary.A free library’s record carries the id
license_id_from_cc_url()reads from its licence URL, the flags derived from it (requires_attributionamong them),rights_verifiedonly where that id is verified, and the library’s attribution for the title. A paid library’s claims nothing:'unknown', every flag closed, no attribution.>>> rec = track_license(MUSIC_LIBRARIES["incompetech"], "A") >>> rec.license_id, rec.requires_attribution, rec.commercial_ok, rec.rights_verified ('CC-BY-4.0', True, True, True) >>> rec = track_license(MUSIC_LIBRARIES["artlist"], "A") >>> rec.license_id, rec.commercial_ok, rec.rights_verified, rec.attribution_text ('unknown', False, False, None)
- Return type:
- foley.sources.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:
- foley.sources.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:
Modules
Acquire a music library's titles: verified files, one provenance row each, a resumable table. |
|
A free music library as a live retrieve source: titles in, licensed tracks out (#212). |
|
|
|
Which titles a video credits, by library: the credit-block parser and the titles file. |
|
Fetching a library's files politely, through foley's transport and its resilience layer. |
|
Music libraries as data: who made one, its licence, its credit, where a title's file is. |
|
Where else a track's bytes may be: the library's own server, then the Internet Archive. |
|
Checking a downloaded file is audio: an audio stream and a duration, read by foley's probes. |