"""Importer for consented Buddi/Gulf child speech collected outside Abjad-Kids.""" from __future__ import annotations import csv from pathlib import Path from typing import Any from buddi_asr.data.abjad import ( _manifest_audio_value, _materialize, _wav_duration, pseudonymize, ) from buddi_asr.data.manifest import ManifestRecord, write_manifest from buddi_asr.errors import ManifestError REQUIRED_COLUMNS = {"audio", "text", "speaker_key", "language", "consent_basis"} ALLOWED_CONSENT_BASES = {"verified_parental_consent", "public_research_license"} SAFE_OPTIONAL_COLUMNS = { "age_group", "category", "device", "dialect", "gender_optional", "license", "noise_level", "split", } def import_local_csv( input_csv: str | Path, output_manifest: str | Path, *, processed_audio_dir: str | Path, salt: str, source_name: str = "buddi_consent_collection", audio_mode: str = "hardlink", ) -> dict[str, Any]: """Import a private CSV while stripping direct identity from the output.""" csv_path = Path(input_csv).resolve() manifest_path = Path(output_manifest).resolve() processed_root = Path(processed_audio_dir).resolve() if not csv_path.is_file(): raise ManifestError(f"Input CSV not found: {csv_path}") records: list[ManifestRecord] = [] seen_files: set[str] = set() with csv_path.open(encoding="utf-8-sig", newline="") as handle: reader = csv.DictReader(handle) fields = set(reader.fieldnames or []) missing = REQUIRED_COLUMNS - fields if missing: raise ManifestError("Input CSV is missing columns: " + ", ".join(sorted(missing))) unsafe_extra = fields - REQUIRED_COLUMNS - SAFE_OPTIONAL_COLUMNS if unsafe_extra: raise ManifestError( "Unrecognized columns are blocked to prevent accidental PII export: " + ", ".join(sorted(unsafe_extra)) ) for line_number, row in enumerate(reader, start=2): consent_basis = row["consent_basis"].strip() if consent_basis not in ALLOWED_CONSENT_BASES: raise ManifestError( f"{csv_path}:{line_number}: consent_basis must be one of " + ", ".join(sorted(ALLOWED_CONSENT_BASES)) ) relative_audio = row["audio"].strip() source_audio = (csv_path.parent / relative_audio).resolve() if not source_audio.is_file(): raise ManifestError(f"{csv_path}:{line_number}: audio not found: {source_audio}") source_file_id = pseudonymize(relative_audio, salt, namespace="file") if source_file_id in seen_files: raise ManifestError(f"{csv_path}:{line_number}: duplicate audio row") seen_files.add(source_file_id) opaque_name = source_file_id.removeprefix("file_") + source_audio.suffix.lower() final_audio = processed_root / opaque_name[:2] / opaque_name _materialize(source_audio, final_audio, audio_mode) speaker_id = pseudonymize(row["speaker_key"].strip(), salt, namespace="speaker") metadata = { "consent_basis": consent_basis, "source_file_id": source_file_id, } for key in ("device", "gender_optional", "noise_level"): value = row.get(key, "").strip() if value: metadata[key] = value record = ManifestRecord( audio=_manifest_audio_value(final_audio, manifest_path), text=row["text"].strip(), language=row["language"].strip(), dialect=row.get("dialect", "").strip() or "unknown", age_group=row.get("age_group", "").strip() or "unknown", speaker_id=speaker_id, source=source_name, category=row.get("category", "").strip() or "conversation", license=row.get("license", "").strip() or "private-consented", duration_sec=_wav_duration(source_audio), split=row.get("split", "").strip() or None, metadata=metadata, ) record.validate() records.append(record) write_manifest(records, manifest_path) return { "manifest": str(manifest_path), "records": len(records), "speakers": len({record.speaker_id for record in records}), "source": source_name, "direct_identity_exported": False, }