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

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +29 -22
src/streamlit_app.py CHANGED
@@ -7,18 +7,24 @@ import os
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,
@@ -29,58 +35,59 @@ def load_my_model():
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}%")
 
7
  # --- PAGE CONFIG ---
8
  st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered")
9
 
10
+ # --- MODEL LOADING LOGIC ---
11
  @st.cache_resource
12
  def load_my_model():
13
+ # 1. FIND THE FILE: Check for common names and locations
14
+ possible_names = ['rice_model.h5', 'rice_transfer_model.h5', 'src/rice_transfer_model.h5']
15
+ model_path = None
16
 
17
+ for name in possible_names:
18
+ if os.path.exists(name):
19
+ model_path = name
20
+ break
21
+
22
+ if model_path is None:
23
+ st.error("Model file not found! Please ensure your .h5 file is uploaded to the Hugging Face Space.")
24
+ return None
25
 
26
  try:
27
+ # 2. RECONSTRUCT ARCHITECTURE (Bypasses Keras 3 version errors)
28
  base_model = tf.keras.applications.MobileNetV2(
29
  input_shape=(224, 224, 3),
30
  include_top=False,
 
35
  model = tf.keras.Sequential([
36
  base_model,
37
  tf.keras.layers.GlobalAveragePooling2D(),
38
+ # MATCHING YOUR KAGGLE WEIGHTS: 512 neurons
39
  tf.keras.layers.Dense(512, activation='relu'),
40
  tf.keras.layers.Dense(5, activation='softmax')
41
  ])
42
 
43
+ # 3. LOAD WEIGHTS
44
  model.load_weights(model_path)
45
  return model
46
  except Exception as e:
47
+ st.error(f"Error loading model: {e}")
 
48
  return None
49
 
50
  # Initialize Model
51
  model = load_my_model()
52
 
53
+ # Alphabetical order based on folder names (Standard for Keras)
54
  labels = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
55
 
56
  # --- USER INTERFACE ---
57
  st.title("🌾 Rice Variety Classification")
58
+ st.write("Upload an image of a rice grain to identify its variety.")
59
 
60
+ uploaded_file = st.file_uploader("Upload Image (JPG/PNG)", type=["jpg", "jpeg", "png"])
61
 
62
  if uploaded_file is not None and model is not None:
63
+ # 1. Display Image
64
  image = Image.open(uploaded_file)
65
  st.image(image, caption='Uploaded Sample', use_container_width=True)
66
 
67
+ with st.spinner('AI is processing...'):
68
+ # 2. PREPROCESSING (Matching your MobileNetV2 training)
69
  img = image.resize((224, 224))
70
  img_array = np.array(img).astype('float32')
71
 
72
+ # Remove Alpha channel if it exists
73
  if img_array.shape[-1] == 4:
74
  img_array = img_array[:,:,:3]
75
 
76
  img_array = np.expand_dims(img_array, axis=0)
77
 
78
+ # Scaling between -1 and 1 (Required for MobileNetV2)
79
  img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
80
 
81
+ # 3. PREDICTION
82
  predictions = model.predict(img_array)
83
  result_idx = np.argmax(predictions[0])
84
  confidence = predictions[0][result_idx] * 100
85
 
86
+ # 4. RESULTS
87
  st.success(f"Prediction: **{labels[result_idx]}**")
88
+ st.metric(label="Confidence Level", value=f"{confidence:.2f}%")
89
 
90
+ # Show all probabilities to help debug "Jasmine vs Ipsala"
91
+ with st.expander("Show detailed breakdown"):
92
  for i, name in enumerate(labels):
93
  st.write(f"{name}: {predictions[0][i]*100:.2f}%")