zacCMU commited on
Commit
6901f02
·
verified ·
1 Parent(s): 98b8a74

Update app.py from Colab

Browse files
Files changed (1) hide show
  1. app.py +78 -85
app.py CHANGED
@@ -1,54 +1,47 @@
1
  #this was in part generated with gemini llm
2
- import os  # For reading environment variables
3
- import shutil  # For directory cleanup
4
- import zipfile  # For extracting model archives
5
- import pathlib  # For path manipulations
6
- import tempfile  # For creating temporary files/directories
7
-
8
- import gradio  # For interactive UI
9
- import pandas  # For tabular data handling
10
  import PIL.Image # For image I/O
11
 
12
  import huggingface_hub # For downloading model assets
13
- import autogluon.multimodal  # For loading AutoGluon image classifiera
14
  from huggingface_hub import HfApi
15
 
16
- # 1. Initialize the API object (optional for download, but kept)
17
  # Hardcoded Hub model (native zip)
18
  MODEL_REPO_ID = "FaiyazAzam/24679-image-autolguon-predictor"
19
- ZIP_FILENAME  = "autogluon_image_predictor_dir.zip"
20
  api = HfApi()
21
 
22
  # Local cache/extract dirs
23
- CACHE_DIR   = pathlib.Path("hf_assets")
24
  EXTRACT_DIR = CACHE_DIR / "predictor_native"
25
 
26
  # Download & load the native predictor
27
  def _prepare_predictor_dir() -> str:
28
-     CACHE_DIR.mkdir(parents=True, exist_ok=True)
29
-    
30
-     # *** MODIFICATION HERE ***
31
-     # Removed 'token=HF_TOKEN' and used 'token=True' (which is the default)
32
-     # 'token=True' tells huggingface_hub to automatically look for the token
33
-     # in the environment variables (like HF_TOKEN in a Space Secret).
34
-     local_zip = huggingface_hub.hf_hub_download(
35
-         repo_id=MODEL_REPO_ID,
36
-         filename=ZIP_FILENAME,
37
-         repo_type="model",
38
-         token=True, # Use default token detection (e.g., HF_TOKEN env var)
39
-         local_dir=str(CACHE_DIR),
40
-         local_dir_use_symlinks=False,
41
-     )
42
-     # *** END MODIFICATION ***
43
-
44
-     if EXTRACT_DIR.exists():
45
-         shutil.rmtree(EXTRACT_DIR)
46
-     EXTRACT_DIR.mkdir(parents=True, exist_ok=True)
47
-     with zipfile.ZipFile(local_zip, "r") as zf:
48
-         zf.extractall(str(EXTRACT_DIR))
49
-     contents = list(EXTRACT_DIR.iterdir())
50
-     predictor_root = contents[0] if (len(contents) == 1 and contents[0].is_dir()) else EXTRACT_DIR
51
-     return str(predictor_root)
52
 
53
  PREDICTOR_DIR = _prepare_predictor_dir()
54
  PREDICTOR = autogluon.multimodal.MultiModalPredictor.load(PREDICTOR_DIR)
@@ -59,75 +52,75 @@ CLASS_LABELS = {0: "Pen", 1: "Toy"}
59
 
60
  # Helper to map model class -> human label
61
  def _human_label(c):
62
-     try:
63
-         ci = int(c)
64
-         return CLASS_LABELS.get(ci, str(c))
65
-     except Exception:
66
-         return CLASS_LABELS.get(c, str(c))
67
 
68
  # Do the prediction!
69
  def do_predict(pil_img: PIL.Image.Image):
70
-     # Make sure there's actually an image to work with
71
-     if pil_img is None:
72
-         return "No image provided.", {}, pandas.DataFrame(columns=["Predicted label", "Confidence (%)"])
73
 
74
-     # IF we have something to work with, save it and prepare the input
75
-     tmpdir = pathlib.Path(tempfile.mkdtemp())
76
-     img_path = tmpdir / "input.png"
77
-     pil_img.save(img_path)
78
 
79
-     df = pandas.DataFrame({"image": [str(img_path)]})  # For AutoGluon expected input format
80
 
