File size: 2,544 Bytes
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f66d08
 
 
 
fb6b9a8
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
"""Storage layout (same in the local mirror and in the private HF dataset repo).

raw/<family>/YYYY-MM-DD.parquet   one row per candidate repo per day; append-only, never
                                  edited. Daily downloads are derived at read time by
                                  differencing downloads_all_time between snapshots.
labels/<family>/latest.parquet    current classification (lineage, relation, evidence),
                                  versioned by classifier_version; recomputed freely.
cache/<family>/enrich.jsonl       per-repo file/header evidence keyed by repo sha, so
                                  unchanged repos are not probed again.
"""
import datetime as dt
import json
import os
from pathlib import Path

import pandas as pd

from .hub import api

DATASET_REPO = os.environ.get("HFECO_DATASET", "MiniMaxAI/oss-ecosystem-data")
LOCAL = Path(os.environ.get("HFECO_LOCAL", Path(__file__).resolve().parent.parent / "data"))

LIST_COLS = ["tags", "card_base_model", "hf_parents", "space_models", "sources"]


def write_raw(rows, fam_key, day=None):
    day = day or dt.datetime.now(dt.timezone.utc).date().isoformat()
    df = pd.DataFrame(rows)
    for c in LIST_COLS:
        df[c] = df[c].apply(lambda v: json.dumps(list(v or [])))
    p = LOCAL / "raw" / fam_key / f"{day}.parquet"
    p.parent.mkdir(parents=True, exist_ok=True)
    df.to_parquet(p, index=False)
    return p


def read_raw(fam_key, day=None):
    files = sorted((LOCAL / "raw" / fam_key).glob("*.parquet"))
    if day:
        files = [f for f in files if f.stem == day]
    df = pd.concat([pd.read_parquet(f).assign(day=f.stem) for f in files], ignore_index=True)
    for c in LIST_COLS:
        df[c] = df[c].apply(json.loads)
    # pandas 3 reads missing strings as NaN; the classifier expects None.
    for c in df.columns:
        if c not in LIST_COLS and not pd.api.types.is_numeric_dtype(df[c]):
            df[c] = df[c].astype(object).where(df[c].notna(), None)
    return df


def pull():
    """Mirror the dataset repo into LOCAL (used by the job and the Space)."""
    from huggingface_hub import snapshot_download
    snapshot_download(DATASET_REPO, repo_type="dataset", local_dir=LOCAL)


def push(paths, message):
    from huggingface_hub import CommitOperationAdd
    ops = [CommitOperationAdd(path_in_repo=str(Path(p).resolve().relative_to(LOCAL.resolve())),
                              path_or_fileobj=str(p)) for p in paths]
    api.create_commit(DATASET_REPO, ops, commit_message=message, repo_type="dataset")