Esmaeilkianii commited on
Commit
d6c077d
·
verified ·
1 Parent(s): 4b22250

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -107
app.py CHANGED
@@ -1,112 +1,159 @@
1
- import ee
2
- import json
3
- import pandas as pd
4
  import streamlit as st
5
- import folium
6
- from branca.colormap import linear
7
  import plotly.express as px
8
- import requests
 
 
 
 
9
 
10
- # Authentication with Google Earth Engine
11
- credentials = ee.ServiceAccountCredentials('ee-esmaeilkiani13877-cfdea6eaf411.json', 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com')
 
12
  ee.Initialize(credentials)
13
 
14
- # Define the Area of Interest (AOI)
15
- aoi = ee.Geometry.Rectangle([-118.806, 33.914, -118.770, 33.941]) # Example coordinates, adjust as necessary
16
-
17
- # Functions to calculate indices
18
- def calculate_ndvi(image):
19
- return image.normalizedDifference(['B8', 'B4'])
20
-
21
- def calculate_ndwi(image):
22
- return image.normalizedDifference(['B3', 'B8'])
23
-
24
- def calculate_ndre(image):
25
- return image.normalizedDifference(['B8', 'B5'])
26
-
27
- def calculate_lai(image):
28
- return image.expression('2.5 * (B8 - B4) / (B8 + B4 + 0.5)', {
29
- 'B8': image.select('B8'),
30
- 'B4': image.select('B4')
31
- })
32
-
33
- def calculate_chl(image):
34
- return image.expression('10 * (B8 - B4) / (B8 + B4)', {
35
- 'B8': image.select('B8'),
36
- 'B4': image.select('B4')
37
- })
38
-
39
- # Use Sentinel-2 data
40
- sentinel2 = ee.ImageCollection('COPERNICUS/S2').filterBounds(aoi).filterDate('2023-01-01', '2023-12-31')
41
- ndvi = sentinel2.map(calculate_ndvi)
42
- ndwi = sentinel2.map(calculate_ndwi)
43
- ndre = sentinel2.map(calculate_ndre)
44
- lai = sentinel2.map(calculate_lai)
45
- chl = sentinel2.map(calculate_chl)
46
-
47
- # Load CSV files
48
- farm_coords = pd.read_csv('farm_coordinates.csv')
49
- daily_farm_data = pd.read_csv('پایگاه داده (1).csv', encoding='utf-8')
50
-
51
- # Weather API Key
52
- API_KEY = 'ed47316a45379e2221a75f813229fb46'
53
-
54
- def get_weather_data(latitude, longitude):
55
- url = f"http://api.openweathermap.org/data/2.5/weather?lat={latitude}&lon={longitude}&appid={API_KEY}&units=metric"
56
- response = requests.get(url)
57
- return response.json()
58
-
59
- def create_map(ndvi_image):
60
- map = folium.Map()
61
- folium.TileLayer('OpenStreetMap').add_to(map)
62
- map_bounds = aoi.getInfo()['coordinates'][0]
63
- map.add_child(folium.raster_layers.ImageOverlay(
64
- image=ndvi_image.getMapId()['tile_fetcher'].url_format,
65
- bounds=map_bounds,
66
- opacity=0.7
67
- ))
68
- colormap = linear.YlOrRd_09.scale(0, 1)
69
- colormap.caption = 'NDVI'
70
- colormap.add_to(map)
71
- return map
72
-
73
- def generate_weekly_report(farm_name):
74
- # Pseudo code for weekly comparison, you'd need to implement actual data retrieval
75
- last_week_lai = lai.filterDate('last_week_start', 'last_week_end').mean().getInfo()
76
- this_week_lai = lai.filterDate('this_week_start', 'this_week_end').mean().getInfo()
77
- comparison = "LAI increased by" if this_week_lai > last_week_lai else "LAI decreased by"
78
- st.write(f"Weekly Report for {farm_name}: {comparison} {abs(this_week_lai - last_week_lai)}")
79
-
80
- # Streamlit App
81
- st.title('Sugarcane Farm Monitoring')
82
-
83
- # Dropdown for farm selection
84
- farm = st.selectbox('Select Farm', farm_coords['name'])
85
-
86
- # Display NDVI Map
87
- st.write('NDVI Map')
88
- ndvi_map = create_map(ndvi.mean())
89
- st.components.v1.html(ndvi_map._repr_html_(), width=800, height=600)
90
-
91
- # Display Weather Data
92
- st.write('Weather Data')
93
- if farm in farm_coords['name'].values:
94
- farm_data = farm_coords[farm_coords['name'] == farm].iloc[0]
95
- weather_info = get_weather_data(farm_data['latitude'], farm_data['longitude'])
96
- st.write(f"Temperature: {weather_info['main']['temp']}°C")
97
- st.write(f"Humidity: {weather_info['main']['humidity']}%")
98
- st.write(f"Wind Speed: {weather_info['wind']['speed']} m/s")
99
- else:
100
- st.write("Farm not found in the dataset.")
101
-
102
- # Weekly Report
103
- st.write('Weekly Report')
104
- generate_weekly_report(farm)
105
-
106
- # Time Series Plot for NDVI
107
- st.write('NDVI Time Series')
108
- fig = px.line(ndvi.getRegion(aoi, 30).getInfo(), x='system:time_start', y='nd')
109
- st.plotly_chart(fig)
110
-
111
- # Note: This script assumes you have the necessary permissions, setup, and libraries installed.
112
- # Also, replace placeholder data with real-time data where applicable.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
 
3
  import plotly.express as px
4
+ import folium
5
+ from streamlit_folium import folium_static
6
+ import ee
7
+ import datetime
8
+ import os
9
 
10
+ # Set up Google Earth Engine
11
+ service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com'
12
+ credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-cfdea6eaf411.json')
13
  ee.Initialize(credentials)
14
 
15
+ # Load farm data
16
+ @st.cache_data
17
+ def load_farm_data():
18
+ return pd.read_csv('farm_coordinates.csv')
19
+
20
+ farms = load_farm_data()
21
+
22
+ # Streamlit app
23
+ st.title('Sugarcane Farm Dashboard')
24
+
25
+ # Sidebar
26
+ st.sidebar.title('Navigation')
27
+ page = st.sidebar.radio('Go to', ['Map', 'Comparative Charts', 'Weekly Reports'])
28
+
29
+ if page == 'Map':
30
+ st.header('Sugarcane Farm Map')
31
+
32
+ # Create map
33
+ m = folium.Map(location=[farms['latitude'].mean(), farms['longitude'].mean()], zoom_start=10)
34
+
35
+ # Add markers for each farm
36
+ for idx, row in farms.iterrows():
37
+ folium.Marker(
38
+ location=[row['latitude'], row['longitude']],
39
+ popup=f"Farm: {row['name']}, Age: {row['age']}, Variety: {row['variety']}",
40
+ icon=folium.Icon(color='green', icon='leaf')
41
+ ).add_to(m)
42
+
43
+ # Display map
44
+ folium_static(m)
45
+
46
+ # Farm search
47
+ search_farm = st.text_input('Search for a farm:')
48
+ if search_farm:
49
+ farm = farms[farms['name'].str.contains(search_farm, case=False)]
50
+ if not farm.empty:
51
+ st.write(f"Farm found: {farm['name'].values[0]}")
52
+ st.map(farm)
53
+ else:
54
+ st.write("Farm not found.")
55
+
56
+ elif page == 'Comparative Charts':
57
+ st.header('Comparative Charts')
58
+
59
+ # Function to get NDVI data
60
+ def get_ndvi_data(geometry, start_date, end_date):
61
+ collection = ee.ImageCollection('COPERNICUS/S2_SR') \
62
+ .filterBounds(geometry) \
63
+ .filterDate(start_date, end_date) \
64
+ .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
65
+
66
+ def addNDVI(image):
67
+ ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
68
+ return image.addBands(ndvi)
69
+
70
+ ndvi_collection = collection.map(addNDVI)
71
+ ndvi_values = ndvi_collection.select('NDVI').mean().reduceRegion(
72
+ reducer=ee.Reducer.mean(),
73
+ geometry=geometry,
74
+ scale=10
75
+ ).get('NDVI')
76
+
77
+ return ndvi_values.getInfo()
78
+
79
+ # Function to get LAI data
80
+ def get_lai_data(geometry, start_date, end_date):
81
+ collection = ee.ImageCollection('MODIS/006/MOD15A2H') \
82
+ .filterBounds(geometry) \
83
+ .filterDate(start_date, end_date)
84
+
85
+ lai_values = collection.select('Lai_500m').mean().reduceRegion(
86
+ reducer=ee.Reducer.mean(),
87
+ geometry=geometry,
88
+ scale=500
89
+ ).get('Lai_500m')
90
+
91
+ return lai_values.getInfo()
92
+
93
+ # Date range selection
94
+ start_date = st.date_input('Start date', datetime.date(2023, 1, 1))
95
+ end_date = st.date_input('End date', datetime.date.today())
96
+
97
+ if start_date < end_date:
98
+ # Get NDVI and LAI data for each farm
99
+ ndvi_data = []
100
+ lai_data = []
101
+ for idx, row in farms.iterrows():
102
+ geometry = ee.Geometry.Point([row['longitude'], row['latitude']])
103
+ ndvi = get_ndvi_data(geometry, start_date.isoformat(), end_date.isoformat())
104
+ lai = get_lai_data(geometry, start_date.isoformat(), end_date.isoformat())
105
+ ndvi_data.append({'Farm': row['name'], 'NDVI': ndvi})
106
+ lai_data.append({'Farm': row['name'], 'LAI': lai})
107
+
108
+ ndvi_df = pd.DataFrame(ndvi_data)
109
+ lai_df = pd.DataFrame(lai_data)
110
+
111
+ # NDVI chart
112
+ fig_ndvi = px.bar(ndvi_df, x='Farm', y='NDVI', title='NDVI Comparison')
113
+ st.plotly_chart(fig_ndvi)
114
+
115
+ # LAI chart
116
+ fig_lai = px.bar(lai_df, x='Farm', y='LAI', title='LAI Comparison')
117
+ st.plotly_chart(fig_lai)
118
+ else:
119
+ st.error('Error: End date must fall after start date.')
120
+
121
+ elif page == 'Weekly Reports':
122
+ st.header('Weekly Reports')
123
+
124
+ # Farm selection
125
+ selected_farm = st.selectbox('Select a farm:', farms['name'])
126
+
127
+ # Week selection
128
+ week = st.slider('Select week:', 1, 52, 1)
129
+
130
+ # Simulate weekly data (replace this with actual data processing)
131
+ def get_weekly_data(farm, week):
132
+ return {
133
+ 'NDVI': 0.5 + 0.1 * week, # Simulated increasing NDVI
134
+ 'LAI': 2 + 0.2 * week, # Simulated increasing LAI
135
+ }
136
+
137
+ data = get_weekly_data(selected_farm, week)
138
+
139
+ # Display weekly report
140
+ st.subheader(f'Weekly Report for {selected_farm} - Week {week}')
141
+
142
+ col1, col2 = st.columns(2)
143
+ with col1:
144
+ st.metric(label="NDVI 🌱", value=f"{data['NDVI']:.2f}")
145
+ with col2:
146
+ st.metric(label="LAI 🌡", value=f"{data['LAI']:.2f}")
147
+
148
+ # Trend chart
149
+ weeks = list(range(1, week + 1))
150
+ trend_data = [get_weekly_data(selected_farm, w) for w in weeks]
151
+ trend_df = pd.DataFrame(trend_data)
152
+ trend_df['Week'] = weeks
153
+
154
+ fig = px.line(trend_df, x='Week', y=['NDVI', 'LAI'], title=f'Trend for {selected_farm}')
155
+ st.plotly_chart(fig)
156
+
157
+ # Footer
158
+ st.sidebar.markdown('---')
159
+ st.sidebar.text('Dashboard created with Streamlit')