File size: 3,992 Bytes
d5b2220
 
 
 
 
5882ae2
d5b2220
33af4fe
 
 
d5b2220
 
 
 
 
 
 
 
d4ca3a4
d5b2220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91969
d5b2220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d91969
 
d5b2220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import streamlit as st  
import pandas as pd  
import joblib  
import ee  
import geemap  

# Earth Engine Authentication (Replace with your actual authentication)  
# اعتبار سنجی و اتصال به Google Earth Engine
service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
ee.Initialize(credentials) 


# Load pre-trained model  
model = joblib.load('updated_model.pkl')  # Replace 'updated_model.pkl' with your actual model file  

# Load farm data  
farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv')  # Replace 'Farm_NDRE_TimeSeries.csv' with your actual data file  
farm_names = farm_data['Farm'].tolist()  

# Function to calculate NDRE  
def calculate_ndre(coordinates, start_date, end_date):  
    try:  
        # Define the Earth Engine region of interest (ROI)  
        roi = ee.Geometry.Point(coordinates)  

        # Define the image collection (replace with your actual collection ID and bands)  
        imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
            .filterBounds(roi) \
            .filterDate(start_date, end_date) \
            .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)) #Cloud filtering  
            
        # Function to compute NDRE  
        def ndre(image):  
            red_edge = image.select('B8A')  
            red = image.select('B4')  
            return image.addBands(red_edge.subtract(red).divide(red_edge.add(red)).rename('NDRE'))  

        #Apply NDRE to all images in collection, and reduce to median  
        ndre_image = imageCollection.map(ndre).median().select('NDRE')  

        # Get NDRE value at the point  
        ndre_value = ndre_image.reduceRegion(  
            reducer=ee.Reducer.first(),  
            geometry=roi,  
            scale=10  
        ).getInfo()  

        ndre_value = ndre_value.get('NDRE') #Extract from dictionary  

        return ndre_value  

    except Exception as e:  
        st.error(f"Error calculating NDRE: {e}")  
        return None  


# Streamlit UI  
st.title("Farm Parameter Prediction App")  

# User input  
selected_farm = st.selectbox("Select Farm", Farm)  
farm_age = st.number_input("Farm Age (years)", min_value=0)  
farm_variety = st.text_input("Farm Variety")  
start_date = st.date_input("Start Date")  
end_date = st.date_input("End Date")  


#Find Coordinates based on Farm Name Selection  
selected_farm_data = farm_data[farm_data['Farm'] == selected_farm]  
coordinates = (selected_farm_data['longitude'].iloc[0], selected_farm_data['latitude'].iloc[0])  


if st.button("Calculate NDRE and Show Map"):  
    ndre_value = calculate_ndre(coordinates, start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))  
    if ndre_value is not None:  
        st.write(f"NDRE Value: {ndre_value}")  
        # Map Display (Replace with your actual map display logic)  
        Map = geemap.Map()  
        Map.centerObject(ee.Geometry.Point(coordinates), 12)  

        vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}  
        Map.addLayer(ndre_image, vis_params, 'NDRE')  

        #Display Map  
        Map.to_streamlit(height=500)  

if st.button("Predict"):  
    user_input = pd.DataFrame({  
        'Farm_Name': [selected_farm],  
        'Farm_Age': [farm_age],  
        'Farm_Variety': [farm_variety],  
        'NDRE': [ndre_value] if ndre_value is not None else [0] #Handle cases where ndre_value is None.  Replace 0 with a more suitable default if needed.  
    })  

    # Feature Engineering might be needed here depending on your model's input features  

    prediction = model.predict(user_input)  

    st.write("Predictions:")  
    st.write(f"Brix: {prediction[0][0]}") #Assuming model outputs a list of lists  
    st.write(f"Pol: {prediction[0][1]}")  
    st.write(f"Purity: {prediction[0][2]}")  
    st.write(f"RS: {prediction[0][3]}")