"""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)