File size: 2,058 Bytes
c7893fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
"""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"]