Cem13's picture
Release Kodama Core with weights, runtime, attribution, and evaluation
c7893fa verified
Raw History Blame Contribute Delete
2.06 kB
"""Minimal Hugging Face Hub file access for the data pipeline.
We download individual files (parquet / jsonl / csv) with `hf_hub_download` instead of
`datasets.load_dataset`: it lets us fetch only the splits we need (keeps downloads small),
avoids the duplicate Arrow cache, and works for script-based repos through their
`refs/convert/parquet` branch. Files land in the default HF hub cache.
"""
from __future__ import annotations
import gzip
import io
import json
import zipfile
import pandas as pd
from huggingface_hub import hf_hub_download
def fetch(repo: str, filename: str, revision: str | None = None) -> str:
return hf_hub_download(repo, filename, repo_type="dataset", revision=revision)
def read_rows(repo: str, filename: str, revision: str | None = None, **kw) -> list[dict]:
"""Download one data file and return its rows as dicts."""
path = fetch(repo, filename, revision)
name = filename.lower()
if name.endswith(".parquet"):
df = pd.read_parquet(path)
elif name.endswith((".jsonl", ".jsonl.gz")) or (name.endswith(".json") and kw.pop("lines", True)):
opener = gzip.open if name.endswith(".gz") else open
with opener(path, "rt", encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
elif name.endswith(".csv"):
df = pd.read_csv(path, **kw)
elif name.endswith(".tsv"):
df = pd.read_csv(path, sep="\t", **kw)
else:
raise ValueError(f"unsupported file type: {filename}")
return df.to_dict("records")
def read_many(repo: str, filenames: list[str], revision: str | None = None, **kw) -> list[dict]:
rows: list[dict] = []
for fn in filenames:
rows.extend(read_rows(repo, fn, revision, **dict(kw)))
return rows
def read_zip_member(repo: str, filename: str, member: str, encoding: str = "latin-1") -> str:
path = fetch(repo, filename)
with zipfile.ZipFile(path) as z:
return z.read(member).decode(encoding)
__all__ = ["fetch", "read_rows", "read_many", "read_zip_member", "io"]