prasanthr0416 commited on
Commit
594e520
·
verified ·
1 Parent(s): 84e5fde

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -267
app.py CHANGED
@@ -3,282 +3,52 @@ import numpy as np
3
  import streamlit as st
4
  from PIL import Image
5
  import tensorflow as tf
6
- from tensorflow.keras.preprocessing.image import img_to_array
7
- from tensorflow.keras.applications.efficientnet import preprocess_input as eff_pre
8
 
9
- # ==================== PAGE CONFIG ====================
10
- st.set_page_config(
11
- page_title="Fish Classification App",
12
- page_icon="🐟",
13
- layout="centered"
14
- )
15
 
16
- # ==================== TITLE & DESCRIPTION ====================
17
- st.markdown("""
18
- <div style="text-align: center;">
19
- <h1>🐟 Fish Species Classifier</h1>
20
- <p>Upload an image of a fish to identify its species using AI</p>
21
- </div>
22
- """, unsafe_allow_html=True)
23
 
24
- # ==================== CONSTANTS ====================
25
- IMG_SIZE = (256, 256) # Must match training size
26
 
27
- CLASS_NAMES = [
28
- "animal fish",
29
- "animal fish bass",
30
- "fish sea_food black_sea_sprat",
31
- "fish sea_food gilt_head_bream",
32
- "fish sea_food hourse_mackerel",
33
- "fish sea_food red_mullet",
34
- "fish sea_food red_sea_bream",
35
- "fish sea_food sea_bass",
36
- "fish sea_food shrimp",
37
- "fish sea_food striped_red_mullet",
38
- "fish sea_food trout"
39
  ]
40
 
41
- # ==================== MODEL LOADING ====================
42
- @st.cache_resource
43
- def load_model_from_hf():
44
- """
45
- Load model from Hugging Face Space files
46
- Two options: Direct download or from local if already in space
47
- """
48
- # Try multiple possible model locations
49
- model_paths = [
50
- "EfficientNetB0_head_finetuned.keras", # Direct in space root
51
- "fish_model/EfficientNetB0_head_finetuned.keras", # In folder
52
- "models/EfficientNetB0_head_finetuned.keras", # Another possible location
53
- "EfficientNetB0_head_finetuned (1).keras", # Your uploaded filename
54
- ]
55
-
56
- for model_path in model_paths:
57
- if os.path.exists(model_path):
58
- try:
59
- st.info(f"Loading model from: {model_path}")
60
- model = tf.keras.models.load_model(model_path, compile=False)
61
- st.success(f"✅ Model loaded successfully from {model_path}")
62
- return model
63
- except Exception as e:
64
- st.warning(f"Failed to load {model_path}: {str(e)[:100]}")
65
-
66
- # If not found locally, try to download from URL
67
- try:
68
- st.info("Model not found locally. Trying to download...")
69
-
70
- # You can add a direct download link if your model is hosted somewhere
71
- # For example, if you uploaded to GitHub or other hosting
72
- model_url = "YOUR_MODEL_URL_HERE" # Replace with actual URL
73
-
74
- import urllib.request
75
- local_filename = "downloaded_model.keras"
76
- urllib.request.urlretrieve(model_url, local_filename)
77
-
78
- model = tf.keras.models.load_model(local_filename, compile=False)
79
- st.success("✅ Model downloaded and loaded successfully!")
80
- return model
81
- except:
82
- st.error("❌ Could not load model. Please ensure the model file is uploaded to this Space.")
83
- return None
84
 
85
- # Load the model
86
- model = load_model_from_hf()
87
-
88
- if model is None:
89
- st.warning("""
90
- **Setup Instructions:**
91
- 1. Upload your `EfficientNetB0_head_finetuned.keras` file to this Space
92
- 2. Click the **"Files"** tab in the top navigation
93
- 3. Click **"Add file"** → **"Upload file"**
94
- 4. Select your model file and upload
95
- 5. The app will automatically detect it
96
- """)
97
  st.stop()
98
 
