// Whole-dataset export/import: a zip holding dataset.json (sample information and analysis // settings) plus one 32-bit float WAV per sample with the exact recorded samples. import type { AnalysisSettings } from "../analysis/analyze.ts"; import { decodeWav, encodeWavFloat32 } from "../audio/wav.ts"; import type { RecordingMeta } from "./db.ts"; import { readZip, writeZip, type ZipEntry } from "./zip.ts"; const FORMAT = "rip-sound-analyzer-dataset"; const VERSION = 1; interface DatasetJson { format: string; version: number; exportedAt: string; settings: AnalysisSettings; samples: (RecordingMeta & { audioFile: string })[]; } export async function exportDataset( recs: RecordingMeta[], settings: AnalysisSettings, getAudio: (id: string) => Promise, ): Promise { const entries: ZipEntry[] = []; const samples: DatasetJson["samples"] = []; for (const [i, m] of recs.entries()) { const audioFile = `audio/${String(i + 1).padStart(3, "0")}_${m.id}.wav`; const x = await getAudio(m.id); entries.push({ name: audioFile, data: new Uint8Array(await encodeWavFloat32(x, m.sampleRate).arrayBuffer()) }); samples.push({ ...m, audioFile }); } const json: DatasetJson = { format: FORMAT, version: VERSION, exportedAt: new Date().toISOString(), settings, samples }; entries.unshift({ name: "dataset.json", data: new TextEncoder().encode(JSON.stringify(json, null, 2)) }); return writeZip(entries); } export interface ImportedDataset { settings: AnalysisSettings | null; samples: { meta: RecordingMeta; audio: Float32Array }[]; exportedAt: string; } export async function readDataset(file: File): Promise { const files = readZip(await file.arrayBuffer()); const raw = files.get("dataset.json"); if (!raw) throw new Error("This zip has no dataset.json, so it is not a dataset exported by this app."); const json = JSON.parse(new TextDecoder().decode(raw)) as DatasetJson; if (json.format !== FORMAT) throw new Error("dataset.json is not a Rip Sound Analyzer dataset."); if (json.version > VERSION) throw new Error("This dataset was written by a newer version of the app."); const samples: ImportedDataset["samples"] = []; for (const s of json.samples) { const wavBytes = files.get(s.audioFile); if (!wavBytes) throw new Error(`Missing audio file ${s.audioFile}.`); const d = decodeWav(wavBytes.slice().buffer); if (!d) throw new Error(`Could not read ${s.audioFile}.`); if (d.sampleRate !== s.sampleRate || d.samples.length !== s.length) throw new Error(`${s.audioFile} does not match its description.`); const { audioFile: _unused, ...meta } = s; void _unused; samples.push({ meta, audio: d.samples }); } return { settings: json.settings ?? null, samples, exportedAt: json.exportedAt }; }