Spaces:
Sleeping
Sleeping
Update app.py from Colab
Browse files
app.py
CHANGED
|
@@ -1,54 +1,47 @@
|
|
| 1 |
#this was in part generated with gemini llm
|
| 2 |
-
import os
|
| 3 |
-
import shutil
|
| 4 |
-
import zipfile
|
| 5 |
-
import pathlib
|
| 6 |
-
import tempfile
|
| 7 |
-
|
| 8 |
-
import gradio
|
| 9 |
-
import pandas
|
| 10 |
import PIL.Image # For image I/O
|
| 11 |
|
| 12 |
import huggingface_hub # For downloading model assets
|
| 13 |
-
import autogluon.multimodal
|
| 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
|
| 20 |
api = HfApi()
|
| 21 |
|
| 22 |
# Local cache/extract dirs
|
| 23 |
-
CACHE_DIR
|
| 24 |
EXTRACT_DIR = CACHE_DIR / "predictor_native"
|
| 25 |
|
| 26 |
# Download & load the native predictor
|
| 27 |
def _prepare_predictor_dir() -> str:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 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 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
|
| 68 |
# Do the prediction!
|
| 69 |
def do_predict(pil_img: PIL.Image.Image):
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
|
| 79 |
-
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
| 94 |
-
|
| 95 |
|
| 96 |
# Representative example images! These can be local or links.
|
| 97 |
EXAMPLES = [
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
]
|
| 102 |
|
| 103 |
# Gradio UI
|
| 104 |
with gradio.Blocks() as demo:
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
|
| 120 |
-
|
| 121 |
-
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
|
| 132 |
if __name__ == "__main__":
|
| 133 |
-
|
|
|
|
| 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()
|