Basak Tamer commited on
Commit
0dbbc53
·
verified ·
1 Parent(s): afdc85d

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +66 -45
src/streamlit_app.py CHANGED
@@ -1,65 +1,86 @@
1
  import streamlit as st
2
  import tensorflow as tf
3
- from tensorflow.keras.preprocessing import image
4
- import numpy as np
5
  from PIL import Image
 
 
6
 
7
- # 1. LOAD THE MODEL
8
- # Ensure your 'rice_model.h5' is in the same folder as this script
 
 
9
  @st.cache_resource
10
  def load_my_model():
11
- return tf.keras.models.load_model('src/rice_model.h5')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
 
13
  model = load_my_model()
14
 
15
- # 2. DEFINE LABELS
16
- # This MUST match the alphabetical order or the folder order from training.
17
- # Based on your notebook cells, use this exact order:
18
  labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
19
 
20
- # 3. STREAMLIT UI
21
- st.title("🌾 Rice Variety Classifier")
22
- st.write("Upload an image of a single rice grain to identify its variety.")
23
 
24
- uploaded_file = st.file_uploader("Choose a rice image...", type=["jpg", "jpeg", "png"])
25
 
26
- if uploaded_file is not None:
27
- # Display the uploaded image
28
- img = Image.open(uploaded_file)
29
- st.image(img, caption='Uploaded Image', use_container_width=True)
30
 
31
- with st.spinner('Analyzing grain patterns...'):
32
- # A. Resize to 224x224 (required by MobileNetV2)
33
- img_resized = img.resize((224, 224))
 
34
 
35
- # B. Convert to array and handle channels
36
- img_array = np.array(img_resized).astype('float32')
37
-
38
- # If the image has an Alpha channel (RGBA), remove it
39
  if img_array.shape[-1] == 4:
40
- img_array = img_array[:, :, :3]
41
 
42
- # C. Add batch dimension (1, 224, 224, 3)
43
  img_array = np.expand_dims(img_array, axis=0)
44
 
45
- # D. PREPROCESSING (The Critical Part)
46
- # Your notebook uses standard MobileNetV2 logic.
47
- # If you didn't define a custom Rescaling layer, use this:
48
- img_processed = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
49
-
50
- # E. Predict
51
- predictions = model.predict(img_processed)
52
- result_index = np.argmax(predictions[0])
53
- confidence = predictions[0][result_index] * 100
54
-
55
- # F. Output Results
56
- predicted_label = labels[result_index]
57
-
58
- st.subheader(f"Prediction: **{predicted_label}**")
59
- st.progress(int(confidence))
60
- st.write(f"Confidence: **{confidence:.2f}%**")
61
 
62
- # Optional: Debugging Info (Can be removed later)
63
- with st.expander("See Raw Model Probabilities"):
64
- for i, label in enumerate(labels):
65
- st.write(f"{label}: {predictions[0][i]*100:.2f}%")
 
 
 
 
1
  import streamlit as st
2
  import tensorflow as tf
 
 
3
  from PIL import Image
4
+ import numpy as np
5
+ import os
6
 
7
+ # --- PAGE CONFIG ---
8
+ st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered")
9
+
10
+ # --- MODEL LOADING ---
11
  @st.cache_resource
12
  def load_my_model():
13
+ # Check multiple possible locations for the model file
14
+ model_path = 'rice_transfer_model.h5'
15
+
16
+ if not os.path.exists(model_path):
17
+ # If it's not in the root, check the 'src' folder as a backup
18
+ model_path = os.path.join('src', 'rice_transfer_model.h5')
19
+
20
+ try:
21
+ # 1. Recreate the exact architecture from your Kaggle Notebook
22
+ base_model = tf.keras.applications.MobileNetV2(
23
+ input_shape=(224, 224, 3),
24
+ include_top=False,
25
+ weights=None
26
+ )
27
+ base_model.trainable = False
28
+
29
+ model = tf.keras.Sequential([
30
+ base_model,
31
+ tf.keras.layers.GlobalAveragePooling2D(),
32
+ tf.keras.layers.Dense(512, activation='relu'),
33
+ tf.keras.layers.Dense(5, activation='softmax')
34
+ ])
35
+
36
+ # 2. Load the weights from the verified path
37
+ model.load_weights(model_path)
38
+ return model
39
+ except Exception as e:
40
+ st.error(f"Error: Could not find or load {model_path}. Please ensure the file is uploaded to your Hugging Face Space.")
41
+ st.info(f"System Error Message: {e}")
42
+ return None
43
 
44
+ # Initialize Model
45
  model = load_my_model()
46
 
47
+ # Labels must match your training dictionary exactly
 
 
48
  labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
49
 
50
+ # --- USER INTERFACE ---
51
+ st.title("🌾 Rice Variety Classification")
52
+ st.markdown("### **Deployment for Data Science Assignment**")
53
 
54
+ uploaded_file = st.file_uploader("Upload a rice grain image (JPG/PNG)", type=["jpg", "jpeg", "png"])
55
 
56
+ if uploaded_file is not None and model is not None:
57
+ # 1. Process Image
58
+ image = Image.open(uploaded_file)
59
+ st.image(image, caption='Uploaded Sample', use_container_width=True)
60
 
61
+ with st.spinner('AI is classifying...'):
62
+ # 2. Preprocessing
63
+ img = image.resize((224, 224))
64
+ img_array = np.array(img).astype('float32')
65
 
66
+ # Handle transparency (RGBA to RGB)
 
 
 
67
  if img_array.shape[-1] == 4:
68
+ img_array = img_array[:,:,:3]
69
 
 
70
  img_array = np.expand_dims(img_array, axis=0)
71
 
72
+ # MobileNetV2 scaling (-1 to 1)
73
+ img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
74
+
75
+ # 3. Prediction
76
+ predictions = model.predict(img_array)
77
+ result_idx = np.argmax(predictions[0])
78
+ confidence = predictions[0][result_idx] * 100
 
 
 
 
 
 
 
 
 
79
 
80
+ # 4. Results
81
+ st.success(f"Prediction: **{labels[result_idx]}**")
82
+ st.metric(label="Model Confidence", value=f"{confidence:.2f}%")
83
+
84
+ with st.expander("Show Probability Distribution"):
85
+ for i, name in enumerate(labels):
86
+ st.write(f"{name}: {predictions[0][i]*100:.2f}%")