99
- # ==================== IMAGE PREPROCESSING ====================
100
- def prepare_image(pil_img):
101
- """Preprocess image for EfficientNet model"""
102
- # Convert to RGB and resize
103
- pil_img = pil_img.convert("RGB")
104
- pil_img = pil_img.resize((IMG_SIZE[1], IMG_SIZE[0])) # (width, height)
105
-
106
- # Convert to array and expand dimensions
107
- arr = img_to_array(pil_img) # → (H, W, 3)
108
- arr = np.expand_dims(arr, axis=0) # → (1, H, W, 3)
109
-
110
- # Apply EfficientNet preprocessing
111
- arr = eff_pre(arr)
112
- return arr
113
-
114
- # ==================== PREDICTION ====================
115
- def predict_top1(img):
116
- """Get top-1 prediction"""
117
- x = prepare_image(img)
118
- preds = model.predict(x, verbose=0)[0] # vector of 11 probabilities
119
- top_index = np.argmax(preds) # best class index
120
-
121
- return CLASS_NAMES[top_index], float(preds[top_index])
122
-
123
- def predict_top3(img):
124
- """Get top-3 predictions"""
125
- x = prepare_image(img)
126
- preds = model.predict(x, verbose=0)[0]
127
-
128
- # Get top 3 indices
129
- top_indices = np.argsort(preds)[-3:][::-1]
130
-
131
- results = []
132
- for idx in top_indices:
133
- results.append({
134
- 'class': CLASS_NAMES[idx],
135
- 'confidence': float(preds[idx])
136
- })
137
-
138
- return results
139
-
140
- # ==================== SIDEBAR ====================
141
- with st.sidebar:
142
- st.markdown("### ℹ️ About")
143
- st.markdown("""
144
- This app classifies fish species using a deep learning model.
145
-
146
- **Supported Classes:**
147
- - Animal Fish
148
- - Bass
149
- - Black Sea Sprat
150
- - Gilt-head Bream
151
- - Horse Mackerel
152
- - Red Mullet
153
- - Red Sea Bream
154
- - Sea Bass
155
- - Shrimp
156
- - Striped Red Mullet
157
- - Trout
158
- """)
159
-
160
- st.markdown("### ⚙️ Settings")
161
- show_top3 = st.checkbox("Show top 3 predictions", value=True)
162
-
163
- # ==================== MAIN INTERFACE ====================
164
- st.markdown("### 📤 Upload Fish Image")
165
- uploaded_file = st.file_uploader(
166
- "Choose an image...",
167
- type=["jpg", "jpeg", "png", "bmp"],
168
- help="Upload an image of a fish for classification"
169
- )
170
-
171
- col1, col2 = st.columns([1, 1])
172
- with col1:
173
- # Example images section
174
- st.markdown("### 📸 Example Images")
175
- st.markdown("Try with these examples:")
176
-
177
- example_images = {
178
- "Fish 1": "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400",
179
- "Fish 2": "https://images.unsplash.com/photo-1550358864-518f202c02ba?w-400",
180
- "Fish 3": "https://images.unsplash.com/photo-1560279966-8ff2f6c81d26?w=400"
181
- }
182
-
183
- for name, url in example_images.items():
184
- if st.button(f"Use {name}"):
185
- # In real implementation, you'd download and use the image
186
- st.info(f"Would use {name} example (implement image download)")
187
-
188
- with col2:
189
- # Model info
190
- st.markdown("### 🧠 Model Info")
191
- st.info(f"""
192
- **Model:** EfficientNetB0 Fine-tuned
193
- **Input Size:** {IMG_SIZE[0]}x{IMG_SIZE[1]}
194
- **Classes:** {len(CLASS_NAMES)} species
195
- **File:** EfficientNetB0_head_finetuned.keras
196
- """)
197
 
