AbhishekS2005 commited on
Commit
66ca7f0
·
verified ·
1 Parent(s): a600de8

Add custom handler.py for sklearn inference

Browse files
Files changed (1) hide show
  1. handler.py +62 -0
handler.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom inference handler for the MLForge test sklearn LinearRegression model.
3
+
4
+ This handler lets the Hugging Face Inference API serve sklearn/joblib models
5
+ that are not natively supported by the built-in pipeline loaders.
6
+
7
+ HuggingFace loads this file automatically when the repo uses:
8
+ library_name: sklearn
9
+ pipeline_tag: tabular-regression
10
+
11
+ Expected request format:
12
+ {"inputs": [[5.0, 3.0]]} → single or multi-sample list of feature vectors
13
+ """
14
+
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import joblib
19
+ import numpy as np
20
+
21
+
22
+ class EndpointHandler:
23
+ """Custom HF Endpoint handler for sklearn regression models."""
24
+
25
+ def __init__(self, path: str = ""):
26
+ model_dir = Path(path)
27
+
28
+ # Try the canonical name first, then fall back to any .joblib file
29
+ candidate = model_dir / "sklearn_model.joblib"
30
+ if not candidate.exists():
31
+ matches = list(model_dir.glob("*.joblib"))
32
+ if not matches:
33
+ raise FileNotFoundError(
34
+ f"No .joblib model file found in {model_dir}"
35
+ )
36
+ candidate = matches[0]
37
+
38
+ self.model = joblib.load(candidate)
39
+ self._model_file = candidate.name
40
+
41
+ def __call__(self, data: dict[str, Any]) -> list[float]:
42
+ """Run inference.
43
+
44
+ Args:
45
+ data: Dict with key ``"inputs"`` containing a list of feature vectors,
46
+ e.g. ``{"inputs": [[5.0, 3.0], [1.0, 2.0]]}``
47
+
48
+ Returns:
49
+ List of predicted float values, one per input row.
50
+ """
51
+ raw = data.get("inputs", data.get("data"))
52
+ if raw is None:
53
+ raise ValueError(
54
+ "Request must contain 'inputs' key with a list of feature vectors."
55
+ )
56
+
57
+ X = np.array(raw, dtype=float)
58
+ if X.ndim == 1:
59
+ X = X.reshape(1, -1)
60
+
61
+ predictions = self.model.predict(X)
62
+ return predictions.tolist()