Spaces:
Sleeping
Sleeping
File size: 6,754 Bytes
4362ba2 | 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | """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)
|