81
-     # For class probabilities
82
-     proba_df = PREDICTOR.predict_proba(df)
83
 
84
-     # For user-friendly column names
85
-     proba_df = proba_df.rename(columns={0: "Pen (0)", 1: "Toy (1)"})
86
-     row = proba_df.iloc[0]
87
 
88
-     # For pretty ranked dict expected by gr.Label
89
-     pretty_dict = {
90
-         "Pen": float(row.get("Pen (0)", 0.0)),
91
-         "Toy": float(row.get("Toy (1)", 0.0)),
92
-     }
93
 
94
-     return pretty_dict
95
 
96
  # Representative example images! These can be local or links.
97
  EXAMPLES = [
98
-     ["https://www.penboutique.com/cdn/shop/articles/IMG_6759.jpg?v=1701974210&width=1920"],
99
-     ["https://media.officedepot.com/images/f_auto,q_auto,e_sharpen,h_450/products/790761/790761_p_pilot_g_2_retractable_gel_pens/790761"],
100
-     ["https://i5.walmartimages.com/seo/Disney-Pixar-Toy-Story-True-Talkers-Woody-Figure-with-15-Phrases_8c8c4a17-fb26-4f97-a284-1315c48c18ca.c35d5f2d8b932a490db9bb3f40977220.jpeg"]
101
  ]
102
 
103
  # Gradio UI
104
  with gradio.Blocks() as demo:
105
 
106
-     # Provide an introduction
107
-     gradio.Markdown("# Pen or Toy?")
108
-     gradio.Markdown("""
109
-     This is a simple app that demonstrates how to use an autogluon multimodal
110
-     predictor in a gradio space to predict the contents of a picture. To use,
111
-     just upload a photo. The result should be generated automatically.
112
-     """)
113
 
114
-     # Interface for the incoming image
115
-     image_in = gradio.Image(type="pil", label="Input image", sources=["upload", "webcam"])
116
 
117
-     # Interface elements to show htte result and probabilities
118
-     proba_pretty = gradio.Label(num_top_classes=2, label="Class probabilities")
119
 
120
-     # Whenever a new image is uploaded, update the result
121
-     image_in.change(fn=do_predict, inputs=[image_in], outputs=[proba_pretty])
122
 
123
-       # For clickable example images
124
-     gradio.Examples(
125
-         examples=EXAMPLES,
126
-         inputs=[image_in],
127
-         label="Representative examples",
128
-         examples_per_page=8,
129
-         cache_examples=False,
130
-     )
131
 
132
  if __name__ == "__main__":
133
-     demo.launch()
 
1
  #this was in part generated with gemini llm
2
+ import os # For reading environment variables
3
+ import shutil # For directory cleanup
4
+ import zipfile # For extracting model archives
5
+ import pathlib # For path manipulations
6
+ import tempfile # For creating temporary files/directories
7
+
8
+ import gradio # For interactive UI
9
+ import pandas # For tabular data handling
10
  import PIL.Image # For image I/O
11
 
12
  import huggingface_hub # For downloading model assets
13
+ import autogluon.multimodal # For loading AutoGluon image classifiera
14
  from huggingface_hub import HfApi
15
 
16
+ # 1. Initialize the API object
17
  # Hardcoded Hub model (native zip)
18
  MODEL_REPO_ID = "FaiyazAzam/24679-image-autolguon-predictor"
19
+ ZIP_FILENAME = "autogluon_image_predictor_dir.zip"
20
  api = HfApi()
21
 
22
  # Local cache/extract dirs
23
+ CACHE_DIR = pathlib.Path("hf_assets")
24
  EXTRACT_DIR = CACHE_DIR / "predictor_native"
25
 
26
  # Download & load the native predictor
27
  def _prepare_predictor_dir() -> str:
