File size: 2,492 Bytes
764a062 1a250d3 2f22e88 aeda93a 8ee07b0 1a250d3 aeda93a 1a250d3 aeda93a 1a250d3 ff0d31b 1a250d3 2f22e88 a095592 8ee07b0 1a250d3 aeda93a ac105ff aeda93a ff0d31b a095592 ff0d31b a095592 1a250d3 a095592 2f22e88 ff0d31b 764a062 a095592 ff0d31b aeda93a a095592 764a062 a095592 aeda93a a095592 aeda93a 79cfffd aeda93a | 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import joblib
import pandas as pd
import os
from huggingface_hub import hf_hub_download
from opik import Opik, track
# -------------------------------------------------
# Opik API key (HF Spaces / Expo safe)
# -------------------------------------------------
if "OPIK_API_KEY" not in os.environ:
os.environ["OPIK_API_KEY"] = os.environ.get(
"EXPO_PUBLIC_OPIK_API_KEY", ""
)
# -------------------------------------------------
# Load model from HF Model Hub
# -------------------------------------------------
MODEL_REPO = "obx0x3/sensei-model"
MODEL_FILE = "impulse_model.pkl"
model_path = hf_hub_download(
repo_id=MODEL_REPO,
filename=MODEL_FILE
)
impulse_model = joblib.load(model_path)
# -------------------------------------------------
# Opik client (event logger)
# -------------------------------------------------
try:
opik_client = Opik(project_name="budgetbuddy-hackathon")
except Exception as e:
print("Opik disabled:", e)
opik_client = None
# -------------------------------------------------
# TRACKED FUNCTION (this creates a TRACK)
# -------------------------------------------------
@track(project_name="budgetbuddy-hackathon")
def predict_impulse(category, amount, payment_method, day):
input_data = {
"category": category,
"amount": float(amount),
"payment_method": payment_method,
"day": day
}
df = pd.DataFrame([input_data])
pred = impulse_model.predict(df)[0]
prob = impulse_model.predict_proba(df)[0].max()
result = {
"impulsive": bool(pred),
"confidence": round(float(prob), 3),
"label": "Impulsive" if pred else "Normal Spend"
}
# -------------------------------------------------
# EVENT inside the TRACK
# -------------------------------------------------
if opik_client:
try:
opik_client.log_event(
name="Impulse Analysis Result",
input=input_data,
output=result,
model="sensei-impulse-model",
metadata={
"ui": "hf-space",
"feature": "impulse-detection",
"confidence_band": (
"high" if prob > 0.75 else
"medium" if prob > 0.5 else
"low"
)
}
)
except Exception as e:
print("Opik logging failed:", e)
return result |