kkthyagharajan commited on
Commit
d10791c
Β·
verified Β·
1 Parent(s): bb4c7fe

Uploaded 5 Files

Browse files

Added Camera Feed

Files changed (5) hide show
  1. Dockerfile +14 -13
  2. Insect_HFspace_Camera_Streamlit_App.py +182 -0
  3. LICENSE.txt +21 -0
  4. README.md +60 -12
  5. requirements.txt +6 -3
Dockerfile CHANGED
@@ -1,20 +1,21 @@
1
- FROM python:3.13.5-slim
2
 
3
- WORKDIR /app
 
 
 
 
 
 
4
 
5
- RUN apt-get update && apt-get install -y \
6
- build-essential \
7
- curl \
8
- git \
9
- && rm -rf /var/lib/apt/lists/*
10
 
11
- COPY requirements.txt ./
12
- COPY src/ ./src/
13
 
14
- RUN pip3 install -r requirements.txt
15
 
16
- EXPOSE 8501
17
 
18
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
 
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
1
+ FROM python:3.11-slim
2
 
3
+ # Required for uploads in Docker Spaces
4
+ ENV STREAMLIT_SERVER_ENABLE_CORS=false
5
+ ENV STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION=false
6
+ ENV STREAMLIT_BROWSER_GATHER_USAGE_STATS=false
7
+
8
+ # Fix HuggingFace download + caching inside Docker container
9
+ ENV HF_HOME=/data
10
 
11
+ WORKDIR /app
 
 
 
 
12
 
13
+ COPY requirements.txt .
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
 
16
+ COPY . .
17
 
18
+ EXPOSE 7860
19
 
20
+ CMD ["streamlit", "run", "Insect_HFspace_Streamlit_App.py", "--server.port=7860", "--server.address=0.0.0.0"]
21
 
 
Insect_HFspace_Camera_Streamlit_App.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
14
+ os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "false"
15
+ os.environ["STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION"] = "false"
16
+ # ------------------------------
17
+ # CONFIGURATION
18
+ # ------------------------------
19
+ REPO_ID = "kkthyagharajan/KKT-HF-TransferLearning-Models" # <<< CHANGE THIS
20
+ IMG_SIZE = (300, 300)
21
+
22
+ st.set_page_config(page_title="Insect Classifier", layout="wide")
23
+
24
+ # Cache dictionaries
25
+ @st.cache_resource
26
+ def load_tf_model(model_path):
27
+ return tf.keras.models.load_model(model_path, compile=False)
28
+
29
+ @st.cache_resource
30
+ def load_class_names(model_dir):
31
+ class_file = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/class_names.txt")
32
+ with open(class_file, "r") as f:
33
+ return [x.strip() for x in f.read().split(",")]
34
+
35
+ # ----------------------------------
36
+ # Helper Functions
37
+ # ----------------------------------
38
+ def get_available_models():
39
+ """Return mapping: model_dir β†’ model file (.h5 preferred over .keras)."""
40
+ files = list_repo_files(REPO_ID)
41
+ models = {}
42
+
43
+ # Prefer .h5
44
+ for file in files:
45
+ if file.endswith(".h5"):
46
+ dir = file.split("/")[0]
47
+ models[dir] = file
48
+
49
+ # Use .keras only if .h5 missing
50
+ for file in files:
51
+ if file.endswith(".keras"):
52
+ dir = file.split("/")[0]
53
+ if dir not in models:
54
+ models[dir] = file
55
+
56
+ return models
57
+
58
+ def get_sample_images(model_dir):
59
+ """List sample images inside model_dir/sample_images/"""
60
+ files = list_repo_files(REPO_ID)
61
+ sample_imgs = []
62
+ prefix = f"{model_dir}/sample_images/"
63
+
64
+ for f in files:
65
+ if f.startswith(prefix) and f.lower().endswith((".jpg", ".jpeg", ".png")):
66
+ sample_imgs.append(f.replace(prefix, ""))
67
+
68
+ return sample_imgs
69
+
70
+ def load_sample_image(model_dir, image_name):
71
+ """Download sample image."""
72
+ path = hf_hub_download(repo_id=REPO_ID, filename=f"{model_dir}/sample_images/{image_name}")
73
+ return Image.open(path)
74
+
75
+ def preprocess(img):
76
+ img = img.resize(IMG_SIZE)
77
+ arr = np.array(img) / 255.0
78
+ arr = arr.reshape(1, IMG_SIZE[0], IMG_SIZE[1], 3)
79
+ return arr
80
+
81
+ # ----------------------------------
82
+ # UI Layout
83
+ # ----------------------------------
84
+ st.title("πŸ¦‹ Insect Classification System")
85
+ st.markdown("""
86
+ ### A Multi-Model Deep Learning Web App
87
+ Developed by **Dr. Thyagharajan K K, Professor & Dean (Research)**
88
+ RMD Engineering College
89
+ """)
90
+
91
+ col1, col2 = st.columns([1, 1])
92
+
93
+ # ----------------------------------
94
+ # LEFT PANEL
95
+ # ----------------------------------
96
+ with col1:
97
+ st.subheader("1️⃣ Select Model")
98
+ models = get_available_models()
99
+
100
+ if not models:
101
+ st.error("No models found in HuggingFace repo.")
102
+ st.stop()
103
+
104
+ model_choice = st.selectbox("Choose a model", list(models.keys()))
105
+
106
+ st.subheader("2️⃣ Choose Image Source")
107
+ input_mode = st.radio(
108
+ "Select input method:",
109
+ ["Upload Image", "Use Sample Image", "Live Camera"]
110
+ )
111
+
112
+ input_image = None
113
+
114
+ # Upload
115
+ if input_mode == "Upload Image":
116
+ uploaded = st.file_uploader("Upload image", type=["jpg", "jpeg", "png"])
117
+ if uploaded:
118
+ input_image = Image.open(uploaded)
119
+
120
+ # Sample Images
121
+ elif input_mode == "Use Sample Image":
122
+ sample_images = get_sample_images(model_choice)
123
+ if sample_images:
124
+ selected_sample = st.selectbox("Choose sample image", sample_images)
125
+ if selected_sample:
126
+ input_image = load_sample_image(model_choice, selected_sample)
127
+ st.image(input_image, caption="Sample Image", width=250)
128
+ else:
129
+ st.warning("No sample images found for this model.")
130
+
131
+ # Live Camera
132
+ elif input_mode == "Live Camera":
133
+ camera_image = st.camera_input("Take a picture using your webcam")
134
+ if camera_image:
135
+ input_image = Image.open(camera_image)
136
+ st.image(input_image, caption="Live Camera Capture", width=250)
137
+
138
+ st.markdown("---")
139
+ predict_btn = st.button("πŸ” Predict", use_container_width=True)
140
+
141
+
142
+ # ----------------------------------
143
+ # RIGHT PANEL
144
+ # ----------------------------------
145
+ with col2:
146
+ st.subheader("πŸ“Š Prediction Results")
147
+
148
+ if predict_btn:
149
+ if input_image is None:
150
+ st.error("Please upload or select an image.")
151
+ else:
152
+ # Show image
153
+ st.image(input_image, caption="Input Image", width=300)
154
+
155
+ # Load model
156
+ model_path = hf_hub_download(repo_id=REPO_ID, filename=models[model_choice])
157
+ model = load_tf_model(model_path)
158
+ class_names = load_class_names(model_choice)
159
+
160
+ # Predict
161
+ arr = preprocess(input_image)
162
+ preds = model.predict(arr, verbose=0)[0]
163
+
164
+ idx = np.argmax(preds)
165
+ predicted = class_names[idx]
166
+
167
+ st.success(f"### 🟩 Predicted: **{predicted}** ({preds[idx]*100:.2f}%)")
168
+
169
+ # Top-3 Predictions
170
+ st.subheader("Top 3 Predictions")
171
+ top3 = preds.argsort()[-3:][::-1]
172
+ for i in top3:
173
+ st.write(f"**{class_names[i]}** β€” {preds[i]*100:.2f}%")
174
+
175
+ # Footer
176
+ st.markdown("---")
177
+ st.markdown("""
178
+ **Developed by:** Dr. Thyagharajan K K
179
+ **Professor & Dean (Research)**
180
+ RMD Engineering College
181
+ πŸ“§ **kkthyagharajan@yahoo.com**
182
+ """)
LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Dr. Thyagharajan K K
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
README.md CHANGED
@@ -1,20 +1,68 @@
1
  ---
2
- title: Insect CameraFeed
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: Image Recognition
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,6 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
1
+ streamlit
2
+ tensorflow==2.18.0
3
+ keras==3.8.0
4
+ huggingface_hub
5
+ numpy
6
+ Pillow