File size: 3,608 Bytes
d5b2220
 
 
 
 
5882ae2
d235c3a
33af4fe
 
d5b2220
 
d235c3a
10ebae5
 
d4ca3a4
d5b2220
d235c3a
d5b2220
 
d235c3a
 
 
 
d5b2220
 
 
d235c3a
10ebae5
d5b2220
 
 
 
 
 
 
 
 
 
 
 
 
 
10ebae5
d5b2220
 
 
 
 
d235c3a
d5b2220
b56eaae
d5b2220
 
 
 
 
d235c3a
d5b2220
 
 
032cf90
 
10ebae5
5284fe6
10ebae5
 
d5b2220
 
 
8d91969
d235c3a
d5b2220
10ebae5
 
d5b2220
d235c3a
d5b2220
5284fe6
bd637b6
d5b2220
d235c3a
 
 
bd637b6
 
 
 
 
 
 
 
 
 
5284fe6
 
 
d235c3a
cefdbbd
 
d235c3a
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
import streamlit as st  
import pandas as pd  
import joblib  
import ee  
import geemap  

# Authenticate 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 model and farm data
model = joblib.load('updated_model.pkl')  
farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv')  
farm_names = farm_data['Farm'].tolist()  

# Function to calculate NDRE
def calculate_ndre(coordinates, start_date, end_date):  
    try:  
        # Convert start_date and end_date to strings
        start_date_str = start_date.strftime('%Y-%m-%d')
        end_date_str = end_date.strftime('%Y-%m-%d')

        roi = ee.Geometry.Point(coordinates)  
        imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
            .filterBounds(roi) \
            .filterDate(start_date_str, end_date_str) \
            .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))  
            
        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'))  

        ndre_image = imageCollection.map(ndre).median().select('NDRE')  

        ndre_value = ndre_image.reduceRegion(  
            reducer=ee.Reducer.first(),  
            geometry=roi,  
            scale=10  
        ).getInfo()  

        return ndre_value.get('NDRE') if ndre_value else None  

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

# Streamlit User Interface
st.title("Farm Parameter Prediction App")  
selected_farm = st.selectbox("Select Farm", farm_names)  
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")  

# Handling Farm Data Selection and NDRE Calculation
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('نمایش نقشه NDRE'):
    NDRE = calculate_ndre(coordinates, start_date, end_date)
    if NDRE is not None:
        st.session_state.ndre_value = NDRE  # Store NDRE in session state
        st.write(f'شاخص NDRE: {NDRE}')  
        
        Map = geemap.Map()  
        Map.centerObject(ee.Geometry.Point(coordinates), 12)  

        vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}  
        Map.addLayer(ee.Image(NDRE), vis_params, 'NDRE')  
        Map.to_streamlit(height=500)  
    else:
        st.error("Unable to calculate NDRE.")

# Making Predictions Using the Loaded Model
if st.button("Predict"):  
    ndre_value = st.session_state.get('ndre_value', 0)  
    
    user_input = pd.DataFrame({  
        'Age': [farm_age],  
        'Variety': [farm_variety],  
        'NDRE': [ndre_value]  
    })
    
    if start_date:
        day_of_year = start_date.timetuple().tm_yday
        month = start_date.month
        user_input['DayOfYear'] = [day_of_year]
        user_input['Month'] = [month]

    user_input = user_input[['Age', 'DayOfYear', 'Month', 'Variety', 'NDRE']]

    prediction = model.predict(user_input)  

    st.write("Predictions:")  
    st.write(f"Brix: {prediction[0][0]}")  
    st.write(f"Pol: {prediction[0][1]}")  
    st.write(f"Purity: {prediction[0][2]}")  
    st.write(f"RS: {prediction[0][3]}")