AppSugarcane / app.py
Esmaeilkiani's picture
Update app.py
d235c3a verified
raw
history blame
3.61 kB
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]}")