1Codephoenix commited on
Commit
15c40d8
Β·
verified Β·
1 Parent(s): 4119729

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +33 -37
streamlit_app.py CHANGED
@@ -1,74 +1,70 @@
1
  import streamlit as st
2
- import numpy as np
3
  from tensorflow.keras.models import load_model
4
  from tensorflow.keras.preprocessing import image
 
5
  from PIL import Image
6
- import matplotlib.pyplot as plt
7
- import io
8
 
9
- # Load model
10
  @st.cache_resource
11
- def load_model_safe():
12
- model_path = "fish_freshness_model_retrained_final.keras"
13
- try:
14
- model = load_model(model_path)
15
- return model
16
- except Exception as e:
17
- st.error(f"Error loading model: {e}")
18
- return None
19
 
20
- model = load_model_safe()
21
 
22
- # Define class names and messages
23
  class_names = ['Fresh', 'Moderately Fresh', 'Spoiled']
24
  custom_messages = {
25
  'Fresh': (
26
  "βœ… **Fresh Fish Detected**\n"
27
- "- Estimated Age: Less than 1 day old\n"
28
- "- Bright eyes, red gills, firm flesh\n"
29
- "- Safe for raw or cooked consumption."
30
  ),
31
  'Moderately Fresh': (
32
- "⚠️ **Moderately Fresh Fish Detected**\n"
33
- "- Estimated Age: 2–3 days\n"
34
- "- Slight odor, softening flesh\n"
35
- "- Cook thoroughly before eating."
36
  ),
37
  'Spoiled': (
38
- "🚫 **Spoiled or Unsafe Fish Detected**\n"
39
- "- Estimated Age: 4+ days\n"
40
- "- Dull eyes, strong odor, possible chemical treatment\n"
41
- "- Not safe for consumption. Discard immediately."
42
  )
43
  }
44
 
45
  # Streamlit UI
46
  st.title("🐟 Fish Freshness Classifier")
47
- st.subheader("Upload an image of a fish to analyze its freshness")
48
 
49
- uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
50
 
51
- if uploaded_file and model:
52
  try:
 
53
  img = Image.open(uploaded_file).convert("RGB")
54
- img_resized = img.resize((224, 224)) # Match model input size
55
  img_array = image.img_to_array(img_resized)
56
- img_array = np.expand_dims(img_array / 255.0, axis=0)
57
 
 
58
  prediction = model.predict(img_array)
59
  predicted_index = np.argmax(prediction)
60
- confidence = float(np.max(prediction))
61
  predicted_class = class_names[predicted_index]
 
62
 
63
- # Display results
64
- st.image(img, caption=f"Uploaded Image", use_column_width=True)
65
- st.markdown(f"### 🎯 Prediction: **{predicted_class}** ({confidence*100:.2f}% confidence)")
66
  st.markdown(custom_messages[predicted_class])
67
 
68
- # Show confidence for all classes
69
- st.subheader("πŸ“Š Class Probabilities:")
70
  for i, class_name in enumerate(class_names):
71
  st.write(f"- {class_name}: {prediction[0][i]*100:.2f}%")
72
 
73
  except Exception as e:
74
- st.error(f"Error processing image: {e}")
 
1
  import streamlit as st
2
+ from huggingface_hub import hf_hub_download
3
  from tensorflow.keras.models import load_model
4
  from tensorflow.keras.preprocessing import image
5
+ import numpy as np
6
  from PIL import Image
 
 
7
 
8
+ # Load model from Hugging Face Model Hub
9
  @st.cache_resource
10
+ def load_model_from_hf():
11
+ model_path = hf_hub_download(
12
+ repo_id="1Codephoenix/fish-freshness-model",
13
+ filename="fish_freshness_model_retrained_final.keras"
14
+ )
15
+ return load_model(model_path)
 
 
16
 
17
+ model = load_model_from_hf()
18
 
19
+ # Class labels and custom messages
20
  class_names = ['Fresh', 'Moderately Fresh', 'Spoiled']
21
  custom_messages = {
22
  'Fresh': (
23
  "βœ… **Fresh Fish Detected**\n"
24
+ "- Age: Less than 1 day old\n"
25
+ "- Characteristics: Bright eyes, red gills, firm flesh"
 
26
  ),
27
  'Moderately Fresh': (
28
+ "⚠️ **Moderately Fresh**\n"
29
+ "- Age: 2–3 days\n"
30
+ "- Characteristics: Slightly dull, odor begins, flesh softens"
 
31
  ),
32
  'Spoiled': (
33
+ "🚫 **Spoiled Fish**\n"
34
+ "- Age: 4+ days or treated\n"
35
+ "- Characteristics: Cloudy eyes, odor, unsafe to eat"
 
36
  )
37
  }
38
 
39
  # Streamlit UI
40
  st.title("🐟 Fish Freshness Classifier")
41
+ st.subheader("Upload an image of a fish to predict its freshness level")
42
 
43
+ uploaded_file = st.file_uploader("Upload Fish Image", type=["jpg", "jpeg", "png"])
44
 
45
+ if uploaded_file:
46
  try:
47
+ # Load and preprocess the image
48
  img = Image.open(uploaded_file).convert("RGB")
49
+ img_resized = img.resize((224, 224)) # Match model input
50
  img_array = image.img_to_array(img_resized)
51
+ img_array = np.expand_dims(img_array / 255.0, axis=0) # Normalize
52
 
53
+ # Predict
54
  prediction = model.predict(img_array)
55
  predicted_index = np.argmax(prediction)
 
56
  predicted_class = class_names[predicted_index]
57
+ confidence = prediction[0][predicted_index]
58
 
59
+ # Show image and result
60
+ st.image(img, caption="Uploaded Fish Image", use_column_width=True)
61
+ st.markdown(f"### 🎯 Prediction: **{predicted_class}** ({confidence * 100:.2f}% confidence)")
62
  st.markdown(custom_messages[predicted_class])
63
 
64
+ # Show all class probabilities
65
+ st.subheader("πŸ“Š Confidence Scores")
66
  for i, class_name in enumerate(class_names):
67
  st.write(f"- {class_name}: {prediction[0][i]*100:.2f}%")
68
 
69
  except Exception as e:
70
+ st.error(f"⚠️ Error processing image: {e}")