Spaces:
Running on Zero
Running on Zero
File size: 2,679 Bytes
a758f34 21c4e6f 61e92ba a758f34 1919f0e a758f34 21c4e6f a758f34 1919f0e a758f34 21c4e6f 1919f0e 21c4e6f 61e92ba 21c4e6f a758f34 21c4e6f a758f34 61e92ba 1919f0e b1f2da8 3d984ea 61e92ba 21c4e6f a758f34 1919f0e 21c4e6f 1919f0e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | import json
import os
from pathlib import Path
import gradio as gr
import spaces
import torch
from PIL import Image
from torchvision import models, transforms
MODEL_DIR = Path(os.environ.get("MODEL_DIR", "model"))
MEAN = (0.485, 0.456, 0.406)
STD = (0.229, 0.224, 0.225)
def load_model():
metadata_path = MODEL_DIR / "classes.json"
weights_path = MODEL_DIR / "model.pt"
if not metadata_path.is_file() or not weights_path.is_file():
raise RuntimeError(
f"Missing model files; expected {weights_path} and {metadata_path}"
)
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
classes = metadata.get("classes")
image_size = metadata.get("image_size")
if (
not isinstance(classes, list)
or len(classes) != 2
or set(classes) != {"clear", "litter"}
or not isinstance(image_size, int)
or image_size < 1
):
raise RuntimeError("Invalid classes.json metadata")
classifier = models.mobilenet_v3_small(weights=None)
classifier.classifier[3] = torch.nn.Linear(
classifier.classifier[3].in_features, len(classes)
)
classifier.load_state_dict(
torch.load(weights_path, map_location="cpu", weights_only=True)
)
classifier.eval()
classifier.to("cuda")
return classifier, classes, image_size
model, classes, image_size = load_model()
preprocess = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(image_size),
transforms.ToTensor(),
transforms.Normalize(MEAN, STD),
]
)
@spaces.GPU(duration=10)
def classify(image: Image.Image):
if image is None:
raise gr.Error("Pilih gambar terlebih dahulu.")
tensor = preprocess(image.convert("RGB")).unsqueeze(0)
with torch.inference_mode():
probabilities = torch.softmax(model(tensor.to("cuda")), dim=1)[0].cpu()
best_index = int(probabilities.argmax().item())
label = classes[best_index]
return {
"label": label,
"confidence": float(probabilities[best_index].item()),
"ai_trash_detected": label == "litter",
}
with gr.Blocks(title="SMART POLDER-S3 Inference") as demo:
gr.Markdown("# SMART POLDER-S3 Image Classification")
gr.Markdown("Unggah gambar untuk mengklasifikasikan `clear` atau `litter`.")
image = gr.Image(type="pil", label="Gambar")
result = gr.JSON(label="Hasil prediksi")
predict_button = gr.Button("Klasifikasikan")
predict_button.click(classify, inputs=image, outputs=result)
if __name__ == "__main__":
demo.launch(
server_name="0.0.0.0",
server_port=int(os.environ.get("PORT", "7860")),
)
|