Esmaeilkiani commited on
Commit
d235c3a
1 Parent(s): bd637b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -20
app.py CHANGED
@@ -4,25 +4,27 @@ import joblib
4
  import ee
5
  import geemap
6
 
7
- # Earth Engine Authentication (Replace with your actual authentication)
8
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
9
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
10
  ee.Initialize(credentials)
11
 
12
- # Load pre-trained model
13
  model = joblib.load('updated_model.pkl')
14
-
15
- # Load farm data
16
  farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv')
17
  farm_names = farm_data['Farm'].tolist()
18
 
19
- # Function to calculate NDRE
20
  def calculate_ndre(coordinates, start_date, end_date):
21
  try:
 
 
 
 
22
  roi = ee.Geometry.Point(coordinates)
23
  imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
24
  .filterBounds(roi) \
25
- .filterDate(start_date, end_date) \
26
  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
27
 
28
  def ndre(image):
@@ -44,16 +46,15 @@ def calculate_ndre(coordinates, start_date, end_date):
44
  st.error(f"Error calculating NDRE: {e}")
45
  return None
46
 
47
- # Streamlit UI
48
  st.title("Farm Parameter Prediction App")
49
-
50
- # User input
51
  selected_farm = st.selectbox("Select Farm", farm_names)
52
  farm_age = st.number_input("Farm Age (years)", min_value=0)
53
  farm_variety = st.text_input("Farm Variety")
54
  start_date = st.date_input("Start Date")
55
  end_date = st.date_input("End Date")
56
 
 
57
  selected_farm_data = farm_data[farm_data['Farm'] == selected_farm]
58
  coordinates = (selected_farm_data['longitude'].iloc[0], selected_farm_data['latitude'].iloc[0])
59
 
@@ -67,37 +68,33 @@ if st.button('نمایش نقشه NDRE'):
67
  Map.centerObject(ee.Geometry.Point(coordinates), 12)
68
 
69
  vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}
70
- Map.addLayer(NDRE, vis_params, 'NDRE')
71
  Map.to_streamlit(height=500)
72
  else:
73
  st.error("Unable to calculate NDRE.")
74
 
 
75
  if st.button("Predict"):
76
- # Retrieve NDRE value from session state, default to 0 if not set
77
  ndre_value = st.session_state.get('ndre_value', 0)
78
 
79
- # Prepare the user input DataFrame
80
  user_input = pd.DataFrame({
81
- 'Age': [farm_age], # Rename to match model's expected feature
82
- 'Variety': [farm_variety], # Rename to match model's expected feature
83
- 'NDRE': [ndre_value] # Use the retrieved NDRE value
84
  })
85
 
86
- # Additional features: calculate DayOfYear and Month from the start date
87
  if start_date:
88
  day_of_year = start_date.timetuple().tm_yday
89
  month = start_date.month
90
  user_input['DayOfYear'] = [day_of_year]
91
  user_input['Month'] = [month]
92
 
93
- # Reorder the columns to match the order expected by the model
94
  user_input = user_input[['Age', 'DayOfYear', 'Month', 'Variety', 'NDRE']]
95
 
96
- # Make predictions
97
  prediction = model.predict(user_input)
98
 
99
  st.write("Predictions:")
100
- st.write(f"Brix: {prediction[0][0]}") # Assuming model outputs a list of lists
101
  st.write(f"Pol: {prediction[0][1]}")
102
  st.write(f"Purity: {prediction[0][2]}")
103
- st.write(f"RS: {prediction[0][3]}")
 
4
  import ee
5
  import geemap
6
 
7
+ # Authenticate Earth Engine
8
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
9
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
10
  ee.Initialize(credentials)
11
 
12
+ # Load model and farm data
13
  model = joblib.load('updated_model.pkl')
 
 
14
  farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv')
15
  farm_names = farm_data['Farm'].tolist()
16
 
17
+ # Function to calculate NDRE
18
  def calculate_ndre(coordinates, start_date, end_date):
19
  try:
20
+ # Convert start_date and end_date to strings
21
+ start_date_str = start_date.strftime('%Y-%m-%d')
22
+ end_date_str = end_date.strftime('%Y-%m-%d')
23
+
24
  roi = ee.Geometry.Point(coordinates)
25
  imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
26
  .filterBounds(roi) \
27
+ .filterDate(start_date_str, end_date_str) \
28
  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
29
 
30
  def ndre(image):
 
46
  st.error(f"Error calculating NDRE: {e}")
47
  return None
48
 
49
+ # Streamlit User Interface
50
  st.title("Farm Parameter Prediction App")
 
 
51
  selected_farm = st.selectbox("Select Farm", farm_names)
52
  farm_age = st.number_input("Farm Age (years)", min_value=0)
53
  farm_variety = st.text_input("Farm Variety")
54
  start_date = st.date_input("Start Date")
55
  end_date = st.date_input("End Date")
56
 
57
+ # Handling Farm Data Selection and NDRE Calculation
58
  selected_farm_data = farm_data[farm_data['Farm'] == selected_farm]
59
  coordinates = (selected_farm_data['longitude'].iloc[0], selected_farm_data['latitude'].iloc[0])
60
 
 
68
  Map.centerObject(ee.Geometry.Point(coordinates), 12)
69
 
70
  vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}
71
+ Map.addLayer(ee.Image(NDRE), vis_params, 'NDRE')
72
  Map.to_streamlit(height=500)
73
  else:
74
  st.error("Unable to calculate NDRE.")
75
 
76
+ # Making Predictions Using the Loaded Model
77
  if st.button("Predict"):
 
78
  ndre_value = st.session_state.get('ndre_value', 0)
79
 
 
80
  user_input = pd.DataFrame({
81
+ 'Age': [farm_age],
82
+ 'Variety': [farm_variety],
83
+ 'NDRE': [ndre_value]
84
  })
85
 
 
86
  if start_date:
87
  day_of_year = start_date.timetuple().tm_yday
88
  month = start_date.month
89
  user_input['DayOfYear'] = [day_of_year]
90
  user_input['Month'] = [month]
91
 
 
92
  user_input = user_input[['Age', 'DayOfYear', 'Month', 'Variety', 'NDRE']]
93
 
 
94
  prediction = model.predict(user_input)
95
 
96
  st.write("Predictions:")
97
+ st.write(f"Brix: {prediction[0][0]}")
98
  st.write(f"Pol: {prediction[0][1]}")
99
  st.write(f"Purity: {prediction[0][2]}")
100
+ st.write(f"RS: {prediction[0][3]}")