Spaces:
Sleeping
Sleeping
File size: 5,559 Bytes
d10791c |
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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 18 09:07:10 2025
@author: THYAGHARAJAN
"""
import streamlit as st
import tensorflow as tf
import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download, list_repo_files
import os
os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"
os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
# ------------------------------
# CONFIGURATION
# ------------------------------
REPO_ID = "kkthyagharajan/KKT-HF-TransferLearning-Models" # <<< CHANGE THIS
IMG_SIZE = (300, 300)
st.set_page_config(page_title="Insect Classifier", layout="wide")
# Cache dictionaries
@st.cache_resource
def load_tf_model(model_path):
return tf.keras.models.load_model(model_path, compile=False)
@st.cache_resource
def load_class_names(model_dir):
class_file = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/class_names.txt")
with open(class_file, "r") as f:
return [x.strip() for x in f.read().split(",")]
# ----------------------------------
# Helper Functions
# ----------------------------------
def get_available_models():
"""Return mapping: model_dir β model file (.h5 preferred over .keras)."""
files = list_repo_files(REPO_ID)
models = {}
# Prefer .h5
for file in files:
if file.endswith(".h5"):
dir = file.split("/")[0]
models[dir] = file
# Use .keras only if .h5 missing
for file in files:
if file.endswith(".keras"):
dir = file.split("/")[0]
if dir not in models:
models[dir] = file
return models
def get_sample_images(model_dir):
"""List sample images inside model_dir/sample_images/"""
files = list_repo_files(REPO_ID)
sample_imgs = []
prefix = f"{model_dir}/sample_images/"
for f in files:
if f.startswith(prefix) and f.lower().endswith((".jpg", ".jpeg", ".png")):
sample_imgs.append(f.replace(prefix, ""))
return sample_imgs
def load_sample_image(model_dir, image_name):
"""Download sample image."""
path = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/sample_images/{image_name}")
return Image.open(path)
def preprocess(img):
img = img.resize(IMG_SIZE)
arr = np.array(img) / 255.0
arr = arr.reshape(1, IMG_SIZE[0], IMG_SIZE[1], 3)
return arr
# ----------------------------------
# UI Layout
# ----------------------------------
st.title("π¦ Insect Classification System")
st.markdown("""
### A Multi-Model Deep Learning Web App
Developed by **Dr. Thyagharajan K K, Professor & Dean (Research)**
RMD Engineering College
""")
col1, col2 = st.columns([1, 1])
# ----------------------------------
# LEFT PANEL
# ----------------------------------
with col1:
st.subheader("1οΈβ£ Select Model")
models = get_available_models()
if not models:
st.error("No models found in HuggingFace repo.")
st.stop()
model_choice = st.selectbox("Choose a model", list(models.keys()))
st.subheader("2οΈβ£ Choose Image Source")
input_mode = st.radio(
"Select input method:",
["Upload Image", "Use Sample Image", "Live Camera"]
)
input_image = None
# Upload
if input_mode == "Upload Image":
uploaded = st.file_uploader("Upload image", type=["jpg", "jpeg", "png"])
if uploaded:
input_image = Image.open(uploaded)
# Sample Images
elif input_mode == "Use Sample Image":
sample_images = get_sample_images(model_choice)
if sample_images:
selected_sample = st.selectbox("Choose sample image", sample_images)
if selected_sample:
input_image = load_sample_image(model_choice, selected_sample)
st.image(input_image, caption="Sample Image", width=250)
else:
st.warning("No sample images found for this model.")
# Live Camera
elif input_mode == "Live Camera":
camera_image = st.camera_input("Take a picture using your webcam")
if camera_image:
input_image = Image.open(camera_image)
st.image(input_image, caption="Live Camera Capture", width=250)
st.markdown("---")
predict_btn = st.button("π Predict", use_container_width=True)
# ----------------------------------
# RIGHT PANEL
# ----------------------------------
with col2:
st.subheader("π Prediction Results")
if predict_btn:
if input_image is None:
st.error("Please upload or select an image.")
else:
# Show image
st.image(input_image, caption="Input Image", width=300)
# Load model
model_path = hf_hub_download(repo_id=REPO_ID, filename=models[model_choice])
model = load_tf_model(model_path)
class_names = load_class_names(model_choice)
# Predict
arr = preprocess(input_image)
preds = model.predict(arr, verbose=0)[0]
idx = np.argmax(preds)
predicted = class_names[idx]
st.success(f"### π© Predicted: **{predicted}** ({preds[idx]*100:.2f}%)")
# Top-3 Predictions
st.subheader("Top 3 Predictions")
top3 = preds.argsort()[-3:][::-1]
for i in top3:
st.write(f"**{class_names[i]}** β {preds[i]*100:.2f}%")
# Footer
st.markdown("---")
st.markdown("""
**Developed by:** Dr. Thyagharajan K K
**Professor & Dean (Research)**
RMD Engineering College
π§ **kkthyagharajan@yahoo.com**
""")
|