bcueva commited on
Commit
0b3737a
Β·
verified Β·
1 Parent(s): b7cffe2

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +48 -70
app.py CHANGED
@@ -1,18 +1,16 @@
1
- import pathlib, shutil, zipfile
2
  import pandas
3
  import gradio
4
  import huggingface_hub
5
- import autogluon.tabular
 
6
 
7
- MODEL_REPO_ID = "jennifee/classical_automl_model"
8
- ZIP_FILENAME = "autogluon_predictor_dir.zip"
9
  CACHE_DIR = pathlib.Path("hf_assets")
10
  EXTRACT_DIR = CACHE_DIR / "predictor_native"
11
 
12
- FEATURE_COLS_MODEL = ['phone_hours', 'computer_hours', 'device_count', 'sleep_quality', 'sleep_time', 'sleep_hours']
13
- TARGET_COL = "use_before_bed"
14
- SLEEP_QUALITY_LABELS = ['good', 'medium', 'bad']
15
- USE_BEFORE_BED_LABELS = {0: 'No', 1: 'Yes'}
16
 
17
  def _prepare_predictor_dir() -> str:
18
  CACHE_DIR.mkdir(parents=True, exist_ok=True)
@@ -33,86 +31,66 @@ def _prepare_predictor_dir() -> str:
33
  return str(predictor_root)
34
 
35
  PREDICTOR_DIR = _prepare_predictor_dir()
36
- PREDICTOR = autogluon.tabular.TabularPredictor.load(PREDICTOR_DIR, require_py_version_match=False)
37
 
38
  def _human_label(c):
39
  try:
40
  ci = int(c)
41
- if ci in USE_BEFORE_BED_LABELS:
42
- return USE_BEFORE_BED_LABELS[ci]
43
  except Exception:
44
- pass
45
- return str(c)
46
-
47
- def do_predict(phone_hours, computer_hours, device_count, sleep_quality_label, sleep_time, sleep_hours):
48
- row = {
49
- "phone_hours": float(phone_hours),
50
- "computer_hours": float(computer_hours),
51
- "device_count": int(device_count),
52
- "sleep_quality": sleep_quality_label,
53
- "sleep_time": int(sleep_time),
54
- "sleep_hours": float(sleep_hours),
55
- }
56
- X = pandas.DataFrame([row], columns=FEATURE_COLS_MODEL)
57
 
58
- pred_series = PREDICTOR.predict(X)
59
- raw_pred = pred_series.iloc[0]
60
- pred_label = _human_label(raw_pred)
61
 
62
- proba = None
63
- try:
64
- proba = PREDICTOR.predict_proba(X)
65
- if isinstance(proba, pandas.Series):
66
- proba = proba.to_frame().T
67
- except Exception as e:
68
- print(f"Error calculating probabilities: {e}")
69
- proba = None
70
-
71
- proba_dict = None
72
- if proba is not None:
73
- row0 = proba.iloc[0]
74
- tmp = {}
75
- for cls in [0, 1]:
76
- val = None
77
- if cls in row0.index:
78
- val = row0[cls]
79
- elif str(cls) in row0.index:
80
- val = row0[str(cls)]
81
- if val is not None:
82
- key = _human_label(cls)
83
- tmp[key] = float(tmp.get(key, 0.0)) + float(val)
84
- if tmp:
85
- proba_dict = dict(sorted(tmp.items(), key=lambda kv: kv[1], reverse=True))
86
 
87
  md = f"**Prediction:** {pred_label}"
88
- if proba_dict:
89
- md += f" \n**Confidence:** {round(proba_dict.get(pred_label, 0.0) * 100, 2)}%"
 
 
 
90
 
91
- return proba_dict, md
 
 
 
 
92
 
93
- EXAMPLES = [[3.5, 5.0, 3, 'good', 23, 7.0], [4.2, 6.5, 3, 'medium', 0, 6.5], [5.0, 4.0, 4, 'bad', 1, 6.0], [2.0, 7.5, 3, 'good', 22, 7.5], [3.8, 6.0, 3, 'medium', 0, 6.0]]
94
 
95
  with gradio.Blocks() as demo:
96
- gradio.Markdown("# Predict Phone Use Before Bed")
97
  gradio.Markdown(
98
- "This app predicts whether a student uses their phone before bed based on their sleeping habits."
99
- "\nEnter the student's sleeping habits below to get a prediction."
 
100
  )
101
 
102
- with gradio.Row():
103
- phone_hours = gradio.Number(value=3.5, precision=1, label=FEATURE_COLS_MODEL[0])
104
- computer_hours = gradio.Number(value=5.0, precision=1, label=FEATURE_COLS_MODEL[1])
105
- device_count = gradio.Number(value=3, precision=0, label=FEATURE_COLS_MODEL[2])
106
 
107
- with gradio.Row():
108
- sleep_quality_label = gradio.Radio(choices=SLEEP_QUALITY_LABELS, value="good", label=FEATURE_COLS_MODEL[3])
109
- sleep_time = gradio.Number(value=23, precision=0, label=FEATURE_COLS_MODEL[4])
110
- sleep_hours = gradio.Number(value=7.0, precision=1, label=FEATURE_COLS_MODEL[5])
111
-
112
- proba_pretty = gradio.Label(num_top_classes=2, label="Probability of Using Phone Before Bed")
113
  prediction_output = gradio.Markdown()
