Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -1,12 +1,23 @@
|
|
| 1 |
-
|
| 2 |
-
import os, io, zipfile, pathlib, shutil, traceback
|
| 3 |
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
-
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 7 |
from huggingface_hub import hf_hub_download
|
|
|
|
|
|
|
| 8 |
from autogluon.multimodal import MultiModalPredictor
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# =========================
|
| 12 |
# CONFIG
|
|
@@ -48,20 +59,21 @@ def load_mm_predictor():
|
|
| 48 |
if downloaded.endswith(".zip"):
|
| 49 |
with zipfile.ZipFile(downloaded, "r") as zf:
|
| 50 |
zf.extractall(MODEL_DIR)
|
| 51 |
-
# predictor saves as a directory; point to top-level folder
|
| 52 |
-
# If there is exactly one folder inside, use it
|
| 53 |
kids = [p for p in MODEL_DIR.iterdir()]
|
| 54 |
load_path = MODEL_DIR
|
| 55 |
if len(kids) == 1 and kids[0].is_dir():
|
| 56 |
load_path = kids[0]
|
| 57 |
else:
|
| 58 |
-
# .pkl can be loaded from its file path’s parent
|
| 59 |
load_path = downloaded
|
| 60 |
|
| 61 |
predictor = MultiModalPredictor.load(str(load_path))
|
| 62 |
return predictor
|
| 63 |
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
# =========================
|
| 67 |
# Preprocess (for visualization)
|
|
@@ -71,7 +83,6 @@ TARGET_SIZE = 224
|
|
| 71 |
RESIZE_SHORT = 256
|
| 72 |
|
| 73 |
def preprocess_for_viz(pil_img: Image.Image) -> Image.Image:
|
| 74 |
-
# Keep aspect ratio, resize shorter side to 256, then center crop 224x224
|
| 75 |
img = pil_img.convert("RGB")
|
| 76 |
img = ImageOps.exif_transpose(img) # respect orientation EXIF
|
| 77 |
w, h = img.size
|
|
@@ -92,10 +103,14 @@ ALLOWED_EXT = {".jpg", ".jpeg", ".png"}
|
|
| 92 |
MAX_BYTES = 8 * 1024 * 1024 # 8 MB
|
| 93 |
MAX_SIDE = 4096
|
| 94 |
|
| 95 |
-
def validate_image(fileobj
|
| 96 |
if fileobj is None:
|
| 97 |
raise ValueError("Please upload an image.")
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
ext = pathlib.Path(path).suffix.lower()
|
| 100 |
if ext not in ALLOWED_EXT:
|
| 101 |
raise ValueError("Unsupported file type. Please upload a PNG or JPG/JPEG.")
|
|
@@ -112,38 +127,33 @@ def validate_image(fileobj: gr.File) -> str:
|
|
| 112 |
# =========================
|
| 113 |
def infer(image_file, threshold=0.5, tta=False):
|
| 114 |
try:
|
|
|
|
|
|
|
|
|
|
| 115 |
# 1) Validate & open
|
| 116 |
path = validate_image(image_file)
|
| 117 |
orig = Image.open(path).convert("RGB")
|
| 118 |
vis = preprocess_for_viz(orig.copy())
|
| 119 |
|
| 120 |
# 2) Build test dataframe for predictor
|
| 121 |
-
|
| 122 |
-
df = pd.DataFrame([{"image": tmp_path}])
|
| 123 |
|
| 124 |
# 3) Predict proba for lipstick=1 (binary)
|
| 125 |
proba_main = PREDICTOR.predict_proba(df)
|
| 126 |
-
# MultiModalPredictor returns a DataFrame; get prob for positive class if present
|
| 127 |
-
# If the column names are [0,1] or ["0","1"], handle generically:
|
| 128 |
row = proba_main.iloc[0]
|
| 129 |
-
# Try to locate the positive class (1 / "1" / "lipstick")
|
| 130 |
p1 = None
|
| 131 |
for k in [1, "1", "lipstick", "Lipstick", "positive", "True"]:
|
| 132 |
if k in row.index:
|
| 133 |
-
p1 = float(row[k])
|
| 134 |
-
break
|
| 135 |
if p1 is None:
|
| 136 |
-
# fallback: if only two columns, choose the higher prob and assume it's lipstick for display
|
| 137 |
if len(row.index) == 2:
|
| 138 |
p1 = float(max(row.values))
|
| 139 |
else:
|
| 140 |
-
# last resort: if single-prob (e.g., sigmoid), cast to float
|
| 141 |
p1 = float(row.values[0])
|
| 142 |
|
| 143 |
# 4) Optional simple TTA: average with horizontally flipped image prediction
|
| 144 |
if tta:
|
| 145 |
flipped = orig.transpose(Image.FLIP_LEFT_RIGHT)
|
| 146 |
-
# save flipped temporarily
|
| 147 |
flip_tmp = pathlib.Path(path).with_suffix(".flip_tmp.jpg")
|
| 148 |
flipped.save(flip_tmp, format="JPEG", quality=95)
|
| 149 |
df_flip = pd.DataFrame([{"image": str(flip_tmp)}])
|
|
@@ -164,13 +174,11 @@ def infer(image_file, threshold=0.5, tta=False):
|
|
| 164 |
p0 = float(1.0 - p1)
|
| 165 |
decision = "Lipstick" if p1 >= float(threshold) else "No Lipstick"
|
| 166 |
|
| 167 |
-
# 5) Return: original image, preprocessed image, class probabilities, decision text
|
| 168 |
return orig, vis, {"Lipstick": p1, "No Lipstick": p0}, f"Prediction: {decision} (p1={p1:.3f})"
|
| 169 |
|
| 170 |
except Exception as e:
|
| 171 |
tb = traceback.format_exc(limit=1)
|
| 172 |
-
return None, None, {"error": f"{type(e).__name__}: {e}"}, f"Failed: {type(e).__name__}: {e}
|
| 173 |
-
{tb}"
|
| 174 |
|
| 175 |
# =========================
|
| 176 |
# Build examples from dataset (if available)
|
|
@@ -190,17 +198,14 @@ def get_examples(n=3):
|
|
| 190 |
cnt = min(n, len(ds))
|
| 191 |
for i in range(cnt):
|
| 192 |
rec = ds[i]
|
| 193 |
-
# Assume the image column is "image" with PIL Image or path
|
| 194 |
img = rec.get("image", None)
|
| 195 |
if img is None:
|
| 196 |
continue
|
| 197 |
if isinstance(img, Image.Image):
|
| 198 |
-
# save to temp file
|
| 199 |
p = f"example_{i}.jpg"
|
| 200 |
img.convert("RGB").save(p, "JPEG", quality=95)
|
| 201 |
ex.append([p, 0.5, False])
|
| 202 |
else:
|
| 203 |
-
# could be dict/path-like
|
| 204 |
ex.append([img, 0.5, False])
|
| 205 |
return ex
|
| 206 |
|
|
@@ -210,14 +215,8 @@ EXAMPLES = get_examples(3)
|
|
| 210 |
# Gradio UI
|
| 211 |
# =========================
|
| 212 |
with gr.Blocks() as demo:
|
| 213 |
-
gr.Markdown("#
|
| 214 |
-
gr.Markdown(
|
| 215 |
-
"- Upload a face image; the model predicts **Lipstick** vs **No Lipstick**.
|
| 216 |
-
"
|
| 217 |
-
"- Left: original; Right: the **preprocessed** 224×224 view seen by the model.
|
| 218 |
-
"
|
| 219 |
-
"- This is a **teaching demo**; don’t use for real decisions."
|
| 220 |
-
)
|
| 221 |
|
| 222 |
with gr.Row():
|
| 223 |
with gr.Column():
|
|
@@ -240,4 +239,6 @@ with gr.Blocks() as demo:
|
|
| 240 |
cache_examples=False
|
| 241 |
)
|
| 242 |
|
| 243 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, shutil, zipfile, pathlib, traceback, math
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
+
|
| 5 |
import gradio as gr
|
| 6 |
+
from PIL import Image, ImageOps
|
| 7 |
+
|
| 8 |
+
from datasets import load_dataset
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
+
|
| 11 |
+
# AutoGluon (multimodal)
|
| 12 |
from autogluon.multimodal import MultiModalPredictor
|
| 13 |
+
|
| 14 |
+
# ---------------- Settings ----------------
|
| 15 |
+
TITLE = "💄 Lipstick Detection (EfficientNet-B0 via AutoGluon)"
|
| 16 |
+
DESC = (
|
| 17 |
+
"- Upload a face image; the model predicts **Lipstick** vs **No Lipstick**.\n"
|
| 18 |
+
"- Left: original; Right: the **preprocessed** 224×224 view used by the model.\n"
|
| 19 |
+
"- Teaching demo only."
|
| 20 |
+
)
|
| 21 |
|
| 22 |
# =========================
|
| 23 |
# CONFIG
|
|
|
|
| 59 |
if downloaded.endswith(".zip"):
|
| 60 |
with zipfile.ZipFile(downloaded, "r") as zf:
|
| 61 |
zf.extractall(MODEL_DIR)
|
|
|
|
|
|
|
| 62 |
kids = [p for p in MODEL_DIR.iterdir()]
|
| 63 |
load_path = MODEL_DIR
|
| 64 |
if len(kids) == 1 and kids[0].is_dir():
|
| 65 |
load_path = kids[0]
|
| 66 |
else:
|
|
|
|
| 67 |
load_path = downloaded
|
| 68 |
|
| 69 |
predictor = MultiModalPredictor.load(str(load_path))
|
| 70 |
return predictor
|
| 71 |
|
| 72 |
+
try:
|
| 73 |
+
PREDICTOR = load_mm_predictor()
|
| 74 |
+
except Exception as e:
|
| 75 |
+
PREDICTOR = None
|
| 76 |
+
print("Failed to load predictor:", e)
|
| 77 |
|
| 78 |
# =========================
|
| 79 |
# Preprocess (for visualization)
|
|
|
|
| 83 |
RESIZE_SHORT = 256
|
| 84 |
|
| 85 |
def preprocess_for_viz(pil_img: Image.Image) -> Image.Image:
|
|
|
|
| 86 |
img = pil_img.convert("RGB")
|
| 87 |
img = ImageOps.exif_transpose(img) # respect orientation EXIF
|
| 88 |
w, h = img.size
|
|
|
|
| 103 |
MAX_BYTES = 8 * 1024 * 1024 # 8 MB
|
| 104 |
MAX_SIDE = 4096
|
| 105 |
|
| 106 |
+
def validate_image(fileobj) -> str:
|
| 107 |
if fileobj is None:
|
| 108 |
raise ValueError("Please upload an image.")
|
| 109 |
+
# gr.Image with type="filepath" returns a str path in Spaces
|
| 110 |
+
path = getattr(fileobj, "name", fileobj)
|
| 111 |
+
if not isinstance(path, str):
|
| 112 |
+
path = str(path)
|
| 113 |
+
|
| 114 |
ext = pathlib.Path(path).suffix.lower()
|
| 115 |
if ext not in ALLOWED_EXT:
|
| 116 |
raise ValueError("Unsupported file type. Please upload a PNG or JPG/JPEG.")
|
|
|
|
| 127 |
# =========================
|
| 128 |
def infer(image_file, threshold=0.5, tta=False):
|
| 129 |
try:
|
| 130 |
+
if PREDICTOR is None:
|
| 131 |
+
raise RuntimeError("Model failed to load. Check model artifacts and environment.")
|
| 132 |
+
|
| 133 |
# 1) Validate & open
|
| 134 |
path = validate_image(image_file)
|
| 135 |
orig = Image.open(path).convert("RGB")
|
| 136 |
vis = preprocess_for_viz(orig.copy())
|
| 137 |
|
| 138 |
# 2) Build test dataframe for predictor
|
| 139 |
+
df = pd.DataFrame([{"image": path}])
|
|
|
|
| 140 |
|
| 141 |
# 3) Predict proba for lipstick=1 (binary)
|
| 142 |
proba_main = PREDICTOR.predict_proba(df)
|
|
|
|
|
|
|
| 143 |
row = proba_main.iloc[0]
|
|
|
|
| 144 |
p1 = None
|
| 145 |
for k in [1, "1", "lipstick", "Lipstick", "positive", "True"]:
|
| 146 |
if k in row.index:
|
| 147 |
+
p1 = float(row[k]); break
|
|
|
|
| 148 |
if p1 is None:
|
|
|
|
| 149 |
if len(row.index) == 2:
|
| 150 |
p1 = float(max(row.values))
|
| 151 |
else:
|
|
|
|
| 152 |
p1 = float(row.values[0])
|
| 153 |
|
| 154 |
# 4) Optional simple TTA: average with horizontally flipped image prediction
|
| 155 |
if tta:
|
| 156 |
flipped = orig.transpose(Image.FLIP_LEFT_RIGHT)
|
|
|
|
| 157 |
flip_tmp = pathlib.Path(path).with_suffix(".flip_tmp.jpg")
|
| 158 |
flipped.save(flip_tmp, format="JPEG", quality=95)
|
| 159 |
df_flip = pd.DataFrame([{"image": str(flip_tmp)}])
|
|
|
|
| 174 |
p0 = float(1.0 - p1)
|
| 175 |
decision = "Lipstick" if p1 >= float(threshold) else "No Lipstick"
|
| 176 |
|
|
|
|
| 177 |
return orig, vis, {"Lipstick": p1, "No Lipstick": p0}, f"Prediction: {decision} (p1={p1:.3f})"
|
| 178 |
|
| 179 |
except Exception as e:
|
| 180 |
tb = traceback.format_exc(limit=1)
|
| 181 |
+
return None, None, {"error": f"{type(e).__name__}: {e}"}, f"Failed: {type(e).__name__}: {e}\n{tb}"
|
|
|
|
| 182 |
|
| 183 |
# =========================
|
| 184 |
# Build examples from dataset (if available)
|
|
|
|
| 198 |
cnt = min(n, len(ds))
|
| 199 |
for i in range(cnt):
|
| 200 |
rec = ds[i]
|
|
|
|
| 201 |
img = rec.get("image", None)
|
| 202 |
if img is None:
|
| 203 |
continue
|
| 204 |
if isinstance(img, Image.Image):
|
|
|
|
| 205 |
p = f"example_{i}.jpg"
|
| 206 |
img.convert("RGB").save(p, "JPEG", quality=95)
|
| 207 |
ex.append([p, 0.5, False])
|
| 208 |
else:
|
|
|
|
| 209 |
ex.append([img, 0.5, False])
|
| 210 |
return ex
|
| 211 |
|
|
|
|
| 215 |
# Gradio UI
|
| 216 |
# =========================
|
| 217 |
with gr.Blocks() as demo:
|
| 218 |
+
gr.Markdown(f"# {TITLE}")
|
| 219 |
+
gr.Markdown(DESC)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
with gr.Row():
|
| 222 |
with gr.Column():
|
|
|
|
| 239 |
cache_examples=False
|
| 240 |
)
|
| 241 |
|
| 242 |
+
# In Spaces, share=True is not required; leaving default.
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
demo.launch()
|