foley.sources#

Bulk-corpus source adapters for foley’s SOURCE stage.

This package presents downloaded corpora (FSD50K, Clotho, FoleySet, and the opt-in Sonniss / BBC RemArc) as an ingestable stream of clips + per-clip licenses, consumed by foley.bootstrap.bootstrap(). Importing the package registers every adapter in CORPUS_REGISTRY.

Three adapter kinds share the one ingest pipeline: the narrow bulk-corpus CorpusAdapter (#4 — enumerate + license), the live retrieve SourceAdapter (#5 — Freesound, via add_from()), and the live generate GenerateAdapter (#6 — Stable Audio Open / ElevenLabs, via generate()). The retrieve + generate adapters are auto-discovered by foley.sources.registry and wrap the ingest machinery, never fork it.

Functions

bulk_license(*, source, license_id, ...[, ...])

Build a bulk-acquisition LicenseRecord, flags derived.

corpora_in_rings(rings)

Registered adapters whose ring is in rings (sorted by name).

register_corpus(adapter)

Register adapter in CORPUS_REGISTRY (idempotent) and return it.

ring_of(name)

Return the ring of the registered corpus name (raises KeyError).

select_corpora(*[, rings, corpora])

Resolve the adapters a bootstrap run should touch.

api_license(*, source, license_id, ...[, ...])

Build an API-acquisition LicenseRecord, flags derived.

add_from(source, *, query[, license, limit, ...])

Search a live source and ingest its license-clean hits into library.

discover_sources()

Scan foley.sources sub-packages for a SOURCE_CONFIG and register them.

get_source(name)

Return the {'config', 'adapter'} entry for name, lazily building the adapter.

list_sources(*[, egress_allow])

Return the names of registered live sources (runs discovery first).

register_source(name, config[, adapter])

Register a live source directly (out-of-tree plugin or a test double).

generated_license(*, source, license_id, ...)

Build a generated LicenseRecord, flags derived + provenance stamped.

generate(prompt, *[, backend, library, ...])

Generate a sound via backend and ingest it (by-value) into library.

candidate_of(result)

Wrap a stored IngestResult as a generated candidate.

Classes

ClipSpec(path, source_id[, meta])

One clip inside a local bulk corpus, described but not yet ingested.

CorpusAdapter(*args, **kwargs)

A downloaded bulk corpus presented as an ingestable stream of clips.

UniformCorpus(name, ring, ...[, ...])

A bulk corpus where every clip carries the same license.

ClothoEvalCorpus(name, ring, ...[, ...])

Ring-0 Clotho-eval adapter: per-clip Freesound licences; captions opt-in (NC).

Fsd50kCorpus()

Ring-1 FSD50K adapter with per-clip Freesound license resolution.

SourceAdapter(*args, **kwargs)

The live/HTTP source contract (report 10 §4.2): search + get + download.

GenerateAdapter(*args, **kwargs)

The generation source contract (report 10 §4.2) — a SIBLING of SourceAdapter.

GeneratedClip(audio_bytes, candidate[, ...])

One freshly-generated sound: its transient bytes + a provisional candidate.

Exceptions

GenerationError(message, *, report, status)

Raised by foley.generate() (and foley.edit()) when a backend yields no stored sound.

EditRefusal(message, *, source_id, reason)

Raised (fail-closed) by an edit (foley.edit(), or foley.generate() with an edit backend and audio=) before anything is paid for, when the source's rights do not allow an edit of it to be made and kept, or are not given.

SafetyRefusal(message, *, hits, report)

Raised (fail-closed) when a generation prompt trips a #9b safety gate.

TrademarkRefusal(message, *, hits, report)

A SafetyRefusal for a prompt naming a trademarked audio logo (report 07 §7.2).

RecognizableVoiceRefusal(message, *, hits, ...)

A SafetyRefusal for a prompt requesting a recognizable / cloned voice (report 07 §7.1).

class foley.sources.ClipSpec(path, source_id, meta=dict())[source]#

Bases: object

One clip inside a local bulk corpus, described but not yet ingested.

path#

Absolute path to the audio file on disk.

Type:

str

source_id#

The corpus-native id (e.g. an FSD50K fname); used only for reporting/provenance — the stored SoundRecord.id is still the content hash minted by the ingest pipeline.

Type:

str

meta#

Free-form per-clip metadata the adapter carries to CorpusAdapter.resolve_license() and (optionally) to caption/tag hints — e.g. {"license_id", "creator_name", "source_url", "caption", "tag_hints"}.

Type:

dict

class foley.sources.ClothoEvalCorpus(name, ring, default_license_id, source, rights_verified=True, tag_hints_from_path=False, include_captions=False)[source]#

Bases: UniformCorpus

Ring-0 Clotho-eval adapter: per-clip Freesound licences; captions opt-in (NC).

include_captions: bool = False#

Put the (non-commercial) human captions into the keyword index. Off by default.

iter_clips(root)[source]#

Yield clips carrying their per-file licence (and caption, when opted in).

Return type:

Iterator[ClipSpec]

resolve_license(spec)[source]#

The clip’s own licence from its metadata row (unknown when absent).

Return type:

LicenseRecord

class foley.sources.CorpusAdapter(*args, **kwargs)[source]#

Bases: Protocol

A downloaded bulk corpus presented as an ingestable stream of clips.

Implementations are plain objects (usually a small @dataclass) carrying three class-level facts (name / ring / default_license_id) and the two methods below. They perform no embedding, storage, or library access.

corpus_dir(data_dir)[source]#

The on-disk root for this corpus under data_dir (data_dir/name).

Return type:

str

default_license_id: str#

The corpus compilation license id (a per-clip license may still override).

iter_clips(root)[source]#

Yield a ClipSpec for every ingestable clip under root.

Return type:

Iterator[ClipSpec]

name: str#

Registry key / CLI name — 'fsd50k' | 'clotho' | 'foleyset' | …

resolve_license(spec)[source]#

Return the fully-derived rights record for spec (licensing SSOT).

Return type:

LicenseRecord

ring: int#

0 ship-in-repo, 1 fetch, 2 opt-in/quarantined.

Type:

Bootstrap ring

exception foley.sources.EditRefusal(message, *, source_id, reason)[source]#

Bases: GenerationError

Raised (fail-closed) by an edit (foley.edit(), or foley.generate() with an edit backend and audio=) before anything is paid for, when the source’s rights do not allow an edit of it to be made and kept, or are not given.

See foley.licensing.derivative_refusal(): unverified rights, bytes that may not be sent on, a licence that forbids modification, a share-alike licence (an edit’s own licence cannot carry it), or a licence foley has no row for. Its report is empty and its status is 'rights_blocked'.

source_id#

The id of the sound that was to be edited (None: not known).

reason#

Why it was refused.

class foley.sources.Fsd50kCorpus[source]#

Bases: object

Ring-1 FSD50K adapter with per-clip Freesound license resolution.

corpus_dir(data_dir)[source]#

data_dir/fsd50k — the conventional on-disk root.

Return type:

str

iter_clips(root)[source]#

Yield a clip per audio file, carrying its per-clip license metadata.

Each clip’s meta gets {license_id, rights_verified, creator_name, source_url} resolved from the FSD50K clips-info JSON (fail-closed when a clip is absent from the metadata).

Return type:

Iterator[ClipSpec]

resolve_license(spec)[source]#

Build the per-clip rights record from the metadata in spec.meta.

Return type:

LicenseRecord

class foley.sources.GenerateAdapter(*args, **kwargs)[source]#

Bases: Protocol

The generation source contract (report 10 §4.2) — a SIBLING of SourceAdapter.

A generate adapter (Stable Audio Open local, ElevenLabs Sound Effects hosted; #6) synthesizes a sound from a prompt. It is a deliberate sibling of the retrieve SourceAdapter rather than an extra method on it, so that SourceAdapter stays runtime_checkable for the retrieve trio (search / get / download) alone.

Like a retrieve adapter, a generate adapter performs no storage or library access: it maps foley’s unified GENERATION_AFFORDANCES (prompt, duration_s, model, prompt_influence, negative_prompt, steps, seed, loop, output_format) to its backend’s native params (via SOURCE_CONFIG['param_map'], warning-and-dropping unsupported ones), builds the audio + a generated LicenseRecord, and returns a GeneratedClip. The foley.sources.generate.generate() façade converges it on the shared ingest_one pipeline (by-value, operator-consented).

Optional: demuxer() -> Optional[Callable[[bytes], bytes]], for a backend that answers with a video (#176): the strategy that takes its audio out (None when the answer is already audio). The dispatch uses it again when it replays a kept video answer; without one, ffmpeg (foley.sources.video.audio_track()).

Optional: generate_takes(prompt, n, **affordances) -> list[GeneratedClip], for a backend whose config declares a batch knob (native_defaults['batch'], see batch_limit(); #210): n takes from one call, in order, each with its own licence (its own seed, where the backend reports or derives one). The seed affordance is the first take’s. Fewer clips than asked means the backend answered fewer samples.

generate(prompt, **affordances)[source]#

Synthesize a sound for prompt; return its bytes + provisional candidate.

Return type:

GeneratedClip

name: str#

Registry / façade key — 'stable_audio' | 'elevenlabs' | …

class foley.sources.GeneratedClip(audio_bytes, candidate, notes=list(), raw=None)[source]#

Bases: object

One freshly-generated sound: its transient bytes + a provisional candidate.

The return type of a GenerateAdapter’s generate — the envelope that reconciles report 10 §4.2 (generate -> Candidate: retrieval and generation return the same shape) with foley’s two non-negotiables:

  • adapters never touch storage — so the bytes ride with the candidate in an explicit field rather than being written anywhere, and

  • ``ingest_one`` is never forked — the foley.sources.generate.generate() façade hands audio_bytes to the one shared pipeline (by-value), exactly as foley.sources.pull.add_from() does for a retrieved download.

Generation is retrieval’s search -> Candidate and download -> bytes fused into one call, because there is no server to re-fetch the bytes from.

Provisional/canonical split — on candidate.sound only license / caption / tags are authoritative. id (a discarded "<source>:pending" placeholder), uri, content_sha256, storage_mode, qc, duration_s, sample_rate, channels and the embedding_* fields are all minted downstream by ingest_one() (the façade passes sound_id=None so the stored id is the decoded-PCM content hash). audio_bytes lives ONLY here and is never serialized — a SoundRecord holds a uri, never bytes.

audio_bytes#

The generated audio as encoded container bytes (WAV/FLAC/…), transient and in-memory only — consumed once by the ingest pipeline.

Type:

bytes

candidate#

The report-10 Candidate (origin=CandidateOrigin.generated) carrying the authoritative LicenseRecord (is_ai_generated=True + the generation-provenance block) plus the prompt caption + seed tags.

Type:

Candidate

notes#

Generation-time messages (on_unsupported_param='warn' drops, output-format fallbacks, …). The foley.sources.generate.generate() façade folds these into the stored IngestResult‘s notes so they surface in the run report.

Type:

list

raw#

What the provider returned besides the audio (#61), for a caller who needs a vendor field foley does not model (ElevenLabs: the status and response headers; fal: the response minus its audio payload), else None. The façade copies it onto the returned candidate’s transient raw; it is not kept in the generations cache, so a replayed clip has none.

Type:

Optional[dict]

exception foley.sources.GenerationError(message, *, report, status, cache_key=None)[source]#

Bases: RuntimeError

Raised by foley.generate() (and foley.edit()) when a backend yields no stored sound.

Carries the full IngestReport and the terminal status so a caller can react distinctly to quarantined (QC-rejected — e.g. regenerate), rights_blocked, or error. The lower-level generate() workhorse never raises this — it always returns an inspectable report; only the public foley.generate() promise raises.

report#

The IngestReport from the run.

status#

The terminal IngestResult status ('quarantined' | 'rights_blocked' | 'error' | …).

cache_key#

The key the paid bytes were kept under in the generations cache (foley.generations.get(cache_key)), or None when nothing was kept (a free backend, a refusal before synthesis, a failed cache write). A quarantined generation is retrievable: it was billed either way (#107).

variations#

Raised from foley.variations(), the takes already made (stored Candidates, in order) before the one that failed; None otherwise (#161). foley.variations() sets it on any exception a take raises, not only this one.

Type:

Optional[list]

variations: Optional[list] = None#

The takes made before the failure, when raised from foley.variations().

exception foley.sources.RecognizableVoiceRefusal(message, *, hits, report)[source]#

Bases: SafetyRefusal

A SafetyRefusal for a prompt requesting a recognizable / cloned voice (report 07 §7.1).

exception foley.sources.SafetyRefusal(message, *, hits, report)[source]#

Bases: GenerationError

Raised (fail-closed) when a generation prompt trips a #9b safety gate.

A pre-synthesis hard stop: nothing is generated or stored. Distinct from a resilience error result (a backend/ingest failure the workhorse records without raising) — a safety refusal is a deliberate refusal of an unsafe request. Its report is an empty pre-generation report and status is 'refused'. Carries hits (the matched marks/patterns). Subclass of GenerationError so the public foley.generate() Raises clause already covers it. See foley.provenance.disclosure.scan_prompt().

class foley.sources.SourceAdapter(*args, **kwargs)[source]#

Bases: Protocol

The live/HTTP source contract (report 10 §4.2): search + get + download.

A retrieve adapter (Freesound, #5) fetches existing sounds from a service: search returns ranked Candidates, get resolves one id to a SoundRecord, and download returns the (transient, TOS-permitting) bytes to embed. It returns the SAME Candidate / SoundRecord shapes as the retrieval index, so callers see one uniform interface whether audio is remote, cached, or local.

Distinct from (and complementary to) the narrow bulk-corpus CorpusAdapter: a live adapter does NOT re-implement enrichment or storage — it converges on the same foley.index.ingest.ingest_one() pipeline via foley.sources.pull.add_from() (it wraps the corpus machinery, it does not fork it). Generation adapters (#6: Stable Audio Open, ElevenLabs) will add a sibling generate surface; it is intentionally out of scope here so this Protocol stays runtime-checkable for retrieve adapters.

download(source_id)[source]#

Return a sound’s bytes (honoring cache_bytes_ok at the storage gate).

Return type:

bytes

get(source_id)[source]#

Resolve one source id to a metadata SoundRecord.

Return type:

SoundRecord

search(query, **kw)[source]#

Return ranked candidates for query (license filter pushed native).

Return type:

list[Candidate]

exception foley.sources.TrademarkRefusal(message, *, hits, report)[source]#

Bases: SafetyRefusal

A SafetyRefusal for a prompt naming a trademarked audio logo (report 07 §7.2).

class foley.sources.UniformCorpus(name, ring, default_license_id, source, rights_verified=True, tag_hints_from_path=False)[source]#

Bases: object

A bulk corpus where every clip carries the same license.

Covers FoleySet (CC-BY), Sonniss (Sonniss-GDC), BBC RemArc (RemArc) and any other single-license drop: it walks the audio tree and stamps one license. rights_verified is a constructor field so a corpus whose blanket license is authoritatively known passes the gate, while a merely-assumed one can stay fail-closed. Subclass to enrich per-clip meta (see ClothoEvalCorpus).

corpus_dir(data_dir)[source]#

data_dir/<name> — the conventional on-disk root for this corpus.

Return type:

str

iter_clips(root)[source]#

Yield one ClipSpec per audio file under root.

When tag_hints_from_path is set, the clip’s parent folder names (relative to root) are carried in meta['tag_hints'] — corpora like FoleySet encode a Foley taxonomy in their directory structure.

Return type:

Iterator[ClipSpec]

resolve_license(spec)[source]#

Stamp the corpus’s uniform license (derived via the licensing SSOT).

Return type:

LicenseRecord

foley.sources.add_from(source, *, query, license='source-default', limit=50, library=None, intended_use=None, adapter=None, on_unsupported=None, provider_params=None, **affordances)[source]#

Search a live source and ingest its license-clean hits into library.

Progressive disclosure: add_from("freesound", query="ocean waves") works out of the box (CC0-only, into the process-wide default library); every other knob is an optional keyword. Each hit is license-gated BEFORE any bytes are fetched (fail-closed), then routed through ingest_one(), which applies the by-reference storage gate from the sound’s own license.

Parameters:
  • source (str) – A registered live-source name (e.g. 'freesound').

  • query (Union[str, Sequence[str]]) – The natural-language search query (a music library also takes a list of titles).

  • license (Optional[str]) – License constraint pushed into the source query. Default: the source’s own (config['license']['search_default']), 'cc0' for a source that declares none; a music library (one licence) declares no narrowing. The per-item fail-closed guard enforces the source’s accepted-license allowlist regardless.

  • limit (int) – Max candidates to request from the source.

  • library – Target SoundLibrary (default: the process-wide default library).

  • intended_use (Optional[IntendedUse]) – The rights intent each candidate is gated against (default: DEFAULT_INTENDED_USE).

  • adapter – An optional pre-built adapter to use instead of the registry’s (the dependency-injection seam — a test passes a fake-transport adapter; production omits it and the registry lazily builds one).

  • on_unsupported (Optional[str]) – A search parameter the source cannot honour: None (default) drops it with a note in report.notes; 'raise' raises (see foley.sources._dispatch.translate_affordances()).

  • provider_params (Optional[dict]) – Native search params of the source that foley has no unified affordance for (#61), e.g. Freesound’s {"filter": "ac_brightness:[50 TO 100]"}. Passed to the adapter’s search untranslated (so the unsupported-parameter policy does not see them) and merged over its translated params; the licence filter and the fail-closed gate still apply.

  • **affordances – Extra unified affordances forwarded to the adapter’s search (see foley.base.QUERY_AFFORDANCES): duration_range, sort (relevance | newest | popular | duration), page, kind (sfx | music), sources, include_explicit, similar_to, ucs_category.

Return type:

IngestReport

Returns:

An IngestReport — inspect .ingested for the stored records (each storage_mode == by_reference for Freesound) and .summary() for counts, exactly like foley.ingest().

Raises:
  • SearchArgumentError – A search argument the source refuses before any call (a ValueError), e.g. a page past its result window (Openverse serves ~240 results a query), or Freesound’s kind and ucs_category naming two different top levels.

  • SourceConfigurationError – A missing key or optional dependency.

foley.sources.api_license(*, source, license_id, rights_verified, overrides=None, source_id=None, source_url=None, license_url=None, creator_name=None, attribution_text=None, terms=None)[source]#

Build an API-acquisition LicenseRecord, flags derived.

The live-source sibling of bulk_license() (acquisition_method=api), used by HTTP SourceAdapters (Freesound, …). It exposes the overrides seam so an adapter can flip an operational flag on top of the per-item copyright license without minting a new license_id — the Freesound case: keep the sound’s own CC id (CC0-1.0 / CC-BY-4.0 / …) but pass overrides={'cache_bytes_ok': False} because the API TOS forbids caching the bytes even for CC0. redistribute_standalone_ok (copyright) and cache_bytes_ok (TOS) are distinct; only the latter is flipped.

Parameters:
  • source (str) – Provenance source tag (e.g. 'freesound').

  • license_id (str) – The per-item normalized license id (a key of LICENSE_FLAGS).

  • rights_verified (bool) – True only for an authoritatively-recognized license (fail-closed gate input); MUST be True for foley.keep() to admit the sound.

  • overrides (Optional[dict]) – Per-source flag overrides applied on top of license_id’s row (e.g. {'cache_bytes_ok': False}). Keys must be LicenseFlags fields (validated by derive_license_flags()).

  • source_id (Optional[str]) – The source-native id (e.g. a Freesound numeric id), for provenance.

  • source_url (Optional[str]) – A human-resolvable URL for the item (attribution + the stable by-reference re-fetch handle).

  • license_url (Optional[str]) – The license URL/label exactly as the source served it.

  • creator_name (Optional[str]) – The uploader/creator (required for CC-BY attribution).

  • attribution_text (Optional[str]) – A ready-made attribution string, if supplied.

  • terms (Optional[Mapping]) – What the source states about its terms (source_stated_terms()).

Return type:

LicenseRecord

Returns:

A populated LicenseRecord with its derived flags (+ overrides) applied.

foley.sources.bulk_license(*, source, license_id, rights_verified, source_id=None, source_url=None, license_url=None, creator_name=None, attribution_text=None)[source]#

Build a bulk-acquisition LicenseRecord, flags derived.

The SSOT license builder every bulk-corpus adapter routes through (acquisition_method=bulk); a thin wrapper over _build_license(). Its signature has no overrides (a downloaded corpus is cacheable by-value).

Parameters:
  • source (str) – Provenance source tag (e.g. 'fsd50k', 'foleyset').

  • license_id (str) – The normalized license id (a key of LICENSE_FLAGS, else it falls back to the all-False unknown flags).

  • rights_verified (bool) – Whether the license is authoritatively known (fail-closed gate input — pass False for unrecognized/ambiguous licenses).

  • source_id (Optional[str]) – The corpus-native clip id, for provenance.

  • source_url (Optional[str]) – A human-resolvable URL for the clip (attribution/credits).

  • license_url (Optional[str]) – The licence URL/label exactly as the corpus served it (kept so the credit links the deed the clip was actually released under).

  • creator_name (Optional[str]) – The uploader/creator (required for CC-BY attribution).

  • attribution_text (Optional[str]) – A ready-made attribution string, if the corpus supplies one.

Return type:

LicenseRecord

Returns:

A populated LicenseRecord with its derived flags applied.

foley.sources.candidate_of(result)[source]#

Wrap a stored IngestResult as a generated candidate.

The report-10 §4.2 shape: retrieval and generation return the same Candidate, differing only in origin. Use on a pass / warn result (its record is the canonical, stored SoundRecord).

Parameters:

result (IngestResult) – A stored ingest result (result.record is not None).

Return type:

Candidate

Returns:

A Candidate with origin=CandidateOrigin.generated.

foley.sources.corpora_in_rings(rings)[source]#

Registered adapters whose ring is in rings (sorted by name).

Return type:

list[CorpusAdapter]

foley.sources.discover_sources()[source]#

Scan foley.sources sub-packages for a SOURCE_CONFIG and register them.

A valid live source is a sub-package of foley.sources (ispkg and not _-prefixed) whose config.py defines a SOURCE_CONFIG dict with a name (or a SOURCE_CONFIGS sequence of them: several sources sharing one adapter class, see _declared_configs()). Flat modules (bulk-corpus adapters

  • helpers) are skipped, so this never cross-captures the corpus adapters. Only config.py is imported here (stdlib-cheap); the adapter loads lazily in

get_source(). Idempotent: an already-registered name (e.g. a test double)

is never overwritten. A module whose SOURCE_CONFIGS() raises is skipped with a warning.

Return type:

list[str]

Returns:

The list of discovered source names.

Raises:

SourceNameCollision – If two modules declare the same source name (checked over every declaration before anything is registered, so the outcome does not depend on the order the packages are walked in).

foley.sources.generate(prompt, *, backend=None, library=None, store=True, adapter=None, watermark=None, on_flagged='refuse', watermarker=None, provenance_store=None, on_unsupported=None, reuse_cached=True, generations_cache=None, repair=True, level=None, check_prompt=True, aesthetics=None, pam=None, provider_params=None, variation=0, derived_from=None, takes=1, **affordances)[source]#

Generate a sound via backend and ingest it (by-value) into library.

Progressive disclosure: generate("a single wooden door creak") works out of the box (the local Stable Audio Open backend, into the process-wide default library); every other knob is an optional keyword. The generated bytes are routed through the shared ingest_one() pipeline (decode → QC → embed → tag → store), stored by-value with a content-hash id.

Disclosure/safety (#9b), all optional and degrading gracefully:

  • Safety gate — the prompt is scanned for trademarked audio logos + cloned voices before any synthesis spend (foley.provenance.disclosure.scan_prompt()). Fail-closed by default (on_flagged='refuse' raises SafetyRefusal); on_flagged='warn' proceeds but stamps potential_trademark / contains_recognizable_voice on the record so foley.keep() drops it downstream.

  • Watermark — with foley[provenance] installed, the generated bytes are AudioSeal-watermarked before ingest (the stored bytes carry the mark), setting license.watermark. Without the extra, generation proceeds unmarked (a note is recorded).

  • Content credential — a portable C2PA-shaped JSON sidecar recording the AI origin + license is written for every stored generation and referenced by license.c2pa_manifest_ref (stdlib; always on).

Parameters:
  • prompt (str) – The natural-language sound description.

  • backend (Optional[str]) –

    A registered generate-source name. None (default): default_generate_backend(), the first backend the generation order would try (a paid one only once paid generation is opted in), with **no fallback**: this workhorse runs one backend; the fallback through the order is generate_in_order(), which the public foley.generate() uses. Hosted: 'elevenlabs', and the fal endpoints 'fal_stable_audio_3' | 'fal_elevenlabs' | 'fal_sonilo' | 'fal_mmaudio' (foley[fal]

    • $FAL_KEY).

  • library – Target SoundLibrary (default: the process-wide default library).

  • store (bool) – If False, synthesize + enrich but do not add to the library (probe/QC/embed only — a preview; no content-credential sidecar). The result’s audio_bytes carries the clip, and an enrichment stage whose optional extra is absent (foley[clap]) is skipped with a note rather than failing after the paid call (#107).

  • adapter – An optional pre-built adapter (the dependency-injection seam — a test passes a fake-transport / fake-pipeline adapter; production omits it and the registry lazily builds one).

  • watermark (Optional[bool]) – True require an AudioSeal watermark (error if foley[provenance] absent), False never watermark, None (default, auto) watermark iff AudioSeal is installed.

  • on_flagged (str) – 'refuse' (default, fail-closed) raise on a safety-flagged prompt; 'warn' proceed and flag the record.

  • watermarker – An injected Watermarker (the DI seam; wins over auto-detect — tests pass a fake).

  • provenance_store – A MutableMapping[str, dict] for content-credential sidecars (default: foley.stores.make_provenance_store()).

  • on_unsupported (Optional[str]) – What to do with a parameter the backend cannot honour — 'raise' | 'warn' | 'note'; None (default) raises for a meaning-carrying one (seed, negative_prompt) and drops the rest with a note. See foley.sources._dispatch.translate_affordances().

  • reuse_cached (bool) – Serve an identical paid request from the generations cache instead of paying again (default True; #59).

  • generations_cache – A GenerationsCache (default: local).

  • repair – What to do with a generation QC would quarantine for a clipped run just over the gate (#107). True (default) applies the report’s own fixes (foley.repair.repair(): a 20 ms fade and a true-peak attenuation, which also clear the edge click and the over-ceiling peak such a clip carries), QCs the result again and ingests the repaired clip, recording the repair on the result’s notes and the licence’s transformations; unrepairable faults (silence, NaN, too short, heavy clipping) still quarantine, with the reason noted. False quarantines as before; a callable with foley.repair.repair()’s signature replaces the policy. A clip QC admits with a warning is stored as is. The repair runs before the watermark and the id, so the stored bytes, the content-hash id and the credential all describe the repaired clip; the generations cache keeps the bytes as received.

  • level – Level the clip to a loudness target before it is stored: a layer ('sfx_fg', 'ambience', … , its class target, see foley.level.class_target_lufs()) or a LUFS number. None (default) stores it at the level it was generated at (the WEAVE render applies the layer gains itself). Recorded in the licence’s transformations.

  • check_prompt (bool) – Score the clip against its prompt with the library’s text-audio embedder (foley.prompt_match.prompt_match()) and put the verdict in qc['prompt_match'] and the notes: a mismatch is flagged, not quarantined; without a capable embedder the verdict is 'unchecked'.

  • aesthetics – Score each stored clip with Audiobox Aesthetics (foley.eval.aesthetics.aesthetics_verdict()) and put CE / CU / PC / PQ in qc['aesthetics'] and the notes. True uses AudioboxAesthetics (its interpreter from $FOLEY_AES_PYTHON); a scorer instance (with floors= to flag a low axis) is used as is. A record, never a quarantine: a clip below a floor is stored and noted, and one that cannot be scored is 'unchecked' with the reason (True without an interpreter raises before anything is paid for). A duplicate of a stored clip scores that clip if it has no score yet. None (default) skips it: each scored clip, so each take of foley.variations(), runs the model in its own process (a 415 MB checkpoint loaded per take, seconds a clip).

  • pam – Score each stored clip with PAM (foley.eval.pam.Pam, the probability that “the sound is clear and clean.”, in [0, 1]) and put it in qc['pam'] and the notes, as aesthetics= does (#277): True uses Pam (its interpreter from $FOLEY_PAM_PYTHON); an instance (with floor= to flag a low score) is used as is. A record, never a quarantine; 'unchecked' with the reason when it cannot run (True without an interpreter raises before anything is paid for). No floor is calibrated for SFX (silence scores 0.35), so Tier-0 QC stays the gate. None (default) skips it: it loads a 690 MB model per clip.

  • provider_params (Optional[dict]) – Vendor-native params foley has no unified affordance for (#61), e.g. {"num_inference_steps": 50}. Merged by the backend over its translated native params (a provider param wins), recorded in the licence’s generation_params, and part of the generations-cache key; never seen by the unsupported-parameter policy. A key the source’s provider_params policy reserves or prices raises ValueError before any call, so the cost estimate is the call’s.

  • variation (int) – Which variation of the same request this is (#161; see foley.variations()): 0 (default) is the request itself, a later one is a different paid request in the generations cache.

  • takes (int) – How many takes of the request to make (#210; foley.variations() asks for several): variations variation .. variation + takes - 1. A backend with a batch knob (native_defaults['batch'], an adapter with generate_takes) makes up to its maximum in one call, priced and reserved for all of them before it is sent, each take keyed apart in the generations cache, QC’d and ingested on its own (one result per take, in order); any other makes one (the caller asks again for the rest). Default 1.

  • derived_from – For an edit (#162: an edit backend given audio=), the source clip’s SoundRecord (what foley.edit() passes) or its LicenseRecord. Required by the edit mode, which gates it fail-closed before anything is paid for (foley.sources.edit.edit_lineage(), EditRefusal): the edit is keyed by it, and the clip’s licence is narrowed to it, records it in transformations (and so in the credits and the content credential) before the repair, the level, the watermark and the credential. A byte-identical sound already in the library with wider rights is not handed back as the edit (rights_blocked). Refused for any other mode. A SoundRecord with a known digest must be the bytes sent; a LicenseRecord (or a bare URL as audio=) is the caller’s own, unchecked declaration of the clip’s rights, as ingest(license=) is.

  • **affordances – Unified generation affordances (duration_s, model, prompt_influence, negative_prompt, steps, seed, loop, output_format, sample_rate, expand_prompt — see foley.base.GENERATION_AFFORDANCES; and an edit’s audio, strength, inpaint_start_s / inpaint_end_s, extend_before_s / extend_after_s — see foley.base.EDIT_AFFORDANCES).

Return type:

IngestReport

Returns:

An IngestReport — inspect .ingested for the stored record (storage_mode == by_value) and .summary() for counts. A backend or ingest failure is recorded as a single error result, never raised (add_from-symmetric resilience). Every result of a paid call carries cache_key: where its bytes are in the generations cache.

Raises:
  • SafetyRefusal – If the prompt trips a safety gate and on_flagged='refuse'.

  • EditRefusal – For an edit without derived_from, or whose source’s rights do not allow it (before anything is paid for).

  • WatermarkUnavailable – If watermark=True but foley[provenance] is absent.

foley.sources.generated_license(*, source, license_id, generator_model, generation_prompt, rights_verified=True, generator_version=None, generation_seed=None, generation_params=None, generation_prompt_used=None, disclosure_recommended=True, watermark=None, c2pa_manifest_ref=None, overrides=None, source_id=None, source_url=None, license_url=None, creator_name=None, attribution_text=None, ai_generated=True, terms=None)[source]#

Build a generated LicenseRecord, flags derived + provenance stamped.

The generation sibling of bulk_license() / api_license() (acquisition_method=generated): it routes through the shared _build_license() core — so the eight permission flags are DERIVED from license_id by apply_license_flags(), never hand-set — and then stamps the generation-provenance block in exactly one place, so every generate adapter (Stable Audio Open, ElevenLabs, …) records provenance identically (open-closed).

The consequences flow automatically from the two generator rows in LICENSE_FLAGS: cache_bytes_ok=True (⇒ by-value storage), ai_training_ok=False (the record keeps this restriction — the generate façade consents to embed+persist via allow_ai_training_forbidden but never flips the flag, so foley.keep() still rejects the sound for any IntendedUse(will_train=True)), and — for Stability-Community — revenue_cap_usd=1_000_000 (enforced by foley.keep() at select time).

Parameters:
  • source (str) – The generator tag (e.g. 'stable_audio' / 'elevenlabs').

  • license_id (str) – The generator license id ('Stability-Community' / 'ElevenLabs-SFX' — a key of LICENSE_FLAGS).

  • generator_model (str) – The model identifier (e.g. 'stable-audio-open-1.0', 'eleven_text_to_sound_v2').

  • generation_prompt (str) – The user prompt, verbatim (the prompt sent).

  • generation_prompt_used (Optional[str]) – The prompt the backend reports it used, when it reports one (fal Stable Audio 3 echoes it; it differs when the backend rewrote it, expand_prompt=True).

  • rights_verified (bool) – True (a generator license is authoritatively known); MUST be True or foley.keep() rejects the sound.

  • generator_version (Optional[str]) – Optional model/version string.

  • generation_seed (Optional[int]) – The reproducibility seed (an int for a seeded Stable-Audio-Open run; None for a non-deterministic backend).

  • generation_params (Optional[dict]) – The RESOLVED NATIVE params actually sent to the backend (e.g. guidance_scale — not the unified prompt_influence — audio_end_in_s, …), and where it ran when that decides the bytes (a local model’s device / dtype), for reproducibility + audit.

  • disclosure_recommended (bool) – EU AI Act Art. 50 hint (default True); makes the credits AI-disclosure line render immediately (#9a already reads it).

  • watermark (Optional[dict]) – Pass-through carrier for #9b (AudioSeal); None until then.

  • c2pa_manifest_ref (Optional[str]) – Pass-through carrier for #9b (C2PA); None until then.

  • overrides (Optional[dict]) – Optional per-source flag overrides (rare for generation).

  • source_id (Optional[str]) – Optional source-native id, for provenance.

  • source_url (Optional[str]) – Optional human-resolvable URL.

  • license_url (Optional[str]) – Optional license URL/label.

  • creator_name (Optional[str]) – Optional creator (usually unset for generation).

  • attribution_text (Optional[str]) – Optional ready-made attribution string.

  • ai_generated (bool) – True (default) for a model’s output. False for procedural synthesis (a 'procedural' source, #76): the record then has is_ai_generated=False and disclosure_recommended=False (whatever was passed), and still carries the generation-provenance block.

  • terms (Optional[Mapping]) – What the source states about its terms (source_stated_terms(): the licence basis, whether the vendor reuses its output, API obligations, the vendor’s watermark statement).

Return type:

LicenseRecord

Returns:

A populated LicenseRecord with derived flags applied AND is_ai_generated=ai_generated plus the full generation-provenance block.

foley.sources.get_source(name)[source]#

Return the {'config', 'adapter'} entry for name, lazily building the adapter.

Runs a discovery pass if name is not yet known, then instantiates the adapter on first use (cached in the entry).

Parameters:

name (str) – The source name.

Return type:

dict

Returns:

The registry entry ({'config': dict, 'adapter': SourceAdapter, ...}).

Raises:
  • KeyError – If no such source is registered (after discovery).

  • EgressBlocked – If the source sends data off the device and an offline scope is active (foley.offline() / $FOLEY_OFFLINE).

foley.sources.list_sources(*, egress_allow=None)[source]#

Return the names of registered live sources (runs discovery first).

Parameters:

egress_allow (Optional[frozenset]) – If given, keep only sources whose declared config['data_egress'] is in this set (the local-first / offline filter — see foley.runtime.RuntimeConfig). A source that does not declare data_egress is excluded (fail-closed).

Return type:

list[str]

foley.sources.register_corpus(adapter)[source]#

Register adapter in CORPUS_REGISTRY (idempotent) and return it.

Raises:

ValueError – If a different adapter is already registered under the name.

Return type:

CorpusAdapter

foley.sources.register_source(name, config, adapter=None)[source]#

Register a live source directly (out-of-tree plugin or a test double).

Overwrites any existing entry for name — the seam a test uses to inject a fake-transport-backed adapter. If adapter is None it is lazily built from config on first get_source() (the source must then be an importable foley.sources.<name> package).

Parameters:
  • name (str) – The source name (the add_from() / get_source() key).

  • config (dict) – The SOURCE_CONFIG declaration.

  • adapter – An optional pre-instantiated adapter (bypasses lazy loading).

Return type:

None

foley.sources.ring_of(name)[source]#

Return the ring of the registered corpus name (raises KeyError).

Return type:

int

foley.sources.select_corpora(*, rings=(0, 1), corpora=None)[source]#

Resolve the adapters a bootstrap run should touch.

An explicit corpora allowlist (by name) wins over rings; otherwise every registered adapter in the given rings is selected. Ring 2 is never in the default rings — it is opt-in only.

Raises:

KeyError – If a name in corpora is not registered.

Return type:

list[CorpusAdapter]

Modules

base

The bulk-corpus source contract — a downloaded corpus as an ingestable stream.

bbc_remarc

BBC RemArc (Rewind Archive) — a Ring-2, quarantined corpus.

capabilities

What each live source emits, and what foley plans to support: list_backends + ledger.

clotho

Clotho-eval — a captioned Ring-0 corpus that doubles as a retrieval fixture.

edit

Edits of a sound (#162): audio-to-audio, inpaint, extend — the parts an edit adds to generation.

elevenlabs

ElevenLabs Sound Effects generate source (hosted; #6).

fal

fal-hosted generate sources, executed through falaw (#73).

foleyset

FoleySet — a CC-BY, Foley-native starter corpus (Ring 0).

freesound

Freesound APIv2 retrieve source — CC0 sounds, stored by-reference (foley[freesound]).

fsd50k

FSD50K — the labeled, commercial-safe backbone corpus (Ring 1).

http

Injectable HTTP transport for foley's live source adapters.

internet_archive

Internet Archive retrieve source: keyless, opt-in, uploader-asserted licences (foley[internet-archive]).

media

Media inputs of generation (#74, #162, #215): what video= and an edit's audio= may be, and their identity.

music_library

Acquire a licensed music library, with provenance: verified files, a tracks table, attribution.

openverse

Openverse retrieve source: keyless, licence-rich audio search (foley[openverse]).

pull

add_from — the live-source pull façade (SOURCE → INDEX in one call).

pyfxr

pyfxr procedural source: sfxr-family category presets, free, offline and seeded (#76).

registry

Live-source adapter registry: auto-discovery + lazy loading (arioso's registry, ported).

resilience

Graceful degradation for HTTP source adapters — throttle · backoff · circuit-break (#12).

sonniss

Sonniss GameAudioGDC — a Ring-2, quarantined corpus.

stable_audio

Stable Audio Open 1.0 generate source (local default; #6).

stable_audio_3

Stable Audio 3 Small-SFX generate source (local, CPU, no GPU and no HF token; #72).

video

Video inputs of generation (#74): a video's length, and the audio of a muxed video answer.

wikimedia_commons

Wikimedia Commons retrieve source: keyless, licence per file (foley[wikimedia-commons]).