> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# src/hosting/publish_hf.py

> Publish the project on Hugging Face (decision 0010): a dataset, a model and the dashboard.

`src/hosting/publish_hf.py` · chapter [The dashboard and publishing](https://calendar-effects.mintlify.site/tour/09-dashboards-and-publishing.md), file 14 · 210 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py)

## What it does

Publish the project on Hugging Face (decision 0010): a dataset, a model and the dashboard.

Three repos in the team's Hugging Face organisation (common.settings.HF\_OWNER, HF\_REPOS):
dataset  calendar-effects/calendar-effects   our derived tables (no prices), results and config registries
model    calendar-effects/big-move-model     the Spark MLlib PipelineModel, its scores and charts
space    calendar-effects/dashboard          a free static page that embeds the hosted dashboard

Nothing is uploaded unless you pass --upload. Without it the script builds the three folders in
data/publish/ and lists every file that would go up, so you can open them and check first.

```bash theme={null}
python3 src/hosting/snapshot.py               # the page's data (needs a full run_everything.sh first)
python3 src/hosting/publish_hf.py             # build the folders and list them; uploads nothing
hf auth login                                 # once, with a write token from huggingface.co/settings/tokens
python3 src/hosting/publish_hf.py --upload    # create the repos (public) and upload
```

You must be a member of the organisation with write access. Options: --owner NAME (another account
or organisation), --private (create new repos as private, to look before making them public).

## What is inside

* **`NAMES`** · [line 41](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L41)
* **`CONFIG_FILES`** · [line 42](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L42)
* **`MODEL_CHARTS`** · [line 43](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L43)
* **`REPLACE`** · [line 45](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L45): What each upload replaces, so files dropped from a folder also disappear from the repo.
* **`by_split(df)`** · [line 50](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L50): The big-move model's time split (decision 0007), by the row's year.
* **`render(template, values)`** · [line 57](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L57): A card template with its \{placeholders} filled in (an unknown one raises KeyError).
* **`pct(v, digits)`** · [line 62](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L62)
* **`share(v, digits)`** · [line 66](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L66)
* **`card_values(owner)`** · [line 70](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L70): Every number the three cards show, read from the run's outputs.
* **`stage_dataset(values)`** · [line 110](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L110)
* **`stage_model(values)`** · [line 141](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L141)
* **`stage_space(values)`** · [line 156](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L156): The Space is a page that embeds the hosted dashboard (decision 0013).
* **`listing(folder)`** · [line 165](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L165)
* **`main()`** · [line 170](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/hosting/publish_hf.py#L170)

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts), [`src/common/settings.py`](https://calendar-effects.mintlify.site/reference/src/common/settings), [`src/common/study.py`](https://calendar-effects.mintlify.site/reference/src/common/study), [`src/eventstudy/car.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/car), [`src/eventstudy/charts.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/charts), [`src/eventstudy/stats.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/stats), [`src/hosting/live.py`](https://calendar-effects.mintlify.site/reference/src/hosting/live), [`src/hosting/snapshot.py`](https://calendar-effects.mintlify.site/reference/src/hosting/snapshot)

**Used by:** [`tests/test_hosting.py`](https://calendar-effects.mintlify.site/reference/tests/test_hosting)

## Source

```python title="src/hosting/publish_hf.py" lines expandable theme={null}
"""Publish the project on Hugging Face (decision 0010): a dataset, a model and the dashboard.

Three repos in the team's Hugging Face organisation (common.settings.HF_OWNER, HF_REPOS):
  dataset  calendar-effects/calendar-effects   our derived tables (no prices), results and config registries
  model    calendar-effects/big-move-model     the Spark MLlib PipelineModel, its scores and charts
  space    calendar-effects/dashboard          a free static page that embeds the hosted dashboard

Nothing is uploaded unless you pass --upload. Without it the script builds the three folders in
data/publish/ and lists every file that would go up, so you can open them and check first.

    python3 src/hosting/snapshot.py               # the page's data (needs a full run_everything.sh first)
    python3 src/hosting/publish_hf.py             # build the folders and list them; uploads nothing
    hf auth login                                 # once, with a write token from huggingface.co/settings/tokens
    python3 src/hosting/publish_hf.py --upload    # create the repos (public) and upload

You must be a member of the organisation with write access. Options: --owner NAME (another account
or organisation), --private (create new repos as private, to look before making them public).
"""
from __future__ import annotations

import argparse
import json
import shutil
from datetime import datetime, timezone

import pandas as pd

from common.contracts import load_event_types, load_retailers
from common.settings import (BIG_MOVE_MODEL, BIG_MOVE_MODEL_INFO, CARDS_DIR, CONFIG_DIR, DASHBOARD_URL,
                             DOCS_DIR, DOCS_URL, HF_OWNER, HF_REPOS, PUBLISH_DIR, RESULTS_DIR, SITE_DIR)
from common.study import (ABNORMAL_RETURN_Z, ATTENTION_BASELINE_DAYS, ATTENTION_SPIKE_Z, ESTIMATION_DAYS,
                          ESTIMATION_GAP_DAYS, MARKET_TICKER, ML_TEST_START_YEAR, ML_TRAIN_END_YEAR,
                          ML_VALIDATION_YEAR, STUDY_END_YEAR, STUDY_START_YEAR)
from eventstudy.car import OUTPUT as CARS
from eventstudy.car import code_version
from eventstudy.charts import CHARTS_DIR, short
from eventstudy.stats import ALL, SUMMARY, TREND
from hosting.live import NOT_PUBLISHED, public  # noqa: F401  (NOT_PUBLISHED: tests import it from here)
from hosting.snapshot import TEST_PREDICTIONS, read_stream

NAMES = {kind: HF_REPOS[kind] for kind in ("dataset", "model", "space")}
CONFIG_FILES = ["retailers.csv", "event_types.csv", "event_dates.csv", "wiki_articles.csv"]
MODEL_CHARTS = ["ml_roc_pr.png", "ml_feature_importance.png"]
# What each upload replaces, so files dropped from a folder also disappear from the repo.
REPLACE = {"dataset": ["data/**", "results/**", "config/**", "README.md"],  # not-config: folders inside the HF repo
           "model": ["big_move/**", "*.csv", "*.png", "*.json", "README.md"],
           "space": ["*.html", "*.js", "*.css", "data/**", "README.md"]}  # not-config: folders inside the HF repo


def by_split(df: pd.DataFrame) -> dict[str, pd.DataFrame]:
    """The big-move model's time split (decision 0007), by the row's year."""
    year = pd.to_datetime(df["date"]).dt.year
    return {"train": df[year <= ML_TRAIN_END_YEAR], "validation": df[year == ML_VALIDATION_YEAR],
            "test": df[year >= ML_TEST_START_YEAR]}


def render(template: str, values: dict) -> str:
    """A card template with its {placeholders} filled in (an unknown one raises KeyError)."""
    return (CARDS_DIR / template).read_text().format_map(values)


def pct(v, digits=1) -> str:
    return f"{v:+.{digits}%}"


def share(v, digits=1) -> str:
    return f"{v:.{digits}%}"


def card_values(owner: str) -> dict:
    """Every number the three cards show, read from the run's outputs."""
    retailers = load_retailers(in_scope_only=True)
    info = json.loads(BIG_MOVE_MODEL_INFO.read_text())
    test, metrics = info["test"], pd.read_csv(RESULTS_DIR / "ml_metrics.csv")
    summary = pd.read_csv(SUMMARY)
    store = summary[(summary["event_type"] == ALL) & (summary["group"] == "store")].iloc[0]
    events = [short(e["name"]) for e in load_event_types(in_scope_only=True)]
    importance = pd.read_csv(RESULTS_DIR / "ml_feature_importance.csv").sort_values("importance", ascending=False)
    shown = metrics[metrics["split"] == "test"]
    import pyspark

    return {
        "dataset_repo": f"{owner}/{NAMES['dataset']}", "model_repo": f"{owner}/{NAMES['model']}",
        "space_repo": f"{owner}/{NAMES['space']}",
        "n_retailers": len(retailers),
        "n_online": sum(r["retailer_type"] == "online" for r in retailers),
        "n_store": sum(r["retailer_type"] == "store" for r in retailers),
        "first_year": STUDY_START_YEAR, "last_year": STUDY_END_YEAR, "forecast_year": STUDY_END_YEAR + 1,
        "event_names": ", ".join(events[:-1]) + " and " + events[-1],
        "estimation_days": ESTIMATION_DAYS, "gap_days": ESTIMATION_GAP_DAYS, "market": MARKET_TICKER,
        "attention_days": ATTENTION_BASELINE_DAYS, "abnormal_z": ABNORMAL_RETURN_Z, "spike_z": ATTENTION_SPIKE_Z,
        "alert_share": share(info["alert_top_share"], 0), "alert_cutoff": f"{info['alert_cutoff']:.3f}",
        "store_all_car": pct(store["mean_car"]), "store_all_p": f"{store['p_clustered']:.3f}",
        "auc_roc": f"{test['auc_roc']:.2f}", "precision_top": share(test["precision_top"]),
        "base_rate": share(test["base_rate"]), "lift_top": f"{test['lift_top']:.1f}×",
        "test_years": "{}–{}".format(*info["test_years"]), "fit_years": "{}–{}".format(*info["fit_years"]),
        "fit_years_train": f"{STUDY_START_YEAR}–{ML_TRAIN_END_YEAR}", "validation_year": ML_VALIDATION_YEAR,
        "params": ", ".join(f"{k}={v}" for k, v in info["params"].items()),
        "features": ", ".join(f"`{f}`" for f in info["features"]), "n_features": len(info["features"]),
        "spark_version": pyspark.__version__,
        "metrics_table": "\n".join(
            f"| {r.model} | {r.features} | {r.split} | {r.auc_roc:.3f} | {r.auc_pr:.3f} | {r.precision_top:.1%} | {r.lift_top:.1f}× |"
            for r in shown.itertuples()),
        "importance_table": "\n".join(f"| `{r.feature}` | {r.importance:.3f} |" for r in importance.itertuples()),
        "built": datetime.now(timezone.utc).strftime("%Y-%m-%d"), "code_version": code_version(),
        "dashboard_url": DASHBOARD_URL, "docs_url": DOCS_URL,
    }


def stage_dataset(values: dict):
    out = PUBLISH_DIR / "dataset"
    shutil.rmtree(out, ignore_errors=True)
    (out / "data").mkdir(parents=True)
    (out / CONFIG_DIR.name).mkdir()
    signals = public(read_stream("stream_signals")).sort_values(["ticker", "date"])
    predictions = public(read_stream("stream_predictions")).sort_values(["ticker", "date"])
    for name, df in (("daily_signals", signals), ("big_move_predictions", predictions)):
        (out / "data" / name).mkdir()
        for split, part in by_split(df).items():
            part.to_parquet(out / "data" / name / f"{split}.parquet", index=False)
    # Every table as Parquet: the dataset viewer reads all of a repository's tables with one reader,
    # so a CSV among Parquet files shows as an error there.
    tables = {"event_windows.parquet": pd.read_parquet(CARS),
              "ml_test_predictions.parquet": pd.read_parquet(TEST_PREDICTIONS),
              "event_summary.parquet": pd.read_csv(SUMMARY), "event_trend.parquet": pd.read_csv(TREND)}
    for name, df in tables.items():
        df.to_parquet(out / "data" / name, index=False)
    results = DOCS_DIR / "results"
    if (results / "README.md").exists():
        shutil.copytree(results, out / "results")
    for name in CONFIG_FILES:
        shutil.copy(CONFIG_DIR / name, out / CONFIG_DIR.name / name)
    counts = {"n_signals": len(signals), "n_windows": len(tables["event_windows.parquet"]),
              "n_predictions": len(predictions), "n_test": len(tables["ml_test_predictions.parquet"]),
              "n_summary": len(tables["event_summary.parquet"]), "n_trend": len(tables["event_trend.parquet"])}
    values.update({k: f"{v:,}" for k, v in counts.items()})
    (out / "README.md").write_text(render("dataset.md", values))
    return out


def stage_model(values: dict):
    out = PUBLISH_DIR / "model"
    shutil.rmtree(out, ignore_errors=True)
    out.mkdir(parents=True)
    shutil.copytree(BIG_MOVE_MODEL, out / BIG_MOVE_MODEL.name, ignore=shutil.ignore_patterns(".*.crc"))
    shutil.copy(BIG_MOVE_MODEL_INFO, out / BIG_MOVE_MODEL_INFO.name)
    for name in ["ml_metrics.csv", "ml_feature_importance.csv"]:
        shutil.copy(RESULTS_DIR / name, out / name)
    for name in MODEL_CHARTS:
        if (CHARTS_DIR / name).exists():
            shutil.copy(CHARTS_DIR / name, out / name)
    (out / "README.md").write_text(render("model.md", values))
    return out


def stage_space(values: dict):
    """The Space is a page that embeds the hosted dashboard (decision 0013)."""
    out = PUBLISH_DIR / "space"
    shutil.rmtree(out, ignore_errors=True)
    shutil.copytree(SITE_DIR, out)
    (out / "README.md").write_text(render("space.md", values))
    return out


def listing(folder) -> list[str]:
    files = sorted(p for p in folder.rglob("*") if p.is_file())
    return [f"  {p.relative_to(folder)}  ({p.stat().st_size / 1e6:.2f} MB)" for p in files]


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--upload", action="store_true", help="create the repos and upload (default: only build and list)")
    parser.add_argument("--owner", default=HF_OWNER, help="Hugging Face account or organisation (default: the team's)")
    parser.add_argument("--private", action="store_true", help="create new repos as private")
    parser.add_argument("--only", choices=list(NAMES), help="upload only this one (all three are still built)")
    args = parser.parse_args()

    from huggingface_hub import HfApi
    api = HfApi()
    owner = args.owner or HF_OWNER

    values = card_values(owner)
    links = {"dataset": f"https://huggingface.co/datasets/{values['dataset_repo']}",
             "model": f"https://huggingface.co/{values['model_repo']}",
             "space": f"https://huggingface.co/spaces/{values['space_repo']}"}
    # All three are built (locally, in seconds): the dataset's counts fill in the other cards.
    stage = {"dataset": stage_dataset, "model": stage_model, "space": stage_space}
    folders = {kind: stage[kind](values) for kind in stage}
    folders = {kind: folder for kind, folder in folders.items() if args.only in (None, kind)}

    for kind, folder in folders.items():
        print(f"\n{kind}: {values[kind + '_repo']}  ←  {folder}")
        print("\n".join(listing(folder)))
    if not args.upload:
        print("\nNothing uploaded. Check the folders above, then run again with --upload.")
        return

    for kind, folder in folders.items():
        repo_id = values[kind + "_repo"]
        api.create_repo(repo_id, repo_type=kind, private=args.private or None, exist_ok=True,
                        space_sdk="static" if kind == "space" else None)
        api.upload_folder(repo_id=repo_id, folder_path=folder, repo_type=kind, delete_patterns=REPLACE[kind],
                          commit_message=f"Calendar Effects {values['code_version']}")
        print(f"uploaded {kind}: {links[kind]}")
    if "space" in folders:
        print(f"\nThe Space {links['space']} embeds the hosted dashboard, {DASHBOARD_URL}")


if __name__ == "__main__":
    main()
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.