EnYa32 commited on
Commit
efbb38d
Β·
verified Β·
1 Parent(s): bf120b0

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +78 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,80 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ #--- Date Fruit Classifier using Transfer Learning (ResNet50)
 
 
2
  import streamlit as st
3
+ import numpy as np
4
+ from PIL import Image
5
+ import tensorflow as tf
6
+ from tensorflow.keras.models import load_model
7
+ from tensorflow.keras.applications.resnet50 import preprocess_input
8
+ import warnings
9
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
10
+
11
+ st.set_page_config(
12
+ page_title="Date Fruit Classifier (ResNet50 – Transfer Learning)",
13
+ layout="centered"
14
+ )
15
+
16
+ # ------------------ SETTINGS ------------------
17
+ MODEL_PATH = "src/best_date_resnet50.keras"
18
+ IMG_SIZE = (224, 224)
19
+
20
+ CLASS_NAMES = [
21
+ "Ajwa", "Galaxy", "Medjool", "Meneifi",
22
+ "Nabtat Ali", "Rutab", "Shaishe", "Sokari", "Sugaey"
23
+ ]
24
+
25
+ # ------------------ LOAD MODEL ------------------
26
+ @st.cache_resource
27
+ def load_model_cached():
28
+ return load_model(MODEL_PATH, compile=False)
29
+
30
+ model = load_model_cached()
31
+
32
+ # ------------------ IMAGE PREPROCESSING ------------------
33
+ def preprocess_image(image: Image.Image) -> np.ndarray:
34
+ image = image.convert("RGB")
35
+ image = image.resize(IMG_SIZE)
36
+ img_array = np.array(image)
37
+ img_array = np.expand_dims(img_array, axis=0)
38
+ img_array = preprocess_input(img_array) # ResNet50 specific
39
+ return img_array
40
+
41
+ # ------------------ PREDICTION ------------------
42
+ def predict(image: Image.Image):
43
+ processed_img = preprocess_image(image)
44
+ preds = model.predict(processed_img)
45
+ probs = tf.nn.softmax(preds[0]).numpy()
46
+ top_idx = np.argmax(probs)
47
+ return CLASS_NAMES[top_idx], probs[top_idx], probs
48
+
49
+ # ------------------ STREAMLIT UI ------------------
50
+ st.title("🌴 Date Fruit Classifier (Transfer Learning – ResNet50)")
51
+ st.write(
52
+ "This app uses a **ResNet50 model with Transfer Learning** "
53
+ "to classify date fruit images."
54
+ )
55
+
56
+ st.sidebar.header("πŸ”§ Model Info")
57
+ st.sidebar.write(f"**Model file:** `{MODEL_PATH}`")
58
+ st.sidebar.write("**Class labels:**")
59
+ for cls in CLASS_NAMES:
60
+ st.sidebar.write(f"- {cls}")
61
+
62
+ uploaded_file = st.file_uploader("πŸ“€ Upload an image", type=["jpg", "jpeg", "png"])
63
+
64
+ if uploaded_file is not None:
65
+ image = Image.open(uploaded_file)
66
+ st.image(image, caption="πŸ“Έ Uploaded Image", use_container_width=True)
67
+
68
+ if st.button("πŸ” Predict (ResNet50)"):
69
+ with st.spinner("Analyzing..."):
70
+ top_class, top_prob, probabilities = predict(image)
71
+
72
+ st.subheader("πŸ”Ž Prediction")
73
+ st.write(f"**Class:** `{top_class}`")
74
+ st.write(f"**Confidence:** {top_prob:.2%}")
75
 
76
+ st.subheader("πŸ“Š Confidence per Class")
77
+ for cls, prob in zip(CLASS_NAMES, probabilities):
78
+ st.write(f"- **{cls}** β†’ {prob:.2%}")
79
+ else:
80
+ st.info("Upload an image to start.")