prasanthr0416 commited on
Commit
ddedb37
Β·
verified Β·
1 Parent(s): cfc642e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -38
app.py CHANGED
@@ -2,53 +2,81 @@ import os
2
  import numpy as np
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!")
 
2
  import numpy as np
3
  import streamlit as st
4
  from PIL import Image
5
+ from tensorflow.keras.models import load_model
6
+ from tensorflow.keras.preprocessing.image import img_to_array
7
 
8
+ # CONFIG
9
+ MODEL_PATH = "custom_cnn_last4_finetuned (1).h5"
10
+ IMG_SIZE = (256, 256)
11
 
12
+ CLASS_NAMES = [
13
+ "animal fish",
14
+ "animal fish bass",
15
+ "fish sea_food black_sea_sprat",
16
+ "fish sea_food gilt_head_bream",
17
+ "fish sea_food hourse_mackerel",
18
+ "fish sea_food red_mullet",
19
+ "fish sea_food red_sea_bream",
20
+ "fish sea_food sea_bass",
21
+ "fish sea_food shrimp",
22
+ "fish sea_food striped_red_mullet",
23
+ "fish sea_food trout"
24
+ ]
25
 
26
+ st.set_page_config(page_title="Custom CNN Fish Classifier", layout="centered")
27
+ st.title("🐟 Fish Classifier")
28
 
29
+ # LOAD MODEL
30
+ @st.cache_resource
31
+ def load_cnn_model():
32
+ try:
33
+ model = load_model(MODEL_PATH, compile=False)
34
+ return model
35
+ except Exception as e:
36
+ st.error(f"Model loading failed:\n{e}")
37
+ st.info("""
38
+ **Upload your model file to this Space:**
39
+ File must be named: `custom_cnn_last4_finetuned (1).h5`
40
+ """)
41
+ return None
42
 
43
+ model = load_cnn_model()
 
 
 
 
 
44
 
45
+ if model is None:
46
+ # Show what files exist
47
+ if os.path.exists("."):
48
+ st.write("Files in this space:")
49
+ for f in os.listdir("."):
50
+ st.write(f"- {f}")
51
  st.stop()
52
 
53
+ # PREPROCESS IMAGE
54
+ def prepare_image(pil_img):
55
+ pil_img = pil_img.convert("RGB")
56
+ pil_img = pil_img.resize((IMG_SIZE[1], IMG_SIZE[0]))
57
+
58
+ arr = img_to_array(pil_img)
59
+ arr = arr / 255.0 # Normalize to 0-1
60
+ arr = np.expand_dims(arr, axis=0)
61
 
62
+ return arr
63
+
64
+ # PREDICT
65
+ def predict_top1(img):
66
+ x = prepare_image(img)
67
+ preds = model.predict(x, verbose=0)[0]
68
+ top_index = np.argmax(preds)
69
+
70
+ return CLASS_NAMES[top_index], float(preds[top_index])
71
+
72
+ # UI
73
+ uploaded = st.file_uploader("Upload fish image", type=["jpg", "jpeg", "png"])
74
 
75
  if uploaded:
76
  img = Image.open(uploaded)
77
+ st.image(img, caption="Uploaded Image", use_container_width=True)
78
+
79
+ if st.button("Predict"):
80
+ label, prob = predict_top1(img)
81
+ st.markdown(f"## 🎯 Prediction: **{label}**")
82
+ st.markdown(f"### Confidence: **{prob*100:.2f}%**")