Restore pre-BYOM Space
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152534 unmodified lines58596061626364656667686970717273744 unmodified lines7980818283848548 unmodified lines1341351361371381391405 unmodified lines14614714814915015146 unmodified lines19819920020120220331 unmodified lines235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436"""NILMbench HuggingFace Space.Three tabs:1. **Built-in example** – run the FaustineCNN baseline on a packaged6-second 16 kHz V/I frame from UK-DALE House 2.2. **Upload V/I frame** – run FaustineCNN on a user-supplied single frame.3. **Benchmark your model** – upload a ``.py`` model definition + a ``.pt``weights file and score it on the dense UK-DALE House 2 benchmark (full60,000 frames; the Space defaults to a 500-frame quick check to staywithin the free-tier compute budget).Model weights, classes, and recall-constrained cutoffs for the baseline arepulled from the HF model repo ``Pybunny/nilmbench-faustine`` at startup."""# ----------------------------------------------------------------------# Monkey-patch the gradio_client schema walker BEFORE importing gradio.# In gradio 4.44 / gradio_client 1.5 the walker recurses into# ``additionalProperties`` without checking whether the value is a bool# (JSON-Schema allows ``additionalProperties: true``), then crashes with# ``TypeError: argument of type 'bool' is not iterable``. This brings down# the / route at startup. Patching the two entry points is enough.# ----------------------------------------------------------------------import gradio_client.utils as _gc_utils # noqa: E402_orig_get_type = _gc_utils.get_type_orig_to_python = _gc_utils._json_schema_to_python_typedef _safe_get_type(schema):if isinstance(schema, bool):return "Any" if schema else "None"return _orig_get_type(schema)def _safe_to_python(schema, defs):if isinstance(schema, bool):return "Any" if schema else "None"return _orig_to_python(schema, defs)_gc_utils.get_type = _safe_get_type_gc_utils._json_schema_to_python_type = _safe_to_pythonimport importlib.utilimport jsonimport sysimport tempfileimport tracebackfrom pathlib import Pathimport numpy as np4 unmodified linesimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom huggingface_hub import hf_hub_download, snapshot_download# nilmbench is installed from the companion GitHub repo (see requirements.txt).from nilmbench.runner import run_user_modelfrom nilmbench.benchmark import evaluate_densefrom nilmbench.io.report import render_markdown_reportHERE = Path(__file__).resolve().parentEXAMPLES_DIR = HERE / "examples"MODEL_REPO = "Pybunny/nilmbench-faustine"DATASET_REPO = "Pybunny/nilmbench-ukdale"# UK-DALE House 2 calibration constants (from calibration_house_2.cfg).V_PER_ADC = 1.88296904357e-74 unmodified lines# ----------------------------------------------------------------------# Baseline model (self-contained for the single-frame demo)# ----------------------------------------------------------------------class FaustineCNN(nn.Module):def __init__(self, n_categories: int):48 unmodified lines# ----------------------------------------------------------------------# Single-frame inference (tabs 1 and 2)# ----------------------------------------------------------------------def _to_2d_image(vi_norm: np.ndarray) -> torch.Tensor:if vi_norm.shape != (2, 96000):5 unmodified linesdef predict(vi_norm: np.ndarray, aggregate_W: float) -> dict[str, float]:with torch.no_grad():scores = MODEL(_to_2d_image(vi_norm)).cpu().numpy().squeeze(0)shares = scores / (scores.sum() + 1e-9)raw = shares * float(aggregate_W)out = {}46 unmodified linesreturn figdef list_examples() -> list[str]:if not EXAMPLES_DIR.exists():return []31 unmodified linesreturn make_overview_plot(vi, preds, None), preds# ----------------------------------------------------------------------# Tab 3: full benchmark, with the user's uploaded model# ----------------------------------------------------------------------_BENCHMARK_DATA_DIR: Path | None = Nonedef _ensure_benchmark_data() -> Path:"""Snapshot-download the dense House-2 split (cached after first call)."""global _BENCHMARK_DATA_DIRif _BENCHMARK_DATA_DIR is not None:return _BENCHMARK_DATA_DIRlocal = snapshot_download(repo_id=DATASET_REPO,repo_type="dataset",allow_patterns=["benchmark/*", "summary.json", "README.md"],)_BENCHMARK_DATA_DIR = Path(local)return _BENCHMARK_DATA_DIRdef _import_user_module(file_path: Path, class_name: str):"""Dynamically import a user-uploaded ``.py`` and return the class."""spec = importlib.util.spec_from_file_location("user_model_module", file_path)if spec is None or spec.loader is None:raise ImportError(f"Could not load module from {file_path}")mod = importlib.util.module_from_spec(spec)sys.modules["user_model_module"] = modspec.loader.exec_module(mod)if not hasattr(mod, class_name):raise AttributeError(f"Uploaded module has no attribute '{class_name}'. "f"Available: {[n for n in dir(mod) if not n.startswith('_')]}")return getattr(mod, class_name)def _subset_dataset(data_root: Path, max_frames: int) -> Path:"""Make a temporary benchmark/ directory with the first N frames only.Lets us cap compute time on the free Space tier."""src = data_root / "benchmark"n_total = int(np.load(src / "x_vi_6s.npy", mmap_mode="r").shape[0])if max_frames >= n_total:return data_root # use full settmp_root = Path(tempfile.mkdtemp(prefix="nilmbench_subset_"))sub = tmp_root / "benchmark"sub.mkdir(parents=True)x = np.load(src / "x_vi_6s.npy", mmap_mode="r")np.save(sub / "x_vi_6s.npy", np.asarray(x[:max_frames]))lab = np.load(src / "labels_and_index.npz", allow_pickle=True)sliced = {}for k in lab.files:v = lab[k]if v.ndim >= 1 and v.shape[0] == n_total:sliced[k] = v[:max_frames]else:sliced[k] = vnp.savez_compressed(sub / "labels_and_index.npz", **sliced)return tmp_rootdef run_benchmark_upload(model_file, weights_file, class_name: str,output_kind: str, max_frames: int, batch_size: int):"""Run the user's model on the dense House-2 set and render a report."""if model_file is None:return "**Please upload a Python file defining your model.**", Noneclass_name = (class_name or "Model").strip() or "Model"try:ModelCls = _import_user_module(Path(model_file.name), class_name)except Exception as exc:return (f"**Failed to import model class `{class_name}`:**\n\n"f"```\n{traceback.format_exc()}\n```"), Nonetry:data_root = _ensure_benchmark_data()except Exception:return (f"**Could not download benchmark data:**\n\n"f"```\n{traceback.format_exc()}\n```"), Nonetry:active_root = _subset_dataset(data_root, int(max_frames))except Exception:return (f"**Could not prepare data subset:**\n\n"f"```\n{traceback.format_exc()}\n```"), Nonetmpdir = Path(tempfile.mkdtemp(prefix="nilmbench_report_"))preds_path = tmpdir / "predictions.npz"try:# We already have the class; rebind via a temporary module name so# nilmbench.runner's importer can find it.sys.modules["__nilmbench_user__"] = sys.modules["user_model_module"]run = run_user_model(module_spec=f"__nilmbench_user__:{class_name}",weights_path=weights_file.name if weights_file is not None else None,data_root=active_root,out_path=preds_path,batch_size=int(batch_size),device="cpu",output_kind=output_kind,strict_load=False,model_name=class_name,)except Exception:return (f"**Model failed during inference:**\n\n"f"```\n{traceback.format_exc()}\n```"), Nonepreds = np.load(preds_path, allow_pickle=True)result = evaluate_dense(y_true_W=preds["y_true"].astype(np.float32),y_pred_W=preds["y_pred"].astype(np.float32),classes=[str(c) for c in preds["class_names"]],model_name=class_name,)extra = {"Model class": class_name,"Weights file": Path(weights_file.name).name if weights_file else "(none)","Frames scored": f"{run.n_frames} / 60,000","Output kind": output_kind,}md = render_markdown_report(result,title=f"NILMbench report — {class_name}",extra=extra,)score_json_path = tmpdir / "score.json"score_json_path.write_text(json.dumps(result.to_dict(), indent=2, sort_keys=True))return md, str(score_json_path)# ----------------------------------------------------------------------# UI# ----------------------------------------------------------------------def build_ui() -> gr.Blocks:examples = list_examples()with gr.Blocks(title="NILMbench") as demo:gr.Markdown("# NILMbench\n""Open benchmark for high-frequency NILM regression on UK-DALE 2015 ""(House 1 → House 2). Headline metric: modified Jaccard index ""**MJ$_{20W}$** with hybrid tolerance.\n\n""Source code: <https://github.com/Saharmgh/NILMbench> · ""Baseline model: <https://huggingface.co/Pybunny/nilmbench-faustine> · ""Dataset: <https://huggingface.co/datasets/Pybunny/nilmbench-ukdale>")with gr.Tabs():with gr.TabItem("Single frame · built-in example"):ex = gr.Dropdown(examples, label="Example frame",value=examples[0] if examples else None)btn = gr.Button("Run FaustineCNN", variant="primary")plot_a = gr.Plot()lab_a = gr.JSON(label="Predicted power per category (W)")btn.click(run_example, ex, [plot_a, lab_a])with gr.TabItem("Single frame · upload V/I"):up = gr.File(label="V/I segment (.npy, shape (2, 96000), ""FLAC-normalised float in [-1, 1])")agg = gr.Slider(0, 8000, value=300, step=10,label="Aggregate active power (W)")btn2 = gr.Button("Run FaustineCNN", variant="primary")plot_b = gr.Plot()lab_b = gr.JSON(label="Predicted power per category (W)")btn2.click(run_upload, [up, agg], [plot_b, lab_b])with gr.TabItem("Benchmark your model"):gr.Markdown("Full benchmark scoring is run via the CLI on your ""machine (uses up to 5 GB of UK-DALE 16 kHz V/I data ""and tens of minutes on CPU):\n\n""```bash\n""pip install git+https://github.com/Saharmgh/NILMbench\n""nilmbench benchmark \\\n"" --module my_model:MyModel \\\n"" --weights ./my_checkpoint.pt \\\n"" --data hf:Pybunny/nilmbench-ukdale \\\n"" --out ./report/\n""```\n\n""See ""[examples/byom_template.py](https://github.com/Saharmgh/NILMbench/blob/main/examples/byom_template.py) ""and ""[docs/TESTING_GUIDE.md](https://github.com/Saharmgh/NILMbench/blob/main/docs/TESTING_GUIDE.md) ""for the model contract and a step-by-step recipe.")return demoif __name__ == "__main__":# Use bare launch(); HF Spaces auto-detects host/port from env vars.# The schema bug that breaks /info is already handled by the# gradio_client monkey-patch at the top of this file.build_ui().launch()12345678910111213144 unmodified lines19202122232425262728294 unmodified lines3435363738394048 unmodified lines899091929394955 unmodified lines10110210310410510610710846 unmodified lines15515615715815916016116216331 unmodified lines195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233"""NILMbench HuggingFace Space.Single-frame demo of the FaustineCNN baseline. Model weights, classes, andrecall-constrained cutoffs are pulled from the HF model repo``Pybunny/nilmbench-faustine`` at startup. Example frames are bundled withthe Space so the demo works offline of the laptop."""from __future__ import annotationsimport jsonfrom pathlib import Pathimport numpy as np4 unmodified linesimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom huggingface_hub import hf_hub_downloadHERE = Path(__file__).resolve().parentEXAMPLES_DIR = HERE / "examples"MODEL_REPO = "Pybunny/nilmbench-faustine"# UK-DALE House 2 calibration constants (from calibration_house_2.cfg).V_PER_ADC = 1.88296904357e-74 unmodified lines# ----------------------------------------------------------------------# Model (self-contained so the Space has no dependency on the nilmbench pkg)# ----------------------------------------------------------------------class FaustineCNN(nn.Module):def __init__(self, n_categories: int):48 unmodified lines# ----------------------------------------------------------------------# Inference + plotting# ----------------------------------------------------------------------def _to_2d_image(vi_norm: np.ndarray) -> torch.Tensor:if vi_norm.shape != (2, 96000):5 unmodified linesdef predict(vi_norm: np.ndarray, aggregate_W: float) -> dict[str, float]:with torch.no_grad():scores = MODEL(_to_2d_image(vi_norm)).cpu().numpy().squeeze(0)# FaustineCNN outputs per-category Bernoulli activations; renormalise# across categories to obtain shares, then scale by the aggregate.shares = scores / (scores.sum() + 1e-9)raw = shares * float(aggregate_W)out = {}46 unmodified linesreturn fig# ----------------------------------------------------------------------# Gradio handlers# ----------------------------------------------------------------------def list_examples() -> list[str]:if not EXAMPLES_DIR.exists():return []31 unmodified linesreturn make_overview_plot(vi, preds, None), preds# ----------------------------------------------------------------------# UI# ----------------------------------------------------------------------def build_ui() -> gr.Blocks:examples = list_examples()with gr.Blocks(title="NILMbench demo") as demo:gr.Markdown("# NILMbench demo\n""FaustineCNN trained on UK-DALE House 1, applied to a single ""6-second 16 kHz V/I segment from House 2. Predicted power is ""post-processed with the recall-constrained cutoffs from the paper.\n\n""Source code: <https://github.com/Saharmgh/NILMbench> · ""Model: <https://huggingface.co/Pybunny/nilmbench-faustine>")with gr.Tabs():with gr.TabItem("Built-in example"):ex = gr.Dropdown(examples, label="Example frame",value=examples[0] if examples else None)btn = gr.Button("Run", variant="primary")plot_a = gr.Plot()lab_a = gr.JSON(label="Predicted power per category (W)")btn.click(run_example, ex, [plot_a, lab_a])with gr.TabItem("Upload your own"):up = gr.File(label="V/I segment (.npy, shape (2, 96000), ""FLAC-normalised float in [-1, 1])")agg = gr.Slider(0, 8000, value=300, step=10,label="Aggregate active power (W)")btn2 = gr.Button("Run", variant="primary")plot_b = gr.Plot()lab_b = gr.JSON(label="Predicted power per category (W)")btn2.click(run_upload, [up, agg], [plot_b, lab_b])return demoif __name__ == "__main__":build_ui().launch()
app.py+23-226