Basak Tamer commited on
Commit
4444f7f
·
verified ·
1 Parent(s): c0285b5

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +66 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,68 @@
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
  import streamlit as st
2
+ import tensorflow as tf
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+ # --- PAGE CONFIG ---
7
+ st.set_page_config(page_title="Rice Variety AI", page_icon="🌾", layout="centered")
8
+
9
+ # --- MODEL RECONSTRUCTION (Fixed Shape) ---
10
+ @st.cache_resource
11
+ def load_my_model():
12
+ try:
13
+ # 1. Recreate the Base (MobileNetV2)
14
+ base_model = tf.keras.applications.MobileNetV2(
15
+ input_shape=(224, 224, 3),
16
+ include_top=False,
17
+ weights=None
18
+ )
19
+ base_model.trainable = False
20
+
21
+ # 2. Rebuild the Top Layers (MATCHING YOUR WEIGHTS: 512 neurons)
22
+ model = tf.keras.Sequential([
23
+ base_model,
24
+ tf.keras.layers.GlobalAveragePooling2D(),
25
+ tf.keras.layers.Dense(512, activation='relu'), # Changed from 128 to 512
26
+ tf.keras.layers.Dense(5, activation='softmax')
27
+ ])
28
+
29
+ # 3. Load the weights
30
+ model.load_weights('src/rice_transfer_model.h5')
31
+ return model
32
+ except Exception as e:
33
+ st.error(f"Shape Mismatch or Loading Error: {e}")
34
+ return None
35
+
36
+ # Initialize Model
37
+ model = load_my_model()
38
+ class_names = ['Arborio', 'Basmati', 'Ipsala', 'Jasmine', 'Karacadag']
39
+
40
+ # --- USER INTERFACE ---
41
+ st.title("🌾 Rice Variety Classification")
42
+ st.markdown("### **Transfer Learning Edition (MobileNetV2)**")
43
+
44
+ uploaded_file = st.file_uploader("Upload a rice grain image...", type=["jpg", "jpeg", "png"])
45
+
46
+ if uploaded_file is not None and model is not None:
47
+ image = Image.open(uploaded_file)
48
+ st.image(image, caption='Uploaded Sample', use_container_width=True)
49
+
50
+ with st.spinner('Calculating probabilities...'):
51
+ # Preprocessing
52
+ img = image.resize((224, 224))
53
+ img_array = np.array(img)
54
+
55
+ if img_array.shape[-1] == 4:
56
+ img_array = img_array[:,:,:3]
57
+
58
+ img_array = np.expand_dims(img_array, axis=0)
59
+ img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
60
+
61
+ # Prediction
62
+ predictions = model.predict(img_array)
63
+ result_idx = np.argmax(predictions[0])
64
+ confidence = predictions[0][result_idx] * 100
65
 
66
+ # Results
67
+ st.success(f"Prediction: **{class_names[result_idx]}**")
68
+ st.metric(label="Confidence Level", value=f"{confidence:.2f}%")