siavava commited on
Commit
84e4ea0
·
verified ·
1 Parent(s): e491622

(fix): read published shards from the hub when the checkout has lfs pointers

Browse files
Files changed (1) hide show
  1. src/ai_tech_articles/__init__.py +39 -1
src/ai_tech_articles/__init__.py CHANGED
@@ -57,6 +57,44 @@ def load_dotenv(path: Path | None = None) -> list[str]:
57
  return loaded
58
 
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def local_parquet_files() -> list[Path]:
61
  """The parquet shard(s) in ``data/``, if the repo is checked out."""
62
  return sorted(DATA_DIR.glob("train-*.parquet"))
@@ -73,7 +111,7 @@ def load_table(local_first: bool = True) -> pa.Table:
73
  if files:
74
  import pyarrow.parquet as pq
75
 
76
- return pa.concat_tables([pq.read_table(f) for f in files])
77
  from datasets import load_dataset
78
 
79
  return load_dataset(HF_REPO_ID, split="train").data.table
 
57
  return loaded
58
 
59
 
60
+ LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1"
61
+
62
+
63
+ def lfs_pointer(path: Path) -> dict[str, str] | None:
64
+ """The parsed pointer if `path` is a Git LFS pointer file, else None.
65
+
66
+ A checkout without LFS objects (GitHub Actions by default) leaves pointer
67
+ text where the parquet should be.
68
+ """
69
+ try:
70
+ with open(path, "rb") as fh:
71
+ head = fh.read(512)
72
+ except OSError:
73
+ return None
74
+ if not head.startswith(LFS_POINTER_PREFIX):
75
+ return None
76
+ fields = dict(line.split(" ", 1) for line in head.decode("utf-8", "replace").splitlines() if " " in line)
77
+ return fields
78
+
79
+
80
+ def shard_file(path: Path) -> Path:
81
+ """A readable parquet file for `path`: itself, or the Hub's copy when the
82
+ checkout only has the LFS pointer (verified against the pointer's sha256)."""
83
+ pointer = lfs_pointer(path)
84
+ if pointer is None:
85
+ return path
86
+ import hashlib
87
+
88
+ from huggingface_hub import hf_hub_download
89
+
90
+ local = Path(hf_hub_download(HF_REPO_ID, f"data/{path.name}", repo_type="dataset"))
91
+ want = pointer.get("oid", "").removeprefix("sha256:")
92
+ got = hashlib.sha256(local.read_bytes()).hexdigest()
93
+ if want and got != want:
94
+ raise RuntimeError(f"{path.name}: Hub copy sha256 {got} does not match the LFS pointer {want}")
95
+ return local
96
+
97
+
98
  def local_parquet_files() -> list[Path]:
99
  """The parquet shard(s) in ``data/``, if the repo is checked out."""
100
  return sorted(DATA_DIR.glob("train-*.parquet"))
 
111
  if files:
112
  import pyarrow.parquet as pq
113
 
114
+ return pa.concat_tables([pq.read_table(shard_file(f)) for f in files])
115
  from datasets import load_dataset
116
 
117
  return load_dataset(HF_REPO_ID, split="train").data.table