198
- # ==================== PREDICTION SECTION ====================
199
- if uploaded_file is not None:
200
- # Display uploaded image
201
- image = Image.open(uploaded_file)
202
-
203
- st.markdown("---")
204
- col1, col2 = st.columns(2)
205
-
206
- with col1:
207
- st.image(image, caption="Uploaded Image", use_container_width=True)
208
-
209
- with col2:
210
- st.markdown("### 🔍 Analysis")
211
-
212
- if st.button("🔍 Classify Image", type="primary", use_container_width=True):
213
- with st.spinner("Analyzing image..."):
214
- # Get predictions
215
- top1_class, top1_conf = predict_top1(image)
216
-
217
- # Display top-1 result
218
- st.markdown(f"### 🎯 **Prediction:** {top1_class}")
219
- st.markdown(f"#### **Confidence:** {top1_conf*100:.2f}%")
220
-
221
- # Confidence bar
222
- st.progress(float(top1_conf))
223
-
224
- # Show top-3 if enabled
225
- if show_top3:
226
- st.markdown("### 📊 Top 3 Predictions")
227
- top3_results = predict_top3(image)
228
-
229
- for i, result in enumerate(top3_results):
230
- col_a, col_b = st.columns([3, 2])
231
- with col_a:
232
- st.write(f"{i+1}. {result['class']}")
233
- with col_b:
234
- st.write(f"{result['confidence']*100:.1f}%")
235
-
236
- # Progress bar for each prediction
237
- st.progress(float(result['confidence']))
238
-
239
- # Download button for results
240
- st.markdown("---")
241
- if st.button("📥 Download Prediction Results"):
242
- results_text = f"Fish Classification Results\n"
243
- results_text += f"Image: {uploaded_file.name}\n"
244
- results_text += f"Top Prediction: {top1_class} ({top1_conf*100:.2f}%)\n\n"
245
-
246
- if show_top3:
247
- results_text += "Top 3 Predictions:\n"
248
- top3 = predict_top3(image)
249
- for i, r in enumerate(top3):
250
- results_text += f"{i+1}. {r['class']}: {r['confidence']*100:.2f}%\n"
251
-
252
- # Create download
253
- st.download_button(
254
- label="Download as Text File",
255
- data=results_text,
256
- file_name="fish_classification_results.txt",
257
- mime="text/plain"
258
- )
259
 
260
- else:
261
- # Welcome message when no image uploaded
262
- st.markdown("---")
263
- st.info("👈 **Upload an image using the file uploader above to get started!**")
264
 
265
- # Quick tips
266
- with st.expander("💡 Tips for Best Results", expanded=True):
267
- st.markdown("""
268
- 1. **Clear Images:** Use well-lit, clear photos
269
- 2. **Focus on Fish:** Ensure the fish is clearly visible
270
- 3. **Multiple Angles:** Side views work best
271
- 4. **File Types:** JPG, PNG, BMP supported
272
- 5. **Size:** Images are resized to 256x256 pixels
273
-
274
- The model was trained on 11 fish species using EfficientNetB0 architecture.
275
- """)
276
-
277
- # ==================== FOOTER ====================
278
- st.markdown("---")
279
- st.markdown("""
280
- <div style="text-align: center; color: gray;">
281
- <p>Built with TensorFlow & Streamlit | Model: EfficientNetB0 Fine-tuned</p>
282
- <p>Upload your <code>EfficientNetB0_head_finetuned.keras</code> file to get started!</p>
283
- </div>
284
- """, unsafe_allow_html=True)
 
3
  import streamlit as st
4
  from PIL import Image
5
  import tensorflow as tf
 
 
6
 
7
+ # Set page config
8
+ st.set_page_config(page_title="Fish Classifier", page_icon="🐟")
 
 
 
 
9
 
10
+ st.title("🐟 Fish Species Classifier")
 
 
 
 
 
 
11
 
12
+ # List all files to find the model
13
+ st.write("Searching for model file...")
14
 
15
+ # Look for model in common locations
16
+ possible_paths = [
17
+ "EfficientNetB0_head_finetuned (1).keras",
18
+ "EfficientNetB0_head_finetuned.keras",
19
+ "model.keras",
20
+ "fish_model.keras",
21
+ "EfficientNetB0.keras",
 
 
 
 
 
22
  ]
23
 
24
+ found_model = None
25
+ for path in possible_paths:
26
+ if os.path.exists(path):
27
+ st.success(f"✅ Found model at: {path}")
28
+ found_model = path
29
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
+ if not found_model:
32
+ st.error("❌ Model file not found!")
33
+ st.write("Please upload your model file to the Space.")
 
 
 
 
 
 
 
 
 
34
  st.stop()
35
 
36
+ # Try to load the model
37
+ try:
38
+ model = tf.keras.models.load_model(found_model, compile=False)
39
+ st.success("✅ Model loaded successfully!")
40
+ except Exception as e:
41
+ st.error(f"❌ Failed to load model: {str(e)[:200]}")
42
+ st.stop()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Simple interface
45
+ uploaded = st.file_uploader("Upload fish image", type=["jpg", "png", "jpeg"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ if uploaded:
48
+ img = Image.open(uploaded)
49
+ st.image(img, caption="Uploaded Image")
 
50
 
51
+ if st.button("Classify"):
52
+ st.write("Processing...")
53
+ # Add your prediction code here
54
+ st.success("Classification complete!")