File size: 2,226 Bytes
4d8779f
 
 
 
5e562ec
b9f1e89
1724c49
4d8779f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1724c49
5e562ec
 
 
 
 
 
1724c49
 
4d8779f
 
 
 
c27bcf0
4d8779f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1724c49
4d8779f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c27bcf0
4d8779f
 
 
c27bcf0
4d8779f
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import numpy as np
import streamlit as st
import tensorflow as tf
from PIL import Image
from huggingface_hub import hf_hub_download
import os


class_names = [
 'Tomato_Bacterial_spot',
 'Tomato_Early_blight',
 'Tomato_Late_blight',
 'Tomato_Leaf_Mold',
 'Tomato_Septoria_leaf_spot',
 'Tomato_Spider_mites_Two_spotted_spider_mite',
 'Tomato__Target_Spot',
 'Tomato__Tomato_YellowLeaf__Curl_Virus',
 'Tomato__Tomato_mosaic_virus',
 'Tomato_healthy'
]

@st.cache_resource
def load_model_from_hub():
    model_path = hf_hub_download(
        repo_id="Heizsenberg/leaf_classification",
        filename="leaf_detection_model.keras",
        repo_type="space"   # VERY IMPORTANT
    )
    model = tf.keras.models.load_model(model_path)
    return model



def predict_image(model, img):
    # Preprocess
    img = img.convert("RGB")  # VERY IMPORTANT
    img = img.resize((128, 128))
    img_array = np.array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)

    # 4. Predict
    predictions = model.predict(img_array)
    predicted_index = np.argmax(predictions[0])
    
    predicted_label = class_names[predicted_index]
    
    confidence = np.max(predictions[0])

    return img, predicted_label, confidence

def run():
    classifier_model = load_model_from_hub()
    
    st.write("upload a tomato leaf image to be predicted")
    
    uploaded_file = st.file_uploader(
        "Choose an tomato leaf image to be uploaded",
        type=["JPG", "jpg", "jpeg"] # Specify accepted file types
    )
    
    if uploaded_file is not None:
        st.success("File uploaded successfully!")
        st.write("Filename:", uploaded_file.name)
        st.write(uploaded_file)
        
        st.write("Image")
        # To read image file buffer as a PIL Image:
        img = Image.open(uploaded_file)

        image, predicted_class, confidence = predict_image(
            classifier_model, img
        )

        confidence = confidence * 100
        
        # show result
        st.image(img, caption="Uploaded Image", use_container_width=True)
        st.success(f"Tomato Leaf Prediction: {predicted_class}")
        st.write(f"with confidence level of: {confidence}")

    
if __name__ == '__main__':
    run()