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
|
Build a bulk-acquisition |
|
Registered adapters whose ring is in |
|
Register |
|
Return the ring of the registered corpus |
|
Resolve the adapters a bootstrap run should touch. |
|
Build an API-acquisition |
|
Search a live |
Scan |
|
|
Return the |
|
Return the names of registered live sources (runs discovery first). |
|
Register a live source directly (out-of-tree plugin or a test double). |
|
Build a generated |
|
Generate a sound via |
|
Wrap a stored |
Classes
|
One clip inside a local bulk corpus, described but not yet ingested. |
|
A downloaded bulk corpus presented as an ingestable stream of clips. |
|
A bulk corpus where every clip carries the same license. |
|
Ring-0 Clotho-eval adapter: per-clip Freesound licences; captions opt-in (NC). |
Ring-1 FSD50K adapter with per-clip Freesound license resolution. |
|
|
The live/HTTP source contract (report 10 §4.2): |
|
The generation source contract (report 10 §4.2) — a SIBLING of |
|
One freshly-generated sound: its transient bytes + a provisional candidate. |
Exceptions
|
Raised by |
|
Raised (fail-closed) by an edit ( |
|
Raised (fail-closed) when a generation prompt trips a #9b safety gate. |
|
A |
|
A |
- class foley.sources.ClipSpec(path, source_id, meta=dict())[source]#
Bases:
objectOne clip inside a local bulk corpus, described but not yet ingested.
- source_id#
The corpus-native id (e.g. an FSD50K
fname); used only for reporting/provenance — the storedSoundRecord.idis still the content hash minted by the ingest pipeline.- Type:
- 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:
- class foley.sources.ClothoEvalCorpus(name, ring, default_license_id, source, rights_verified=True, tag_hints_from_path=False, include_captions=False)[source]#
Bases:
UniformCorpusRing-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.
- class foley.sources.CorpusAdapter(*args, **kwargs)[source]#
Bases:
ProtocolA 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:
- exception foley.sources.EditRefusal(message, *, source_id, reason)[source]#
Bases:
GenerationErrorRaised (fail-closed) by an edit (
foley.edit(), orfoley.generate()with an edit backend andaudio=) 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. Itsreportis empty and itsstatusis'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:
objectRing-1 FSD50K adapter with per-clip Freesound license resolution.
- iter_clips(root)[source]#
Yield a clip per audio file, carrying its per-clip license metadata.
Each clip’s
metagets{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).
- class foley.sources.GenerateAdapter(*args, **kwargs)[source]#
Bases:
ProtocolThe 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
SourceAdapterrather than an extra method on it, so thatSourceAdapterstaysruntime_checkablefor 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 (viaSOURCE_CONFIG['param_map'], warning-and-dropping unsupported ones), builds the audio + a generatedLicenseRecord, and returns aGeneratedClip. Thefoley.sources.generate.generate()façade converges it on the sharedingest_onepipeline (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 (Nonewhen 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'], seebatch_limit(); #210):ntakes from one call, in order, each with its own licence (its own seed, where the backend reports or derives one). Theseedaffordance is the first take’s. Fewer clips than asked means the backend answered fewer samples.
- class foley.sources.GeneratedClip(audio_bytes, candidate, notes=list(), raw=None)[source]#
Bases:
objectOne freshly-generated sound: its transient bytes + a provisional candidate.
The return type of a
GenerateAdapter’sgenerate— 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 handsaudio_bytesto the one shared pipeline (by-value), exactly asfoley.sources.pull.add_from()does for a retrieved download.
Generation is retrieval’s
search -> Candidateanddownload -> bytesfused into one call, because there is no server to re-fetch the bytes from.Provisional/canonical split — on
candidate.soundonlylicense/caption/tagsare authoritative.id(a discarded"<source>:pending"placeholder),uri,content_sha256,storage_mode,qc,duration_s,sample_rate,channelsand theembedding_*fields are all minted downstream byingest_one()(the façade passessound_id=Noneso the stored id is the decoded-PCM content hash).audio_byteslives ONLY here and is never serialized — aSoundRecordholds auri, 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:
- candidate#
The report-10
Candidate(origin=CandidateOrigin.generated) carrying the authoritativeLicenseRecord(is_ai_generated=True+ the generation-provenance block) plus the prompt caption + seed tags.- Type:
- notes#
Generation-time messages (
on_unsupported_param='warn'drops, output-format fallbacks, …). Thefoley.sources.generate.generate()façade folds these into the storedIngestResult‘snotesso they surface in the run report.- Type:
- 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 transientraw; it is not kept in the generations cache, so a replayed clip has none.
- exception foley.sources.GenerationError(message, *, report, status, cache_key=None)[source]#
Bases:
RuntimeErrorRaised by
foley.generate()(andfoley.edit()) when a backend yields no stored sound.Carries the full
IngestReportand the terminalstatusso a caller can react distinctly toquarantined(QC-rejected — e.g. regenerate),rights_blocked, orerror. The lower-levelgenerate()workhorse never raises this — it always returns an inspectable report; only the publicfoley.generate()promise raises.- report#
The
IngestReportfrom the run.
- status#
The terminal
IngestResultstatus ('quarantined'|'rights_blocked'|'error'| …).
- cache_key#
The key the paid bytes were kept under in the generations cache (
foley.generations.get(cache_key)), orNonewhen 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 (storedCandidates, in order) before the one that failed;Noneotherwise (#161).foley.variations()sets it on any exception a take raises, not only this one.
- variations: Optional[list] = None#
The takes made before the failure, when raised from
foley.variations().
- exception foley.sources.RecognizableVoiceRefusal(message, *, hits, report)[source]#
Bases:
SafetyRefusalA
SafetyRefusalfor a prompt requesting a recognizable / cloned voice (report 07 §7.1).
- exception foley.sources.SafetyRefusal(message, *, hits, report)[source]#
Bases:
GenerationErrorRaised (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
errorresult (a backend/ingest failure the workhorse records without raising) — a safety refusal is a deliberate refusal of an unsafe request. Itsreportis an empty pre-generation report andstatusis'refused'. Carrieshits(the matched marks/patterns). Subclass ofGenerationErrorso the publicfoley.generate()Raisesclause already covers it. Seefoley.provenance.disclosure.scan_prompt().
- class foley.sources.SourceAdapter(*args, **kwargs)[source]#
Bases:
ProtocolThe live/HTTP source contract (report 10 §4.2):
search+get+download.A retrieve adapter (Freesound, #5) fetches existing sounds from a service:
searchreturns rankedCandidates,getresolves one id to aSoundRecord, anddownloadreturns the (transient, TOS-permitting) bytes to embed. It returns the SAMECandidate/SoundRecordshapes 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 samefoley.index.ingest.ingest_one()pipeline viafoley.sources.pull.add_from()(it wraps the corpus machinery, it does not fork it). Generation adapters (#6: Stable Audio Open, ElevenLabs) will add a siblinggeneratesurface; 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_okat the storage gate).- Return type:
- get(source_id)[source]#
Resolve one source id to a metadata
SoundRecord.- Return type:
- exception foley.sources.TrademarkRefusal(message, *, hits, report)[source]#
Bases:
SafetyRefusalA
SafetyRefusalfor 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:
objectA 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_verifiedis 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-clipmeta(seeClothoEvalCorpus).- corpus_dir(data_dir)[source]#
data_dir/<name>— the conventional on-disk root for this corpus.- Return type:
- iter_clips(root)[source]#
Yield one
ClipSpecper audio file underroot.When
tag_hints_from_pathis set, the clip’s parent folder names (relative toroot) are carried inmeta['tag_hints']— corpora like FoleySet encode a Foley taxonomy in their directory structure.
- 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
sourceand ingest its license-clean hits intolibrary.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 throughingest_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 inreport.notes;'raise'raises (seefoley.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’ssearchuntranslated (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(seefoley.base.QUERY_AFFORDANCES):duration_range,sort(relevance|newest|popular|duration),page,kind(sfx|music),sources,include_explicit,similar_to,ucs_category.
- Return type:
- Returns:
An
IngestReport— inspect.ingestedfor the stored records (eachstorage_mode == by_referencefor Freesound) and.summary()for counts, exactly likefoley.ingest().- Raises:
SearchArgumentError – A search argument the source refuses before any call (a
ValueError), e.g. apagepast its result window (Openverse serves ~240 results a query), or Freesound’skindanducs_categorynaming 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 HTTPSourceAdapters (Freesound, …). It exposes theoverridesseam so an adapter can flip an operational flag on top of the per-item copyright license without minting a newlicense_id— the Freesound case: keep the sound’s own CC id (CC0-1.0/CC-BY-4.0/ …) but passoverrides={'cache_bytes_ok': False}because the API TOS forbids caching the bytes even for CC0.redistribute_standalone_ok(copyright) andcache_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 ofLICENSE_FLAGS).rights_verified (
bool) –Trueonly for an authoritatively-recognized license (fail-closed gate input); MUST beTrueforfoley.keep()to admit the sound.overrides (
Optional[dict]) – Per-source flag overrides applied on top oflicense_id’s row (e.g.{'cache_bytes_ok': False}). Keys must beLicenseFlagsfields (validated byderive_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:
- Returns:
A populated
LicenseRecordwith 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 nooverrides(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 ofLICENSE_FLAGS, else it falls back to the all-Falseunknownflags).rights_verified (
bool) – Whether the license is authoritatively known (fail-closed gate input — passFalsefor 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:
- Returns:
A populated
LicenseRecordwith its derived flags applied.
- foley.sources.candidate_of(result)[source]#
Wrap a stored
IngestResultas a generated candidate.The report-10 §4.2 shape: retrieval and generation return the same
Candidate, differing only inorigin. Use on apass/warnresult (itsrecordis the canonical, storedSoundRecord).- Parameters:
result (
IngestResult) – A stored ingest result (result.recordis notNone).- Return type:
- Returns:
A
Candidatewithorigin=CandidateOrigin.generated.
- foley.sources.corpora_in_rings(rings)[source]#
Registered adapters whose ring is in
rings(sorted by name).- Return type:
- foley.sources.discover_sources()[source]#
Scan
foley.sourcessub-packages for aSOURCE_CONFIGand register them.A valid live source is a sub-package of
foley.sources(ispkgand not_-prefixed) whoseconfig.pydefines aSOURCE_CONFIGdict with aname(or aSOURCE_CONFIGSsequence of them: several sources sharing one adapter class, see_declared_configs()). Flat modules (bulk-corpus adaptershelpers) are skipped, so this never cross-captures the corpus adapters. Only
config.pyis 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:
- 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
backendand ingest it (by-value) intolibrary.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 sharedingest_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'raisesSafetyRefusal);on_flagged='warn'proceeds but stampspotential_trademark/contains_recognizable_voiceon the record sofoley.keep()drops it downstream.Watermark — with
foley[provenance]installed, the generated bytes are AudioSeal-watermarked before ingest (the stored bytes carry the mark), settinglicense.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.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 isgenerate_in_order(), which the publicfoley.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) – IfFalse, synthesize + enrich but do not add to the library (probe/QC/embed only — a preview; no content-credential sidecar). The result’saudio_bytescarries 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]) –Truerequire an AudioSeal watermark (error iffoley[provenance]absent),Falsenever 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. Seefoley.sources._dispatch.translate_affordances().reuse_cached (
bool) – Serve an identical paid request from the generations cache instead of paying again (defaultTrue; #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’snotesand the licence’stransformations; unrepairable faults (silence, NaN, too short, heavy clipping) still quarantine, with the reason noted.Falsequarantines as before; a callable withfoley.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, seefoley.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’stransformations.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 inqc['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 inqc['aesthetics']and the notes.TrueusesAudioboxAesthetics(its interpreter from$FOLEY_AES_PYTHON); a scorer instance (withfloors=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 (Truewithout 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 offoley.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 inqc['pam']and the notes, asaesthetics=does (#277):TrueusesPam(its interpreter from$FOLEY_PAM_PYTHON); an instance (withfloor=to flag a low score) is used as is. A record, never a quarantine;'unchecked'with the reason when it cannot run (Truewithout 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’sgeneration_params, and part of the generations-cache key; never seen by the unsupported-parameter policy. A key the source’sprovider_paramspolicy reserves or prices raisesValueErrorbefore any call, so the cost estimate is the call’s.variation (
int) – Which variation of the same request this is (#161; seefoley.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): variationsvariation .. variation + takes - 1. A backend with a batch knob (native_defaults['batch'], an adapter withgenerate_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). Default1.derived_from – For an edit (#162: an edit backend given
audio=), the source clip’sSoundRecord(whatfoley.edit()passes) or itsLicenseRecord. Required by theeditmode, 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 intransformations(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. ASoundRecordwith a known digest must be the bytes sent; aLicenseRecord(or a bare URL asaudio=) is the caller’s own, unchecked declaration of the clip’s rights, asingest(license=)is.**affordances – Unified generation affordances (
duration_s,model,prompt_influence,negative_prompt,steps,seed,loop,output_format,sample_rate,expand_prompt— seefoley.base.GENERATION_AFFORDANCES; and an edit’saudio,strength,inpaint_start_s/inpaint_end_s,extend_before_s/extend_after_s— seefoley.base.EDIT_AFFORDANCES).
- Return type:
- Returns:
An
IngestReport— inspect.ingestedfor the stored record (storage_mode == by_value) and.summary()for counts. A backend or ingest failure is recorded as a singleerrorresult, never raised (add_from-symmetric resilience). Every result of a paid call carriescache_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=Truebutfoley[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 fromlicense_idbyapply_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 viaallow_ai_training_forbiddenbut never flips the flag, sofoley.keep()still rejects the sound for anyIntendedUse(will_train=True)), and — forStability-Community—revenue_cap_usd=1_000_000(enforced byfoley.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 ofLICENSE_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 beTrueorfoley.keep()rejects the sound.generator_version (
Optional[str]) – Optional model/version string.generation_seed (
Optional[int]) – The reproducibility seed (anintfor a seeded Stable-Audio-Open run;Nonefor a non-deterministic backend).generation_params (
Optional[dict]) – The RESOLVED NATIVE params actually sent to the backend (e.g.guidance_scale— not the unifiedprompt_influence—audio_end_in_s, …), and where it ran when that decides the bytes (a local model’sdevice/dtype), for reproducibility + audit.disclosure_recommended (
bool) – EU AI Act Art. 50 hint (defaultTrue); makes the credits AI-disclosure line render immediately (#9a already reads it).watermark (
Optional[dict]) – Pass-through carrier for #9b (AudioSeal);Noneuntil then.c2pa_manifest_ref (
Optional[str]) – Pass-through carrier for #9b (C2PA);Noneuntil then.overrides (
Optional[dict]) – Optional per-source flag overrides (rare for generation).source_id (
Optional[str]) – Optional source-native id, for provenance.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.Falsefor procedural synthesis (a'procedural'source, #76): the record then hasis_ai_generated=Falseanddisclosure_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:
- Returns:
A populated
LicenseRecordwith derived flags applied ANDis_ai_generated=ai_generatedplus the full generation-provenance block.
- foley.sources.get_source(name)[source]#
Return the
{'config', 'adapter'}entry forname, lazily building the adapter.Runs a discovery pass if
nameis not yet known, then instantiates the adapter on first use (cached in the entry).- Parameters:
name (
str) – The source name.- Return type:
- 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 declaredconfig['data_egress']is in this set (the local-first / offline filter — seefoley.runtime.RuntimeConfig). A source that does not declaredata_egressis excluded (fail-closed).- Return type:
- foley.sources.register_corpus(adapter)[source]#
Register
adapterinCORPUS_REGISTRY(idempotent) and return it.- Raises:
ValueError – If a different adapter is already registered under the name.
- Return type:
- 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. IfadapterisNoneit is lazily built fromconfigon firstget_source()(the source must then be an importablefoley.sources.<name>package).- Parameters:
name (
str) – The source name (theadd_from()/get_source()key).config (
dict) – TheSOURCE_CONFIGdeclaration.adapter – An optional pre-instantiated adapter (bypasses lazy loading).
- Return type:
- foley.sources.ring_of(name)[source]#
Return the ring of the registered corpus
name(raisesKeyError).- Return type:
- foley.sources.select_corpora(*, rings=(0, 1), corpora=None)[source]#
Resolve the adapters a bootstrap run should touch.
An explicit
corporaallowlist (by name) wins overrings; otherwise every registered adapter in the given rings is selected. Ring 2 is never in the defaultrings— it is opt-in only.- Raises:
KeyError – If a name in
corporais not registered.- Return type:
Modules
The bulk-corpus source contract — a downloaded corpus as an ingestable stream. |
|
BBC RemArc (Rewind Archive) — a Ring-2, quarantined corpus. |
|
What each live source emits, and what foley plans to support: |
|
Clotho-eval — a captioned Ring-0 corpus that doubles as a retrieval fixture. |
|
Edits of a sound (#162): audio-to-audio, inpaint, extend — the parts an edit adds to generation. |
|
ElevenLabs Sound Effects generate source (hosted; #6). |
|
fal-hosted generate sources, executed through |
|
FoleySet — a CC-BY, Foley-native starter corpus (Ring 0). |
|
Freesound APIv2 retrieve source — CC0 sounds, stored by-reference ( |
|
FSD50K — the labeled, commercial-safe backbone corpus (Ring 1). |
|
Injectable HTTP transport for foley's live source adapters. |
|
Internet Archive retrieve source: keyless, opt-in, uploader-asserted licences ( |
|
Media inputs of generation (#74, #162, #215): what |
|
Acquire a licensed music library, with provenance: verified files, a tracks table, attribution. |
|
Openverse retrieve source: keyless, licence-rich audio search ( |
|
|
|
pyfxr procedural source: sfxr-family category presets, free, offline and seeded (#76). |
|
Live-source adapter registry: auto-discovery + lazy loading (arioso's registry, ported). |
|
Graceful degradation for HTTP source adapters — throttle · backoff · circuit-break (#12). |
|
Sonniss GameAudioGDC — a Ring-2, quarantined corpus. |
|
Stable Audio Open 1.0 generate source (local default; #6). |
|
Stable Audio 3 Small-SFX generate source (local, CPU, no GPU and no HF token; #72). |
|
Video inputs of generation (#74): a video's length, and the audio of a muxed video answer. |
|
Wikimedia Commons retrieve source: keyless, licence per file ( |