Spaces:
Sleeping

superkart-api / app.py
Metatron2030's picture
deploy superkart-sales-v1.0 (test RMSE 274.21)
4362ba2 verified
Raw History Blame Contribute Delete
6.75 kB
"""SuperKart sales-forecast API.
Serves the pipeline produced in the training notebook. All preprocessing --
feature engineering, scaling, one-hot encoding -- lives INSIDE the
serialized pipeline, so this file contains no data-cleaning logic. That is
deliberate: any transformation implemented here could diverge from training.
"""
import json
import logging
import os
import time
import joblib
import numpy as np
import pandas as pd
from flask import Flask, jsonify, request
# superkart_features must be importable BEFORE joblib.load: the pipeline's
# FunctionTransformer references engineer() by module path.
import superkart_features # noqa: F401
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s [%(name)s] %(message)s")
log = logging.getLogger("superkart-api")
app = Flask(__name__)
MODEL_PATH = os.getenv("MODEL_PATH", "superkart_model_v1.joblib")
MAX_BATCH = int(os.getenv("MAX_BATCH", 500))
# ── Load once at import time, never per request ──────────────────────────
pipe = joblib.load(MODEL_PATH)
manifest = json.load(open("model_manifest.json"))
MODEL_VERSION = manifest["model_version"]
COLUMNS = manifest["expected_columns"]
LEVELS = manifest.get("categorical_levels", {})
RANGES = manifest.get("numeric_ranges", {})
NUMERIC = set(RANGES) | {"Store_Establishment_Year"}
log.info("loaded %s (%s) β€” %d expected columns",
MODEL_PATH, MODEL_VERSION, len(COLUMNS))
# ── Golden-sample assertion: refuse to serve a model that changed ────────
MODEL_READY = False
try:
g = json.load(open("golden_sample.json"))
got = pipe.predict(pd.DataFrame(g["input"]))
if np.allclose(got, g["expected"], rtol=g.get("tolerance_rtol", 1e-6)):
MODEL_READY = True
log.info("golden-sample check PASSED")
else:
log.error("GOLDEN SAMPLE MISMATCH expected=%s got=%s",
g["expected"], list(map(float, got)))
except FileNotFoundError:
MODEL_READY = True
log.warning("no golden_sample.json β€” serving UNVERIFIED")
def validate(row, idx=0):
"""Return (clean_row, error_message). Fail fast and be specific."""
if not isinstance(row, dict):
return None, f"row {idx}: expected an object, got {type(row).__name__}"
missing = [c for c in COLUMNS if c not in row]
if missing:
return None, f"row {idx}: missing field(s): {', '.join(missing)}"
clean = {}
for c in COLUMNS:
v = row[c]
if c in NUMERIC:
try:
v = float(v)
except (TypeError, ValueError):
return None, f"row {idx}: '{c}' must be numeric, got {v!r}"
if not np.isfinite(v):
return None, f"row {idx}: '{c}' must be finite, got {v!r}"
r = RANGES.get(c)
# Out-of-range is a WARNING, not an error: the model extrapolates,
# and rejecting a genuinely new product would be unhelpful.
if r and not (r["min"] <= v <= r["max"]):
log.warning("row %d: %s=%s outside training range [%s, %s]",
idx, c, v, r["min"], r["max"])
else:
v = str(v)
known = LEVELS.get(c)
if known and v not in known:
# handle_unknown='ignore' encodes this as all-zeros (Β§9.6).
log.warning("row %d: %s='%s' unseen in training", idx, c, v)
clean[c] = v
return clean, None
@app.get("/")
def root():
return jsonify(
service="SuperKart Sales Forecast API",
model=MODEL_VERSION,
status="ready" if MODEL_READY else "model_verification_failed",
endpoints={
"GET /health": "liveness probe",
"GET /v1/model-info": "model version, metrics, expected schema",
"POST /v1/predict": "single object or array of objects "
f"(max {MAX_BATCH})",
},
example={c: ("FD1234" if c == "Product_Id" else "…") for c in COLUMNS},
), 200
@app.get("/health")
def health():
return jsonify(status="ok"), 200
@app.get("/ready")
def ready():
if not MODEL_READY:
return jsonify(status="model_verification_failed"), 503
return jsonify(status="ready", model=MODEL_VERSION), 200
@app.get("/v1/model-info")
def model_info():
return jsonify(
model=MODEL_VERSION,
model_type=manifest["model_type"],
metrics=manifest["metrics"],
expected_columns=COLUMNS,
categorical_levels=LEVELS,
numeric_ranges=RANGES,
max_batch=MAX_BATCH,
known_limitations=manifest.get("known_limitations", []),
), 200
@app.post("/v1/predict")
def predict():
t0 = time.perf_counter()
payload = request.get_json(silent=True) # silent -> None, not a 500
if payload is None:
return jsonify(error="body must be valid JSON with "
"Content-Type: application/json",
code="MALFORMED_JSON"), 400
rows = payload if isinstance(payload, list) else [payload]
if not rows:
return jsonify(error="empty request", code="EMPTY"), 400
if len(rows) > MAX_BATCH:
return jsonify(error=f"batch limit is {MAX_BATCH} rows, got {len(rows)}",
code="BATCH_TOO_LARGE"), 413
clean = []
for i, r in enumerate(rows):
c, err = validate(r, i)
if err:
return jsonify(error=err, code="INVALID_INPUT", row=i), 422
clean.append(c)
try:
preds = pipe.predict(pd.DataFrame(clean, columns=COLUMNS))
except Exception:
log.exception("inference failed") # trace to the logs...
return jsonify(error="inference failed", # ...never to the caller
code="INFERENCE_ERROR"), 500
ms = (time.perf_counter() - t0) * 1000
vals = [round(float(p), 2) for p in preds]
body = {"predictions": vals, "n": len(vals),
"model": MODEL_VERSION, "unit": "Product_Store_Sales_Total"}
if len(vals) == 1:
body["prediction"] = vals[0]
log.info("predict n=%d ms=%.1f", len(vals), ms)
resp = jsonify(body)
resp.headers["X-Inference-Ms"] = f"{ms:.1f}"
resp.headers["X-Model-Version"] = MODEL_VERSION
return resp, 200
@app.errorhandler(404)
def nf(_):
return jsonify(error="route not found", code="NO_ROUTE"), 404
@app.errorhandler(405)
def na(_):
return jsonify(error="method not allowed", code="BAD_METHOD"), 405
if __name__ == "__main__":
# 0.0.0.0, NOT 127.0.0.1: inside a container loopback is unreachable
# from outside no matter what port mapping is used.
app.run(host="0.0.0.0", port=int(os.getenv("PORT", 7860)), debug=False)