File size: 3,271 Bytes
b3b6115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""TRCS Hugging Face Dataset Loader Utilities."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any, Dict, List, Optional

import datasets

PACKAGE_ROOT = Path(__file__).resolve().parent


def get_manifest_path(split: str = "telephone_grid") -> Path:
    """Return absolute path to dataset split manifest."""
    split_norm = split.lower().strip()
    if split_norm in ("telephone_grid", "e2"):
        p = PACKAGE_ROOT / "manifests" / "e2_telephone_grid.jsonl"
        if not p.exists():
            p = PACKAGE_ROOT / "data" / "telephone_grid" / "test.jsonl"
        return p
    elif split_norm in ("hallucination", "e1"):
        p = PACKAGE_ROOT / "manifests" / "e1_hallucination.jsonl"
        if not p.exists():
            p = PACKAGE_ROOT / "data" / "hallucination" / "test.jsonl"
        return p
    elif split_norm == "default":
        p = PACKAGE_ROOT / "data" / "default" / "test.jsonl"
        return p
    else:
        raise ValueError(f"Unknown split: {split}. Choose from ['telephone_grid', 'hallucination', 'default']")


def load_trcs_manifest(split: str = "telephone_grid") -> List[Dict[str, Any]]:
    """Load TRCS manifest records as a list of Python dictionaries."""
    m_path = get_manifest_path(split)
    if not m_path.exists():
        raise FileNotFoundError(f"Manifest not found: {m_path}")

    records = []
    with open(m_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rec = json.loads(line)
                # Resolve relative audio path to absolute
                if "audio_path" in rec:
                    p = Path(rec["audio_path"])
                    if not p.is_absolute():
                        rec["audio_path_abs"] = str(PACKAGE_ROOT / p)
                    else:
                        rec["audio_path_abs"] = str(p)
                records.append(rec)
    return records


def load_trcs_dataset(
    split: str = "telephone_grid",
    resolve_audio_paths: bool = True,
    as_audio: bool = False,
) -> datasets.Dataset:
    """Load TRCS dataset as a Hugging Face `datasets.Dataset` object.

    Args:
        split: Split name ('telephone_grid'/'e2', 'hallucination'/'e1', or 'default').
        resolve_audio_paths: If True, adds 'audio_path_abs' with absolute path to audio files.
        as_audio: If True, adds an 'audio' column cast to `datasets.Audio(sampling_rate=16000)`.
    """
    split_norm = split.lower().strip()
    config_name = "telephone_grid" if split_norm in ("telephone_grid", "e2") else ("hallucination" if split_norm in ("hallucination", "e1") else "default")
    ds = datasets.load_dataset(str(PACKAGE_ROOT), config_name, split="test", verification_mode="no_checks")

    if resolve_audio_paths or as_audio:
        def _add_abs(ex: Dict[str, Any]) -> Dict[str, Any]:
            rel_p = Path(ex["audio_path"])
            abs_p = str(rel_p if rel_p.is_absolute() else (PACKAGE_ROOT / rel_p))
            out = {"audio_path_abs": abs_p}
            if as_audio:
                out["audio"] = abs_p
            return out

        ds = ds.map(_add_abs)
        if as_audio:
            ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16000))

    return ds