Spaces:
Sleeping
Sleeping
Download src/streamlit_app.py from EnYa32/Rice_Classifier_ResNet50: direct link, hf CLI and curl.
- Browser
- Download file 4.34 kB
-
https://huggingface.co/spaces/EnYa32/Rice_Classifier_ResNet50/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/EnYa32/Rice_Classifier_ResNet50/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/EnYa32/Rice_Classifier_ResNet50/resolve/main/src/streamlit_app.py
4.34 kB
| # app_rice_resnet50.py | |
| import streamlit as st | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image | |
| import tensorflow as tf | |
| from tensorflow.keras.applications.resnet50 import preprocess_input | |
| # ----------------- SETTINGS ----------------- | |
| # Falls das Modell im Root liegt, nimm: "./best_rice_resnet50.keras" | |
| MODEL_PATH = "src/best_rice_resnet50.keras" | |
| IMG_SIZE = (224, 224) | |
| CLASS_NAMES = [ | |
| "Arborio", | |
| "Basmati", | |
| "Ipsala", | |
| "Jasmine", | |
| "Karacadag", | |
| ] | |
| # ----------------- MODEL LOADING ----------------- | |
| def load_resnet_model(): | |
| try: | |
| model = tf.keras.models.load_model(MODEL_PATH, compile=False) | |
| return model | |
| except Exception as e: | |
| st.error(f"Error loading model: {e}") | |
| return None | |
| def preprocess_image(image: Image.Image) -> np.ndarray: | |
| """Resize image and apply ResNet50 preprocessing.""" | |
| img = image.convert("RGB") | |
| img = img.resize(IMG_SIZE) | |
| img_array = np.array(img).astype("float32") | |
| img_array = preprocess_input(img_array) | |
| img_array = np.expand_dims(img_array, axis=0) | |
| return img_array | |
| def predict_image(model, image_array: np.ndarray): | |
| """Safe prediction with Top-3; robust gegen Längen-Mismatch.""" | |
| preds = model.predict(image_array, verbose=0)[0] | |
| probs = tf.nn.softmax(preds).numpy() | |
| n_model = len(probs) | |
| n_labels = len(CLASS_NAMES) | |
| n = min(n_model, n_labels) | |
| # Hauptklasse (nur im Bereich [0, n)) | |
| main_idx = int(np.argmax(probs[:n])) | |
| pred_class = CLASS_NAMES[main_idx] | |
| pred_conf = float(probs[main_idx]) | |
| # Top-k (hier 3) nur im gültigen Bereich | |
| k = min(3, n) | |
| topk_idx = np.argsort(probs[:n])[-k:][::-1] | |
| topk = [(CLASS_NAMES[i], float(probs[i])) for i in topk_idx] | |
| # Nur die ersten n Wahrscheinlichkeiten zurückgeben | |
| return pred_class, pred_conf, probs[:n], topk, n_model, n_labels | |
| # ----------------- PAGE CONFIG ----------------- | |
| st.set_page_config( | |
| page_title="Rice Classifier – ResNet50 (Transfer Learning)", | |
| page_icon="🌾", | |
| layout="wide", | |
| ) | |
| # ----------------- SIDEBAR ----------------- | |
| st.sidebar.title("🌾 Rice ResNet50 Classifier") | |
| st.sidebar.write( | |
| "This app uses a ResNet50 transfer learning model to classify rice grains." | |
| ) | |
| st.sidebar.subheader("Rice classes") | |
| for idx, name in enumerate(CLASS_NAMES): | |
| st.sidebar.write(f"- **{idx}** → {name}") | |
| st.sidebar.markdown("---") | |
| st.sidebar.caption("Author: Enes Yamac") | |
| # ----------------- MAIN PAGE ----------------- | |
| st.title("🌾 Rice Classifier – ResNet50 (Transfer Learning)") | |
| st.write("Upload a rice grain image. The model will predict the rice type and show top-3 results.") | |
| uploaded_file = st.file_uploader( | |
| "Upload a rice image (JPG or PNG)", | |
| type=["jpg", "jpeg", "png"], | |
| ) | |
| if uploaded_file is not None: | |
| image = Image.open(uploaded_file) | |
| col1, col2 = st.columns([1, 1]) | |
| with col1: | |
| st.subheader("Uploaded image") | |
| st.image(image, width=500) | |
| with st.spinner("Loading ResNet50 model and making prediction..."): | |
| model = load_resnet_model() | |
| if model is not None: | |
| img_array = preprocess_image(image) | |
| pred_class, pred_conf, probs, top3, n_model, n_labels = predict_image( | |
| model, img_array | |
| ) | |
| # kurze Warnung, falls Modell/Labels nicht exakt matchen | |
| if n_model != n_labels: | |
| st.warning( | |
| f"Model outputs {n_model} classes, CLASS_NAMES has {n_labels}. " | |
| f"Only the first {min(n_model, n_labels)} are shown." | |
| ) | |
| with col2: | |
| st.subheader("Prediction") | |
| st.markdown(f"**Predicted class:** `{pred_class}`") | |
| st.markdown(f"**Confidence:** `{pred_conf:.2%}`") | |
| st.subheader("Top-3 predictions") | |
| for name, p in top3: | |
| st.write(f"- {name}: {p:.2%}") | |
| st.subheader("Class probabilities") | |
| df = pd.DataFrame( | |
| {"class": CLASS_NAMES[: len(probs)], "probability": probs} | |
| ).set_index("class") | |
| st.bar_chart(df) | |
| with st.expander("Show probabilities as text"): | |
| for name, p in zip(CLASS_NAMES[: len(probs)], probs): | |
| st.write(f"- {name}: {p:.2%}") | |
| else: | |
| st.info("Please upload a rice image to get a prediction.") |