apsora commited on
Commit
0b09d2c
·
verified ·
1 Parent(s): 3e1266f

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +92 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pathlib, shutil, zipfile
3
+ import pandas as pd
4
+ import gradio as gr
5
+ from huggingface_hub import hf_hub_download
6
+ from autogluon.tabular import TabularPredictor
7
+
8
+ # ====== Settings (edit if your repo/zip name changes) ======
9
+ MODEL_REPO_ID = "Iris314/classical-automl-model"
10
+ ZIP_FILENAME = "lego_predictor_dir.zip"
11
+
12
+ # UI → model feature name mapping
13
+ COLUMN_ALIAS = {
14
+ "Length": "Max Length (cm)",
15
+ "Height": "Max Height (cm)",
16
+ "Width": "Width (cm)",
17
+ "Studs": "Studs",
18
+ }
19
+ FEATURE_COLS_UI = ["Length", "Height", "Width", "Studs"]
20
+
21
+ # ====== Load predictor from the model repo ======
22
+ CACHE_DIR = pathlib.Path("hf_cache"); EXTRACT_DIR = CACHE_DIR / "predictor"
23
+ CACHE_DIR.mkdir(exist_ok=True, parents=True)
24
+
25
+ def load_predictor():
26
+ local_zip = hf_hub_download(
27
+ repo_id=MODEL_REPO_ID,
28
+ filename=ZIP_FILENAME,
29
+ repo_type="model",
30
+ local_dir=str(CACHE_DIR),
31
+ local_dir_use_symlinks=False,
32
+ )
33
+ if EXTRACT_DIR.exists():
34
+ shutil.rmtree(EXTRACT_DIR)
35
+ EXTRACT_DIR.mkdir(parents=True, exist_ok=True)
36
+ with zipfile.ZipFile(local_zip, "r") as zf:
37
+ zf.extractall(EXTRACT_DIR)
38
+ kids = list(EXTRACT_DIR.iterdir())
39
+ path = kids[0] if len(kids) == 1 and kids[0].is_dir() else EXTRACT_DIR
40
+ return TabularPredictor.load(str(path), require_py_version_match=False)
41
+
42
+ PREDICTOR = load_predictor()
43
+
44
+ def _cast_and_rename(row_dict):
45
+ row = dict(row_dict)
46
+ row["Length"] = float(row["Length"])
47
+ row["Height"] = float(row["Height"])
48
+ row["Width"] = float(row["Width"])
49
+ row["Studs"] = int(round(float(row["Studs"])))
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({"Length": length, "Height": height, "Width": width, "Studs": studs})
57
+ pred = PREDICTOR.predict(X)
58
+ pred_val = pred.iloc[0] if hasattr(pred, "iloc") else pred
59
+ try:
60
+ proba = PREDICTOR.predict_proba(X)
61
+ s = proba.iloc[0] if hasattr(proba, "iloc") else proba
62
+ s = s.sort_values(ascending=False)
63
+ s.index = [str(k) for k in s.index]
64
+ return {k: float(v) for k, v in s.items()}
65
+ except Exception:
66
+ return {"prediction": str(pred_val)}
67
+ except Exception as e:
68
+ import traceback
69
+ return {"error": f"{type(e).__name__}: {e}", "traceback": traceback.format_exc()}
70
+
71
+ with gr.Blocks() as demo:
72
+ gr.Markdown("# 🧱 LEGO Brick Classifier")
73
+ gr.Markdown("Enter dimensions to predict **Standard / Flat / Sloped**. Uses a classmate's AutoGluon model trained on `aedupuga/lego-sizes`.")
74
+ with gr.Row():
75
+ length = gr.Slider(1, 10, step=0.1, value=4, label="Length")
76
+ height = gr.Slider(0.2, 5, step=0.1, value=1.2, label="Height")
77
+ with gr.Row():
78
+ width = gr.Slider(1, 10, step=0.1, value=2, label="Width")
79
+ studs = gr.Number(value=4, precision=0, label="Studs")
80
+ out = gr.Label(num_top_classes=3, label="Predicted Class / Probabilities")
81
+ gr.Button("Classify Brick", variant="primary").click(
82
+ fn=classify_brick, inputs=[length, height, width, studs], outputs=out
83
+ )
84
+ gr.Examples(
85
+ examples=[[4, 1.2, 2, 4],[2, 0.6, 2, 2],[3, 2.0, 2, 2]],
86
+ inputs=[length, height, width, studs],
87
+ label="Examples",
88
+ cache_examples=False
89
+ )
90
+
91
+ if __name__ == "__main__":
92
+ demo.launch()