28
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
29
+ local_zip = huggingface_hub.hf_hub_download(
30
+ repo_id=MODEL_REPO_ID,
31
+ filename=ZIP_FILENAME,
32
+ repo_type="model",
33
+ token=True,
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, exist_ok=True)
40
+ with zipfile.ZipFile(local_zip, "r") as zf:
41
+ zf.extractall(str(EXTRACT_DIR))
42
+ contents = list(EXTRACT_DIR.iterdir())
43
+ predictor_root = contents[0] if (len(contents) == 1 and contents[0].is_dir()) else EXTRACT_DIR
44
+ return str(predictor_root)
 
 
 
 
 
 
 
45
 
46
  PREDICTOR_DIR = _prepare_predictor_dir()
47
  PREDICTOR = autogluon.multimodal.MultiModalPredictor.load(PREDICTOR_DIR)
 
52
 
53
  # Helper to map model class -> human label
54
  def _human_label(c):
55
+ try:
56
+ ci = int(c)
57
+ return CLASS_LABELS.get(ci, str(c))
58
+ except Exception:
59
+ return CLASS_LABELS.get(c, str(c))
60
 
61
  # Do the prediction!
62
  def do_predict(pil_img: PIL.Image.Image):
63
+ # Make sure there's actually an image to work with
64
+ if pil_img is None:
65
+ return "No image provided.", {}, pandas.DataFrame(columns=["Predicted label", "Confidence (%)"])
66
 
67
+ # IF we have something to work with, save it and prepare the input
68
+ tmpdir = pathlib.Path(tempfile.mkdtemp())
69
+ img_path = tmpdir / "input.png"
70
+ pil_img.save(img_path)
71
 
72
+ df = pandas.DataFrame({"image": [str(img_path)]}) # For AutoGluon expected input format
73
 
74
+ # For class probabilities
75
+ proba_df = PREDICTOR.predict_proba(df)
76
 
77
+ # For user-friendly column names
78
+ proba_df = proba_df.rename(columns={0: "Pen (0)", 1: "Toy (1)"})
79
+ row = proba_df.iloc[0]
80
 
81
+ # For pretty ranked dict expected by gr.Label
82
+ pretty_dict = {
83
+ "Pen": float(row.get("Pen (0)", 0.0)),
84
+ "Toy": float(row.get("Toy (1)", 0.0)),
85
+ }
86
 
87
+ return pretty_dict
88
 
89
  # Representative example images! These can be local or links.
90
  EXAMPLES = [
91
+ ["https://www.penboutique.com/cdn/shop/articles/IMG_6759.jpg?v=1701974210&width=1920"],
92
+ ["https://media.officedepot.com/images/f_auto,q_auto,e_sharpen,h_450/products/790761/790761_p_pilot_g_2_retractable_gel_pens/790761"],
93
+ ["https://i5.walmartimages.com/seo/Disney-Pixar-Toy-Story-True-Talkers-Woody-Figure-with-15-Phrases_8c8c4a17-fb26-4f97-a284-1315c48c18ca.c35d5f2d8b932a490db9bb3f40977220.jpeg"]
94
  ]
95
 
96
  # Gradio UI
97
  with gradio.Blocks() as demo:
98
 
99
+ # Provide an introduction
100
+ gradio.Markdown("# Pen or Toy?")
101
+ gradio.Markdown("""
102
+ This is a simple app that demonstrates how to use an autogluon multimodal
103
+ predictor in a gradio space to predict the contents of a picture. To use,
104
+ just upload a photo. The result should be generated automatically.
105
+ """)
106
 
107
+ # Interface for the incoming image
108
+ image_in = gradio.Image(type="pil", label="Input image", sources=["upload", "webcam"])
109
 
110
+ # Interface elements to show htte result and probabilities
111
+ proba_pretty = gradio.Label(num_top_classes=2, label="Class probabilities")
112
 
113
+ # Whenever a new image is uploaded, update the result
114
+ image_in.change(fn=do_predict, inputs=[image_in], outputs=[proba_pretty])
115
 
116
+ # For clickable example images
117
+ gradio.Examples(
118
+ examples=EXAMPLES,
119
+ inputs=[image_in],
120
+ label="Representative examples",
121
+ examples_per_page=8,
122
+ cache_examples=False,
123
+ )
124
 
125
  if __name__ == "__main__":
126
+ demo.launch()