"""Export the trained Random Forest to model.json so a browser can run it (no server needed).""" import json import joblib bundle = joblib.load("model.joblib") model, classes = bundle["model"], bundle["classes"] trees = [] for est in model.estimators_: t = est.tree_ values = t.value[:, 0, :] probs = (values / values.sum(axis=1, keepdims=True)).round(6).tolist() trees.append({ "left": t.children_left.tolist(), "right": t.children_right.tolist(), "feature": t.feature.tolist(), "threshold": [float(x) for x in t.threshold], "probs": probs, }) with open("model.json", "w") as f: json.dump({"classes": classes, "trees": trees}, f, separators=(",", ":")) print(f"Saved model.json with {len(trees)} trees")