# foley.dataset

Bulk training-dataset synthesis over foley’s generators (#321).

`foley.generate` makes one sound at a time and files it in a retrieval library. A
training set wants the opposite: many clips from a grid of prompts, seeds and durations,
written to a plain directory with the audit trail a dataset needs, under a hard budget,
and re-runnable without paying twice:

```default
import foley.dataset as ds

spec = ds.DatasetSpec(
    prompts={"laser": ["laser zap", "laser blast"], "coin": ["coin pickup"]},
    seeds=range(5),
    backends=("pyfxr",),            # offline and free; a paid backend needs budget_usd
    budget_usd=0.0,
    per_class_seconds={"laser": 600},
)
report = ds.synthesize(spec, "~/datasets/sfx-v1")
```

`out_dir` then holds:

```default
audio/<class>/<request_id>.flac   one file per kept clip
manifest.jsonl                    one row per clip: request, QC, cost and the full LicenseRecord
terms/<backend>-<hash>.json       the backend's stated terms, as read when the run began
ATTRIBUTION.md                    credits for the clips whose licences require them
DATASHEET.md, report.json         what is in it, per-class seconds and synthetic share
```

Guarantees:

* **Fail-closed rights.** Every clip is checked with the licence gate against
  `spec.intended_use` (default: training use). A clip whose licence cannot serve it is
  recorded as `refused` with the reason and its audio is not written.
* **Hard budget.** The run is inside a [`foley.agent.policy.Budget`](foley.agent.policy.html.md#foley.agent.policy.Budget) of
  `budget_usd`; the first call the budget refuses ends the run (`stopped='budget'`),
  never a warning. A cost that is unknown counts as a refusal unless the budget approves it.
* **Resumable, idempotent.** A clip’s `request_id` is the hash of everything that
  determines it (class, prompt, backend, seed, duration, params). A second run skips every
  id already in the manifest whose file exists, so an interrupted run continues and
  paid clips are never bought twice.
* **No retrieval indexing.** Clips are made with `store=False`.

The generation call is the `generate_fn` seam (default [`foley.generate()`](foley.html.md#foley.generate)), so tests
and callers with another generator can inject theirs. Everything else here is stdlib.

### Functions

| [`synthesize`](#foley.dataset.synthesize)(spec, out_dir, \*[, generate_fn, ...])   | Write the dataset `spec` describes into `out_dir`; return a [`DatasetReport`](#foley.dataset.DatasetReport).   |
|------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
| [`request_id`](#foley.dataset.request_id)(\*\*request)                             | Content address of a clip request: the same request gives the same id.                                                        |

### Classes

| [`ClipRequest`](#foley.dataset.ClipRequest)(klass, prompt, backend[, seed, ...])   | One clip to make: a class label, a prompt, a backend, a seed and a duration.               |
|-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| [`DatasetSpec`](#foley.dataset.DatasetSpec)(prompts[, seeds, durations_s, ...])    | What to synthesize: a grid of `prompts` (by class) x `seeds` x `durations_s` x `backends`. |
| [`DatasetReport`](#foley.dataset.DatasetReport)(out_dir[, made, skipped_done, ...])  | What a run did.                                                                            |

### *class* foley.dataset.ClipRequest(klass, prompt, backend, seed=None, duration_s=None, params=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One clip to make: a class label, a prompt, a backend, a seed and a duration.

### *class* foley.dataset.DatasetReport(out_dir, made=0, skipped_done=0, refused=0, failed=0, spent_usd=0.0, stopped=None, seconds_by_class=dict(), synthetic_share=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a run did. `stopped` is `None` for a finished run, else why it stopped.

### *class* foley.dataset.DatasetSpec(prompts, seeds=(0,), durations_s=(None,), backends=('pyfxr',), budget_usd=1.0, per_class_seconds=dict(), real_seconds=dict(), intended_use=None, params=dict(), extra=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What to synthesize: a grid of `prompts` (by class) x `seeds` x `durations_s` x `backends`.

* **Parameters:**
  * **prompts** ([`Mapping`](https://docs.python.org/3/library/typing.html#typing.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]) – `{class: [prompt, ...]}`; the class is the label of the clips.
  * **seeds** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)[[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`int`](https://docs.python.org/3/builtins/functions.html#int)]]) – One clip per seed (a backend that takes no seed ignores it, with a note).
  * **durations_s** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)[[`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]) – Requested durations; `None` leaves the duration to the backend.
  * **backends** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]) – Registered generate sources. Each is a grid axis, so every backend makes
    its own clip of each (prompt, seed, duration); none is a fallback for another.
  * **budget_usd** ([`float`](https://docs.python.org/3/builtins/functions.html#float)) – Hard cap on the run’s spend (default `DFLT_BUDGET_USD`).
  * **per_class_seconds** ([`Mapping`](https://docs.python.org/3/library/typing.html#typing.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)]) – Stop making clips of a class once it holds this many seconds
    (counting clips from earlier runs). With `workers > 1` a class can overshoot
    by up to `workers - 1` clips.
  * **real_seconds** ([`Mapping`](https://docs.python.org/3/library/typing.html#typing.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`float`](https://docs.python.org/3/builtins/functions.html#float)]) – Seconds of real (non-synthetic) audio per class, only to report each
    class’s synthetic share.
  * **intended_use** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any)) – The [`foley.IntendedUse`](foley.html.md#foley.IntendedUse) every clip must satisfy; `None`
    means training use (`will_train=True`), so a generator whose licence
    forbids training is refused clip by clip.
  * **params** ([`Mapping`](https://docs.python.org/3/library/typing.html#typing.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Extra provider params, passed to every call (`provider_params`).
  * **extra** ([`Sequence`](https://docs.python.org/3/library/typing.html#typing.Sequence)[[`ClipRequest`](#foley.dataset.ClipRequest)]) – Any further [`ClipRequest`](#foley.dataset.ClipRequest) to add to the grid.

#### requests()

The grid, class by class (so a per-class target stops one class, not the run).

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/typing.html#typing.Iterator)[[`ClipRequest`](#foley.dataset.ClipRequest)]

### foley.dataset.request_id(\*\*request)

Content address of a clip request: the same request gives the same id.

```pycon
>>> a = request_id(klass="laser", prompt="zap", backend="pyfxr", seed=1, duration_s=None)
>>> a == request_id(duration_s=None, seed=1, backend="pyfxr", prompt="zap", klass="laser")
True
>>> a == request_id(klass="laser", prompt="zap", backend="pyfxr", seed=2, duration_s=None)
False
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### foley.dataset.synthesize(spec, out_dir, , generate_fn=None, workers=1, generate_kwargs=None)

Write the dataset `spec` describes into `out_dir`; return a [`DatasetReport`](#foley.dataset.DatasetReport).

* **Parameters:**
  * **spec** ([`DatasetSpec`](#foley.dataset.DatasetSpec)) – The [`DatasetSpec`](#foley.dataset.DatasetSpec).
  * **out_dir** – The dataset directory (created; an existing one is resumed).
  * **generate_fn** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]) – `generate_fn(prompt, *, backend, store=False, seed=..., ...)` returning
    a [`foley.Candidate`](foley.html.md#foley.Candidate) with `audio_bytes`; default [`foley.generate()`](foley.html.md#foley.generate).
  * **workers** ([`int`](https://docs.python.org/3/builtins/functions.html#int)) – Clips made at once (default 1).
  * **generate_kwargs** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`Mapping`](https://docs.python.org/3/library/typing.html#typing.Mapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]]) – Extra keyword arguments for every `generate_fn` call, e.g.
    `{'check_prompt': False}` to skip the CLAP prompt match (which needs the
    `foley[clap]` model) or `{'level': 'sfx_fg'}`.
* **Return type:**
  [`DatasetReport`](#foley.dataset.DatasetReport)
