Download code/pocket_math/io.py from Palaestra/pocket-math-ops: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/io.py
- Command line
-
hf download hf://datasets/Palaestra/pocket-math-ops/code/pocket_math/io.py
-
curl -L -o io.py https://huggingface.co/datasets/Palaestra/pocket-math-ops/resolve/main/code/pocket_math/io.py
2.13 kB
| """JSON Lines files, optionally gzipped, written atomically (temp file, then rename).""" | |
| from __future__ import annotations | |
| import gzip | |
| import hashlib | |
| import json | |
| import os | |
| from collections.abc import Iterable, Iterator | |
| from pathlib import Path | |
| from typing import Any | |
| def _open(path: Path, mode: str, gz: bool | None = None): | |
| if path.suffix == ".gz" if gz is None else gz: | |
| return gzip.open(path, mode + "t", encoding="utf-8") | |
| return open(path, mode, encoding="utf-8") | |
| def read_jsonl(path: str | os.PathLike) -> Iterator[dict[str, Any]]: | |
| with _open(Path(path), "r") as f: | |
| for line in f: | |
| if line.strip(): | |
| yield json.loads(line) | |
| def write_jsonl(path: str | os.PathLike, rows: Iterable[dict[str, Any]]) -> int: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_name(path.name + ".tmp") | |
| n = 0 | |
| with _open(tmp, "w", gz=path.suffix == ".gz") as f: | |
| for row in rows: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| n += 1 | |
| os.replace(tmp, path) | |
| return n | |
| def append_jsonl(path: str | os.PathLike, row: dict[str, Any]) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(path, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| def write_json(path: str | os.PathLike, obj: Any) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| tmp = path.with_name(path.name + ".tmp") | |
| tmp.write_text(json.dumps(obj, indent=2, ensure_ascii=False), encoding="utf-8") | |
| os.replace(tmp, path) | |
| def read_json(path: str | os.PathLike, default: Any = None) -> Any: | |
| path = Path(path) | |
| if not path.exists(): | |
| return default | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def sha256_file(path: str | os.PathLike) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as f: | |
| for block in iter(lambda: f.read(1 << 20), b""): | |
| h.update(block) | |
| return h.hexdigest() | |