114
 
115
- inputs = [phone_hours, computer_hours, device_count, sleep_quality_label, sleep_time, sleep_hours]
 
116
  outputs = [proba_pretty, prediction_output]
117
  for comp in inputs:
118
  comp.change(fn=do_predict, inputs=inputs, outputs=outputs)
@@ -121,7 +99,7 @@ with gradio.Blocks() as demo:
121
  examples=EXAMPLES,
122
  inputs=inputs,
123
  label="Representative examples",
124
- examples_per_page=5,
125
  cache_examples=False,
126
  )
127
 
 
1
+ import pathlib, shutil, zipfile, tempfile
2
  import pandas
3
  import gradio
4
  import huggingface_hub
5
+ import autogluon.multimodal
6
+ import PIL.Image
7
 
8
+ MODEL_REPO_ID = "george2cool36/hw2_image_automl_autogluon"
9
+ ZIP_FILENAME = "ag_image_predictor_dir.zip"
10
  CACHE_DIR = pathlib.Path("hf_assets")
11
  EXTRACT_DIR = CACHE_DIR / "predictor_native"
12
 
13
+ CLASS_LABELS = {0: "πŸ›‘ Has Stop Sign", 1: "βœ… No Stop Sign"}
 
 
 
14
 
15
  def _prepare_predictor_dir() -> str:
16
  CACHE_DIR.mkdir(parents=True, exist_ok=True)
 
31
  return str(predictor_root)
32
 
33
  PREDICTOR_DIR = _prepare_predictor_dir()
34
+ PREDICTOR = autogluon.multimodal.MultiModalPredictor.load(PREDICTOR_DIR)
35
 
36
  def _human_label(c):
37
  try:
38
  ci = int(c)
39
+ return CLASS_LABELS.get(ci, str(c))
 
40
  except Exception:
41
+ return CLASS_LABELS.get(c, str(c))
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ def do_predict(pil_img: PIL.Image.Image):
44
+ if pil_img is None:
45
+ return {}, "No image provided."
46
 
47
+ tmpdir = pathlib.Path(tempfile.mkdtemp())
48
+ img_path = tmpdir / "input.png"
49
+ pil_img.save(img_path)
50
+
51
+ df = pandas.DataFrame({"image": [str(img_path)]})
52
+
53
+ proba_df = PREDICTOR.predict_proba(df)
54
+ proba_df = proba_df.rename(columns={0: "πŸ›‘ Has Stop Sign (0)", 1: "βœ… No Stop Sign (1)"})
55
+ row = proba_df.iloc[0]
56
+
57
+ pretty_dict = {
58
+ "πŸ›‘ Has Stop Sign": float(row.get("πŸ›‘ Has Stop Sign (0)", 0.0)),
59
+ "βœ… No Stop Sign": float(row.get("βœ… No Stop Sign (1)", 0.0)),
60
+ }
61
+
62
+ predicted_class = PREDICTOR.predict(df).iloc[0]
63
+ pred_label = _human_label(predicted_class)
 
 
 
 
 
 
 
64
 
65
  md = f"**Prediction:** {pred_label}"
66
+ if pretty_dict:
67
+ md += f" \n**Confidence:** {round(pretty_dict.get(pred_label, 0.0) * 100, 2)}%"
68
+
69
+
70
+ return pretty_dict, md
71
 
72
+ EXAMPLES = [
73
+ ["https://www.kingsrivercasting.com/images/stories/virtuemart/product/STOP%20SIGN%20(5).jpg"],
74
+ ["https://www.trafficsafetywarehouse.com/Resources/images/traffic-sign-shapes.jpeg"],
75
+ ["https://di-uploads-pod16.dealerinspire.com/toyotaofnorthcharlotte/uploads/2020/08/yield-road-sign.jpg"]
76
+ ]
77
 
 
78
 
79
  with gradio.Blocks() as demo:
80
+ gradio.Markdown("# Has Stop Sign or Not?")
81
  gradio.Markdown(
82
+ "This is a simple app that demonstrates how to use an autogluon multimodal"
83
+ "predictor in a gradio space to predict whether an image contains a stop sign. To use,"
84
+ "just upload a photo. The result should be generated automatically."
85
  )
86
 
87
+ image_in = gradio.Image(type="pil", label="Input image", sources=["upload", "webcam"])
 
 
 
88
 
89
+ proba_pretty = gradio.Label(num_top_classes=2, label="Class probabilities")
 
 
 
 
 
90
  prediction_output = gradio.Markdown()
91
 
92
+
93
+ inputs = [image_in]
94
  outputs = [proba_pretty, prediction_output]
95
  for comp in inputs:
96
  comp.change(fn=do_predict, inputs=inputs, outputs=outputs)
 
99
  examples=EXAMPLES,
100
  inputs=inputs,
101
  label="Representative examples",
102
+ examples_per_page=8,
103
  cache_examples=False,
104
  )
105