|
|
import streamlit as st |
|
|
import torch |
|
|
import json |
|
|
import requests |
|
|
import os |
|
|
from torchvision import models, transforms |
|
|
from PIL import Image |
|
|
from urllib.request import urlretrieve |
|
|
|
|
|
|
|
|
BASE_DIR = "/tmp/streamlit_app" |
|
|
|
|
|
|
|
|
os.environ["STREAMLIT_HOME"] = BASE_DIR |
|
|
MODEL_DIR = os.path.join(BASE_DIR, "models") |
|
|
LABELS_DIR = os.path.join(BASE_DIR, "labels") |
|
|
|
|
|
os.makedirs(MODEL_DIR, exist_ok=True) |
|
|
os.makedirs(LABELS_DIR, exist_ok=True) |
|
|
|
|
|
MODEL_FILENAME = os.getenv("MODEL_FILENAME","mobilenetv2.pth") |
|
|
LABELS_FILENAME = os.getenv("LABELS_FILENAME", "labels.json") |
|
|
|
|
|
model_path = os.path.join(MODEL_DIR, MODEL_FILENAME) |
|
|
labels_path = os.path.join(LABELS_DIR, LABELS_FILENAME) |
|
|
|
|
|
MODEL_URL = os.getenv("MODEL_URL","https://download.pytorch.org/models/mobilenet_v2-b0353104.pth") |
|
|
LABELS_URL = os.getenv("LABELS_URL", "https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json") |
|
|
|
|
|
|
|
|
st.set_page_config( |
|
|
page_title="Klasifikasi Gambar (PyTorch) 📸", |
|
|
page_icon="🖼️", |
|
|
layout="centered" |
|
|
) |
|
|
|
|
|
|
|
|
@st.cache_resource |
|
|
def load_model(): |
|
|
"""Memuat model MobileNetV2 dari file lokal atau mengunduh jika belum ada.""" |
|
|
if not os.path.exists(model_path): |
|
|
st.info("Mengunduh model MobileNetV2...") |
|
|
try: |
|
|
urlretrieve(MODEL_URL, model_path) |
|
|
st.success("Model berhasil diunduh.") |
|
|
except Exception as e: |
|
|
st.error(f"Gagal mengunduh model: {str(e)}") |
|
|
return None |
|
|
|
|
|
try: |
|
|
|
|
|
model = models.mobilenet_v2(weights=None) |
|
|
|
|
|
state_dict = torch.load(model_path, map_location=torch.device('cpu')) |
|
|
model.load_state_dict(state_dict) |
|
|
model.eval() |
|
|
return model |
|
|
except Exception as e: |
|
|
st.error(f"Gagal memuat model: {str(e)}") |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
@st.cache_data |
|
|
def load_labels(): |
|
|
"""Memuat label dari file lokal atau mengunduh jika belum ada.""" |
|
|
if not os.path.exists(labels_path): |
|
|
st.info("Mengunduh label ImageNet...") |
|
|
try: |
|
|
response = requests.get(LABELS_URL) |
|
|
response.raise_for_status() |
|
|
with open(labels_path, 'w') as f: |
|
|
json.dump(response.json(), f) |
|
|
st.success("Label berhasil diunduh.") |
|
|
except Exception as e: |
|
|
st.error(f"Gagal mengunduh label: {str(e)}") |
|
|
return None |
|
|
|
|
|
try: |
|
|
with open(labels_path, 'r') as f: |
|
|
labels = json.load(f) |
|
|
return labels |
|
|
except Exception as e: |
|
|
st.error(f"Gagal memuat label: {str(e)}") |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
def preprocess_image(image): |
|
|
"""Melakukan pra-pemrosesan gambar agar sesuai dengan input model PyTorch.""" |
|
|
try: |
|
|
|
|
|
preprocess = transforms.Compose([ |
|
|
transforms.Resize(256), |
|
|
transforms.CenterCrop(224), |
|
|
transforms.ToTensor(), |
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), |
|
|
]) |
|
|
|
|
|
img_t = preprocess(image) |
|
|
batch_t = torch.unsqueeze(img_t, 0) |
|
|
return batch_t |
|
|
except Exception as e: |
|
|
st.error(f"Gagal memproses gambar: {str(e)}") |
|
|
return None |
|
|
|
|
|
def predict(image, model, labels): |
|
|
"""Melakukan prediksi klasifikasi pada gambar.""" |
|
|
try: |
|
|
st.info("🧠 Model sedang menganalisis gambar...") |
|
|
|
|
|
|
|
|
batch_t = preprocess_image(image) |
|
|
if batch_t is None: |
|
|
return None |
|
|
|
|
|
|
|
|
with torch.no_grad(): |
|
|
output = model(batch_t) |
|
|
|
|
|
|
|
|
probabilities = torch.nn.functional.softmax(output[0], dim=0) |
|
|
|
|
|
|
|
|
top3_prob, top3_catid = torch.topk(probabilities, 3) |
|
|
|
|
|
|
|
|
results = [] |
|
|
for i in range(top3_prob.size(0)): |
|
|
class_name = labels[top3_catid[i]] |
|
|
probability = top3_prob[i].item() |
|
|
results.append((class_name, probability)) |
|
|
|
|
|
return results |
|
|
except Exception as e: |
|
|
st.error(f"Gagal melakukan prediksi: {str(e)}") |
|
|
return None |
|
|
|
|
|
|
|
|
|
|
|
st.title("🖼️ Aplikasi Klasifikasi Gambar (PyTorch)") |
|
|
st.write( |
|
|
"Unggah sebuah gambar, dan AI akan mencoba menebak objek apa yang ada di dalamnya! " |
|
|
"Aplikasi ini menggunakan model **MobileNetV2** dari PyTorch." |
|
|
) |
|
|
|
|
|
|
|
|
try: |
|
|
model = load_model() |
|
|
labels = load_labels() |
|
|
|
|
|
if model is None or labels is None: |
|
|
st.error("Aplikasi tidak dapat dijalankan karena gagal memuat model atau label.") |
|
|
st.stop() |
|
|
except Exception as e: |
|
|
st.error(f"Kesalahan saat inisialisasi aplikasi: {str(e)}") |
|
|
st.stop() |
|
|
|
|
|
|
|
|
uploaded_file = st.file_uploader( |
|
|
"Pilih sebuah gambar...", |
|
|
type=["jpg", "jpeg", "png"], |
|
|
help="Format file yang didukung: JPG, JPEG, PNG" |
|
|
) |
|
|
|
|
|
if uploaded_file is not None: |
|
|
try: |
|
|
|
|
|
image = Image.open(uploaded_file).convert('RGB') |
|
|
st.image(image, caption='Gambar yang Anda Unggah', use_column_width=True) |
|
|
|
|
|
|
|
|
if st.button('✨ Klasifikasikan Gambar Ini!'): |
|
|
with st.spinner('Tunggu sebentar...'): |
|
|
|
|
|
predictions = predict(image, model, labels) |
|
|
|
|
|
if predictions is not None: |
|
|
st.subheader("✅ Hasil Prediksi Teratas:") |
|
|
for i, (label, score) in enumerate(predictions): |
|
|
st.write(f"{i+1}. **{label.replace('_', ' ').title()}** - Keyakinan: {score:.2%}") |
|
|
else: |
|
|
st.error("Prediksi gagal. Silakan coba lagi atau unggah gambar lain.") |
|
|
except Exception as e: |
|
|
st.error(f"Kesalahan saat memproses gambar yang diunggah: {str(e)}") |
|
|
|
|
|
st.write("Detail error: Periksa koneksi internet atau format gambar.") |
|
|
|
|
|
st.divider() |
|
|
st.markdown( |
|
|
"Dibuat dengan ❤️ menggunakan [Streamlit](https://streamlit.io), [PyTorch](https://pytorch.org/) & [Hugging Face Spaces](https://huggingface.co/spaces)." |
|
|
) |
|
|
|