File size: 1,596 Bytes
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""UTF-8 file-loading helpers for NovaGuide datasets."""

from __future__ import annotations

import csv
import json
from pathlib import Path
from typing import Any


def _existing_file(path: str) -> Path:
    """Resolve a file path and raise a clear error when it does not exist."""

    file_path = Path(path)
    if not file_path.is_file():
        raise FileNotFoundError(f"NovaGuide data file not found: {file_path}")
    return file_path


def load_json(path: str) -> Any:
    """Load and return a UTF-8 JSON document."""

    with _existing_file(path).open("r", encoding="utf-8") as handle:
        return json.load(handle)


def load_jsonl(path: str) -> list[dict[str, Any]]:
    """Load non-blank JSONL lines as dictionaries."""

    records: list[dict[str, Any]] = []
    with _existing_file(path).open("r", encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            if not line.strip():
                continue
            value = json.loads(line)
            if not isinstance(value, dict):
                raise ValueError(f"JSONL line {line_number} is not an object: {path}")
            records.append(value)
    return records


def load_csv_records(path: str) -> list[dict[str, str]]:
    """Load a UTF-8 CSV file as a list of row dictionaries."""

    with _existing_file(path).open("r", encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle))


def ensure_dir(path: str) -> None:
    """Create a directory and its parents when they do not exist."""

    Path(path).mkdir(parents=True, exist_ok=True)