ddecosmo commited on
Commit
a439148
·
verified ·
1 Parent(s): 2aaabb6

Upload 6 files

Browse files
Files changed (6) hide show
  1. duo_1.jpg +0 -0
  2. duo_2.jpg +0 -0
  3. image_model.py +164 -0
  4. no_duo_1.jpg +0 -0
  5. no_duo_2.jpg +0 -0
  6. requirements (1).txt +5 -0
duo_1.jpg ADDED
duo_2.jpg ADDED
image_model.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """image_model.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1SRq7ZIsAwqDYyV4UWM9SZJuRYJvQe59o
8
+ """
9
+
10
+ !pip install autogluon.multimodal --quiet
11
+
12
+ import os # For reading environment variables
13
+ import shutil # For directory cleanup
14
+ import zipfile # For extracting model archives
15
+ import pathlib # For path manipulations
16
+ import tempfile # For creating temporary files/directories
17
+
18
+ import gradio # For interactive UI
19
+ import pandas # For tabular data handling
20
+ import PIL.Image # For image I/O
21
+
22
+ import huggingface_hub # For downloading model assets
23
+ import autogluon.multimodal # For loading AutoGluon image classifier
24
+
25
+ # Hardcoded Hub model (native zip)
26
+ MODEL_REPO_ID = "SebastianAndreu/2025-24679-HW1-Part2-image-autogluon-predictor"
27
+ ZIP_FILENAME = "autogluon_image_predictor_dir.zip"
28
+ HF_TOKEN = os.getenv("HF_TOKEN", None)
29
+
30
+ # Local cache/extract dirs
31
+ CACHE_DIR = pathlib.Path("hf_assets")
32
+ EXTRACT_DIR = CACHE_DIR / "predictor_native"
33
+
34
+ # Download & load the native predictor
35
+ def _prepare_predictor_dir() -> str:
36
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
37
+ local_zip = huggingface_hub.hf_hub_download(
38
+ repo_id=MODEL_REPO_ID,
39
+ filename=ZIP_FILENAME,
40
+ repo_type="model",
41
+ token=HF_TOKEN,
42
+ local_dir=str(CACHE_DIR),
43
+ local_dir_use_symlinks=False,
44
+ )
45
+ if EXTRACT_DIR.exists():
46
+ shutil.rmtree(EXTRACT_DIR)
47
+ EXTRACT_DIR.mkdir(parents=True, exist_ok=True)
48
+ with zipfile.ZipFile(local_zip, "r") as zf:
49
+ zf.extractall(str(EXTRACT_DIR))
50
+ contents = list(EXTRACT_DIR.iterdir())
51
+ predictor_root = contents[0] if (len(contents) == 1 and contents[0].is_dir()) else EXTRACT_DIR
52
+ return str(predictor_root)
53
+
54
+ PREDICTOR_DIR = _prepare_predictor_dir()
55
+ PREDICTOR = autogluon.multimodal.MultiModalPredictor.load(PREDICTOR_DIR)
56
+
57
+ # Explicit class labels (edit copy as desired)
58
+ CLASS_LABELS = {0: "No Duo :(", 1: "DUO :-)"}
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: "No Duo :(", 1: "DUO :-)"})
86
+ row = proba_df.iloc[0]
87
+
88
+ # For pretty ranked dict expected by gr.Label
89
+ pretty_dict = {
90
+ "No Duo :(": float(row.get("No Duo :(", 0.0)),
91
+ "DUO :-)": float(row.get("DUO :-)", 0.0)),
92
+ }
93
+
94
+ # Calculate confidence interval (a simple representation for demonstration)
95
+ # This is not a statistically rigorous CI, but rather a representation of the probability spread.
96
+ confidence_info = f"No Duo Probability: {pretty_dict['No Duo :(']:.2f}, DUO Probability: {pretty_dict['DUO :-)']:.2f}"
97
+
98
+ return pretty_dict, confidence_info
99
+
100
+ EXAMPLES = [
101
+ ]
102
+
103
+ # Gradio UI
104
+ with gradio.Blocks() as demo:
105
+
106
+ # Provide an introduction
107
+ gradio.Markdown("# Is Duo Here?")
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
+ # Gradio UI
133
+ with gradio.Blocks() as demo:
134
+
135
+ # Provide an introduction
136
+ gradio.Markdown("# Is Duo Here?")
137
+ gradio.Markdown("""
138
+ This is a simple app that demonstrates how to use an autogluon multimodal
139
+ predictor in a gradio space to predict the contents of a picture. To use,
140
+ just upload a photo. The result should be generated automatically.
141
+ """)
142
+
143
+ # Interface for the incoming image
144
+ image_in = gradio.Image(type="pil", label="Input image", sources=["upload", "webcam"])
145
+
146
+ # Interface elements to show htte result and probabilities
147
+ proba_pretty = gradio.Label(num_top_classes=2, label="Class probabilities")
148
+ confidence_output = gradio.Textbox(label="Confidence Information")
149
+
150
+ # Whenever a new image is uploaded, update the result
151
+ image_in.change(fn=do_predict, inputs=[image_in], outputs=[proba_pretty, confidence_output])
152
+
153
+ # For clickable example images
154
+ gradio.Examples(
155
+ examples=EXAMPLES,
156
+ inputs=[image_in],
157
+ label="Representative examples",
158
+ examples_per_page=8,
159
+ cache_examples=False,
160
+ )
161
+
162
+ # Launch here
163
+ if __name__ == "__main__":
164
+ demo.launch()
no_duo_1.jpg ADDED
no_duo_2.jpg ADDED
requirements (1).txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ autogluon.multimodal
2
+ gradio
3
+ pandas
4
+ Pillow
5
+ huggingface_hub