Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,11 +1,13 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
| 3 |
|
| 4 |
from huggingface_hub import hf_hub_download
|
| 5 |
from autogluon.tabular import TabularPredictor
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
# ---------------- Settings ----------------
|
| 11 |
MODEL_REPO_ID = "Iris314/classical-automl-model"
|
|
@@ -28,9 +30,12 @@ def load_predictor():
|
|
| 28 |
local_zip = hf_hub_download(
|
| 29 |
repo_id=MODEL_REPO_ID,
|
| 30 |
filename=ZIP_FILENAME,
|
| 31 |
-
repo_type="model"
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
-
if EXTRACT_DIR.exists():
|
|
|
|
| 34 |
EXTRACT_DIR.mkdir(parents=True)
|
| 35 |
with zipfile.ZipFile(local_zip, "r") as zf:
|
| 36 |
zf.extractall(EXTRACT_DIR)
|
|
@@ -38,7 +43,11 @@ def load_predictor():
|
|
| 38 |
path = kids[0] if len(kids) == 1 and kids[0].is_dir() else EXTRACT_DIR
|
| 39 |
return TabularPredictor.load(str(path), require_py_version_match=False)
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# ---------------- Helpers ----------------
|
| 44 |
def _cast_and_rename(row_dict):
|
|
@@ -46,20 +55,21 @@ def _cast_and_rename(row_dict):
|
|
| 46 |
row["Length"] = float(row["Length"])
|
| 47 |
row["Height"] = float(row["Height"])
|
| 48 |
row["Width"] = float(row["Width"])
|
| 49 |
-
|
|
|
|
| 50 |
X_ui = pd.DataFrame([row], columns=FEATURE_COLS_UI)
|
| 51 |
X_model = X_ui.rename(columns=COLUMN_ALIAS)
|
| 52 |
return X_model
|
| 53 |
|
| 54 |
def classify_brick(length, height, width, studs):
|
| 55 |
try:
|
|
|
|
|
|
|
|
|
|
| 56 |
X = _cast_and_rename({
|
| 57 |
"Length": length, "Height": height, "Width": width, "Studs": studs
|
| 58 |
})
|
| 59 |
|
| 60 |
-
pred = PREDICTOR.predict(X)
|
| 61 |
-
pred_val = pred.iloc[0] if hasattr(pred, "iloc") else pred
|
| 62 |
-
|
| 63 |
# Try probabilities; fall back to label
|
| 64 |
try:
|
| 65 |
proba = PREDICTOR.predict_proba(X)
|
|
@@ -68,29 +78,30 @@ def classify_brick(length, height, width, studs):
|
|
| 68 |
s.index = [str(k) for k in s.index] # ensure JSON-serializable keys
|
| 69 |
return {k: float(v) for k, v in s.items()}
|
| 70 |
except Exception:
|
|
|
|
|
|
|
| 71 |
return {"prediction": str(pred_val)}
|
| 72 |
except Exception as e:
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# test_X = _cast_and_rename({"Length": 4, "Height": 1.2, "Width": 2, "Studs": 4})
|
| 78 |
-
# print("Prediction:", PREDICTOR.predict(test_X))
|
| 79 |
-
# print("Probabilities:\n", PREDICTOR.predict_proba(test_X))
|
| 80 |
|
| 81 |
-
# ---------------- Gradio
|
| 82 |
demo = gr.Interface(
|
| 83 |
fn=classify_brick,
|
| 84 |
inputs=[
|
| 85 |
-
gr.Slider(1, 10, step=0.1, value=4,
|
| 86 |
gr.Slider(0.2, 5, step=0.1, value=1.2, label="Height"),
|
| 87 |
-
gr.Slider(1, 10, step=0.1, value=2,
|
| 88 |
gr.Number(value=4, precision=0, label="Studs"),
|
| 89 |
],
|
| 90 |
outputs=gr.Label(num_top_classes=3, label="Predicted Class / Probabilities"),
|
| 91 |
examples=[[4, 1.2, 2, 4], [2, 0.6, 2, 2], [3, 2.0, 2, 2]],
|
| 92 |
-
title=
|
| 93 |
-
description=
|
| 94 |
)
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import pathlib, shutil, zipfile, os, traceback
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import gradio as gr
|
| 4 |
|
| 5 |
from huggingface_hub import hf_hub_download
|
| 6 |
from autogluon.tabular import TabularPredictor
|
| 7 |
+
|
| 8 |
+
# ---------------- UI copy ----------------
|
| 9 |
+
TITLE = "🧱 LEGO Brick Classifier"
|
| 10 |
+
DESC = "Predicts whether a LEGO piece is Standard, Flat, or Sloped from basic dimensions."
|
| 11 |
|
| 12 |
# ---------------- Settings ----------------
|
| 13 |
MODEL_REPO_ID = "Iris314/classical-automl-model"
|
|
|
|
| 30 |
local_zip = hf_hub_download(
|
| 31 |
repo_id=MODEL_REPO_ID,
|
| 32 |
filename=ZIP_FILENAME,
|
| 33 |
+
repo_type="model",
|
| 34 |
+
local_dir=str(CACHE_DIR),
|
| 35 |
+
local_dir_use_symlinks=False,
|
| 36 |
)
|
| 37 |
+
if EXTRACT_DIR.exists():
|
| 38 |
+
shutil.rmtree(EXTRACT_DIR)
|
| 39 |
EXTRACT_DIR.mkdir(parents=True)
|
| 40 |
with zipfile.ZipFile(local_zip, "r") as zf:
|
| 41 |
zf.extractall(EXTRACT_DIR)
|
|
|
|
| 43 |
path = kids[0] if len(kids) == 1 and kids[0].is_dir() else EXTRACT_DIR
|
| 44 |
return TabularPredictor.load(str(path), require_py_version_match=False)
|
| 45 |
|
| 46 |
+
try:
|
| 47 |
+
PREDICTOR = load_predictor()
|
| 48 |
+
except Exception as e:
|
| 49 |
+
PREDICTOR = None
|
| 50 |
+
print("Failed to load predictor:", e)
|
| 51 |
|
| 52 |
# ---------------- Helpers ----------------
|
| 53 |
def _cast_and_rename(row_dict):
|
|
|
|
| 55 |
row["Length"] = float(row["Length"])
|
| 56 |
row["Height"] = float(row["Height"])
|
| 57 |
row["Width"] = float(row["Width"])
|
| 58 |
+
# gr.Number returns float; round & cast for integer feature
|
| 59 |
+
row["Studs"] = int(round(float(row["Studs"])))
|
| 60 |
X_ui = pd.DataFrame([row], columns=FEATURE_COLS_UI)
|
| 61 |
X_model = X_ui.rename(columns=COLUMN_ALIAS)
|
| 62 |
return X_model
|
| 63 |
|
| 64 |
def classify_brick(length, height, width, studs):
|
| 65 |
try:
|
| 66 |
+
if PREDICTOR is None:
|
| 67 |
+
raise RuntimeError("Model failed to load on startup. Check model artifact path & runtime deps.")
|
| 68 |
+
|
| 69 |
X = _cast_and_rename({
|
| 70 |
"Length": length, "Height": height, "Width": width, "Studs": studs
|
| 71 |
})
|
| 72 |
|
|
|
|
|
|
|
|
|
|
| 73 |
# Try probabilities; fall back to label
|
| 74 |
try:
|
| 75 |
proba = PREDICTOR.predict_proba(X)
|
|
|
|
| 78 |
s.index = [str(k) for k in s.index] # ensure JSON-serializable keys
|
| 79 |
return {k: float(v) for k, v in s.items()}
|
| 80 |
except Exception:
|
| 81 |
+
pred = PREDICTOR.predict(X)
|
| 82 |
+
pred_val = pred.iloc[0] if hasattr(pred, "iloc") else pred
|
| 83 |
return {"prediction": str(pred_val)}
|
| 84 |
except Exception as e:
|
| 85 |
+
return {
|
| 86 |
+
"error": f"{type(e).__name__}: {e}",
|
| 87 |
+
"traceback": traceback.format_exc(limit=1)
|
| 88 |
+
}
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# ---------------- Gradio ----------------
|
| 91 |
demo = gr.Interface(
|
| 92 |
fn=classify_brick,
|
| 93 |
inputs=[
|
| 94 |
+
gr.Slider(1, 10, step=0.1, value=4, label="Length"),
|
| 95 |
gr.Slider(0.2, 5, step=0.1, value=1.2, label="Height"),
|
| 96 |
+
gr.Slider(1, 10, step=0.1, value=2, label="Width"),
|
| 97 |
gr.Number(value=4, precision=0, label="Studs"),
|
| 98 |
],
|
| 99 |
outputs=gr.Label(num_top_classes=3, label="Predicted Class / Probabilities"),
|
| 100 |
examples=[[4, 1.2, 2, 4], [2, 0.6, 2, 2], [3, 2.0, 2, 2]],
|
| 101 |
+
title=TITLE,
|
| 102 |
+
description=DESC
|
| 103 |
)
|
| 104 |
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
# In Spaces, no share=True needed
|
| 107 |
+
demo.launch()
|