kkthyagharajan commited on
Commit
3cbb760
Β·
verified Β·
1 Parent(s): 5b7a02f

app uploaded

Browse files
Files changed (3) hide show
  1. Insect_HFspace_Streamlit_App.py +169 -0
  2. README.md +68 -20
  3. requirements.txt +5 -3
Insect_HFspace_Streamlit_App.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Nov 18 09:07:10 2025
4
+
5
+ @author: THYAGHARAJAN
6
+ """
7
+
8
+ import streamlit as st
9
+ import tensorflow as tf
10
+ import numpy as np
11
+ from PIL import Image
12
+ from huggingface_hub import hf_hub_download, list_repo_files
13
+
14
+ # ------------------------------
15
+ # CONFIGURATION
16
+ # ------------------------------
17
+ REPO_ID = "kkthyagharajan/KKT-HF-TransferLearning-Models" # <<< CHANGE THIS
18
+ IMG_SIZE = (300, 300)
19
+
20
+ st.set_page_config(page_title="Insect Classifier", layout="wide")
21
+
22
+ # Cache dictionaries
23
+ @st.cache_resource
24
+ def load_tf_model(model_path):
25
+ return tf.keras.models.load_model(model_path, compile=False)
26
+
27
+ @st.cache_resource
28
+ def load_class_names(model_dir):
29
+ class_file = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/class_names.txt")
30
+ with open(class_file, "r") as f:
31
+ return [x.strip() for x in f.read().split(",")]
32
+
33
+ # ----------------------------------
34
+ # Helper Functions
35
+ # ----------------------------------
36
+ def get_available_models():
37
+ """Return mapping: model_dir β†’ model file (.h5 preferred over .keras)."""
38
+ files = list_repo_files(REPO_ID)
39
+ models = {}
40
+
41
+ # Prefer .h5
42
+ for file in files:
43
+ if file.endswith(".h5"):
44
+ dir = file.split("/")[0]
45
+ models[dir] = file
46
+
47
+ # Use .keras only if .h5 missing
48
+ for file in files:
49
+ if file.endswith(".keras"):
50
+ dir = file.split("/")[0]
51
+ if dir not in models:
52
+ models[dir] = file
53
+
54
+ return models
55
+
56
+ def get_sample_images(model_dir):
57
+ """List sample images inside model_dir/sample_images/"""
58
+ files = list_repo_files(REPO_ID)
59
+ sample_imgs = []
60
+ prefix = f"{model_dir}/sample_images/"
61
+
62
+ for f in files:
63
+ if f.startswith(prefix) and f.lower().endswith((".jpg", ".jpeg", ".png")):
64
+ sample_imgs.append(f.replace(prefix, ""))
65
+
66
+ return sample_imgs
67
+
68
+ def load_sample_image(model_dir, image_name):
69
+ """Download sample image."""
70
+ path = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/sample_images/{image_name}")
71
+ return Image.open(path)
72
+
73
+ def preprocess(img):
74
+ img = img.resize(IMG_SIZE)
75
+ arr = np.array(img) / 255.0
76
+ arr = arr.reshape(1, IMG_SIZE[0], IMG_SIZE[1], 3)
77
+ return arr
78
+
79
+ # ----------------------------------
80
+ # UI Layout
81
+ # ----------------------------------
82
+ st.title("πŸ¦‹ Insect Classification System")
83
+ st.markdown("""
84
+ ### A Multi-Model Deep Learning Web App
85
+ Developed by **Dr. Thyagharajan K K, Professor & Dean (Research)**
86
+ RMD Engineering College
87
+ """)
88
+
89
+ col1, col2 = st.columns([1, 1])
90
+
91
+ # ----------------------------------
92
+ # LEFT PANEL
93
+ # ----------------------------------
94
+ with col1:
95
+ st.subheader("1️⃣ Select Model")
96
+ models = get_available_models()
97
+
98
+ if not models:
99
+ st.error("No models found in HuggingFace repo.")
100
+ st.stop()
101
+
102
+ model_choice = st.selectbox("Choose a model", list(models.keys()))
103
+
104
+ st.subheader("2️⃣ Choose Image Source")
105
+ input_mode = st.radio("Select input method:", ["Upload Image", "Use Sample Image"])
106
+
107
+ input_image = None
108
+
109
+ # Upload
110
+ if input_mode == "Upload Image":
111
+ uploaded = st.file_uploader("Upload image", type=["jpg", "jpeg", "png"])
112
+ if uploaded:
113
+ input_image = Image.open(uploaded)
114
+
115
+ # Sample Images
116
+ else:
117
+ sample_images = get_sample_images(model_choice)
118
+ if sample_images:
119
+ selected_sample = st.selectbox("Choose sample image", sample_images)
120
+ if selected_sample:
121
+ input_image = load_sample_image(model_choice, selected_sample)
122
+ st.image(input_image, caption="Sample Image", width=250)
123
+ else:
124
+ st.warning("No sample images found for this model.")
125
+
126
+ st.markdown("---")
127
+ predict_btn = st.button("πŸ” Predict", use_container_width=True)
128
+
129
+ # ----------------------------------
130
+ # RIGHT PANEL
131
+ # ----------------------------------
132
+ with col2:
133
+ st.subheader("πŸ“Š Prediction Results")
134
+
135
+ if predict_btn:
136
+ if input_image is None:
137
+ st.error("Please upload or select an image.")
138
+ else:
139
+ # Show image
140
+ st.image(input_image, caption="Input Image", width=300)
141
+
142
+ # Load model
143
+ model_path = hf_hub_download(repo_id=REPO_ID, filename=models[model_choice])
144
+ model = load_tf_model(model_path)
145
+ class_names = load_class_names(model_choice)
146
+
147
+ # Predict
148
+ arr = preprocess(input_image)
149
+ preds = model.predict(arr, verbose=0)[0]
150
+
151
+ idx = np.argmax(preds)
152
+ predicted = class_names[idx]
153
+
154
+ st.success(f"### 🟩 Predicted: **{predicted}** ({preds[idx]*100:.2f}%)")
155
+
156
+ # Top-3 Predictions
157
+ st.subheader("Top 3 Predictions")
158
+ top3 = preds.argsort()[-3:][::-1]
159
+ for i in top3:
160
+ st.write(f"**{class_names[i]}** β€” {preds[i]*100:.2f}%")
161
+
162
+ # Footer
163
+ st.markdown("---")
164
+ st.markdown("""
165
+ **Developed by:** Dr. Thyagharajan K K
166
+ **Professor & Dean (Research)**
167
+ RMD Engineering College
168
+ πŸ“§ **kkthyagharajan@yahoo.com**
169
+ """)
README.md CHANGED
@@ -1,20 +1,68 @@
1
- ---
2
- title: Insect Streamlit App
3
- emoji: πŸš€
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Insect detection Pretrained DL Models
12
- license: mit
13
- ---
14
-
15
- # Welcome to Streamlit!
16
-
17
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
18
-
19
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
20
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Insect Detection
3
+ emoji: 🐝
4
+ colorFrom: yellow
5
+ colorTo: green
6
+ sdk: docker
7
+ app_file: Insect_HFspace_Streamlit_App.py
8
+ pinned: false
9
+ license: mit
10
+ tags:
11
+ - computer-vision
12
+ - image-classification
13
+ - insect-classification
14
+ - deep-learning
15
+ - tensorflow
16
+ - mobilenet
17
+ - efficientnet
18
+ - resnet
19
+ - inception
20
+ ---
21
+
22
+ # πŸ¦‹ Multi-Model Insect Classification System - A Web/Mobile App
23
+ ### Developed by Dr. Thyagharajan K K
24
+
25
+ ## Description
26
+
27
+ AI-powered insect classification application featuring multiple state-of-the-art deep learning models. Upload images to identify insect species with confidence scores and top-3 predictions.
28
+
29
+ ## Features
30
+
31
+ - 🎯 Multiple pre-trained models (Inception V3, EfficientNet, ResNet50)
32
+ - πŸ“Έ Upload custom images or use sample test images
33
+ - πŸ“Š Confidence scores with top-3 predictions
34
+ - πŸš€ Fast inference with model caching
35
+ - πŸ“± Responsive design for web and mobile
36
+
37
+ ## Models Available
38
+
39
+ - **Inception V3** - High accuracy, balanced performance
40
+ - **EfficientNet B0** - Efficient and lightweight
41
+ - **ResNet50** - Deep residual learning
42
+ - (More models coming soon...)
43
+
44
+ ## How to Use
45
+
46
+ 1. Select a model from the dropdown
47
+ 2. Upload an insect image or choose from sample images
48
+ 3. Click "Predict" to get classification results
49
+ 4. View predicted class with confidence score
50
+
51
+ ## Technical Details
52
+
53
+ - **Framework:** TensorFlow/Keras
54
+ - **Input Size:** 300Γ—300 pixels
55
+ - **Interface:** Streamlit
56
+ - **Hosted on:** Hugging Face Spaces
57
+
58
+ ## License
59
+
60
+ This project is licensed under the MIT License - see the LICENSE file for details.
61
+
62
+ ## Citation
63
+
64
+ If you use this application in your research or educational projects, please provide appropriate attribution.
65
+
66
+ ## Contact
67
+
68
+ For questions or collaboration opportunities, please open a discussion in this Space.
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
1
+ streamlit
2
+ tensorflow-cpu==2.14.0
3
+ huggingface_hub
4
+ numpy
5
+ Pillow