Esmaeilkianii commited on
Commit
0d6ff3d
·
verified ·
1 Parent(s): 473d3b5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -108
app.py CHANGED
@@ -1,130 +1,109 @@
1
- import ee
2
  import streamlit as st
3
- import folium
4
  import pandas as pd
 
 
 
 
5
  import requests
6
- from datetime import datetime, timedelta
 
 
 
7
 
8
- # احراز هویت با Google Earth Engine
9
  service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com'
10
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-cfdea6eaf411.json')
11
  ee.Initialize(credentials)
12
 
13
- # جمع‌آوری داده‌ها از Google Earth Engine
14
- def get_indices(aoi, start_date, end_date):
15
- sentinel2 = ee.ImageCollection('COPERNICUS/S2') \
16
- .filterBounds(aoi) \
17
- .filterDate(start_date, end_date) \
18
- .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
19
-
 
 
 
 
 
 
20
  def calculate_indices(image):
21
  ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
22
  ndwi = image.normalizedDifference(['B3', 'B8']).rename('NDWI')
23
  ndre = image.normalizedDifference(['B8', 'B5']).rename('NDRE')
24
- lai = image.expression('2.76 * (NDVI / (1 - NDVI))', {'NDVI': ndvi}).rename('LAI')
25
- chl = image.expression('(NIR / RED) - 1', {'NIR': image.select('B8'), 'RED': image.select('B4')}).rename('CHL')
26
  return image.addBands([ndvi, ndwi, ndre, lai, chl])
 
 
27
 
28
- indices = sentinel2.map(calculate_indices)
29
- return indices
30
-
31
- # خواندن فایل CSV برای مشخصات مزارع
32
- farm_coordinates = pd.read_csv('farm_coordinates.csv')
33
-
34
- # خواندن فایل CSV برای داده‌های روزانه مزارع
35
  daily_data = pd.read_csv('پایگاه داده (1).csv')
36
 
37
- # نمایش نقشه و شاخص‌ها
38
- def display_map(indices, aoi):
39
- map_center = [aoi.centroid().coordinates().getInfo()[1], aoi.centroid().coordinates().getInfo()[0]]
40
- m = folium.Map(location=map_center, zoom_start=12)
41
-
42
- ndvi_image = indices.select('NDVI').mean()
43
- ndwi_image = indices.select('NDWI').mean()
44
-
45
- ndvi_vis_params = {
46
- 'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']
47
- }
48
- ndwi_vis_params = {
49
- 'min': -1, 'max': 1, 'palette': ['blue', 'white', 'green']
50
- }
51
 
52
- ndvi_url = ndvi_image.getMapId(ndvi_vis_params)['tile_fetcher'].url_format
53
- ndwi_url = ndwi_image.getMapId(ndwi_vis_params)['tile_fetcher'].url_format
 
54
 
55
- folium.TileLayer(tiles=ndvi_url, attr='NDVI', overlay=True, name='NDVI').add_to(m)
56
- folium.TileLayer(tiles=ndwi_url, attr='NDWI', overlay=True, name='NDWI').add_to(m)
57
- folium.LayerControl().add_to(m)
 
 
 
58
 
59
- return m
 
60
 
61
- # مقایسه شاخص‌ها
62
- def compare_indices(indices):
63
- ndvi_chart = indices.select('NDVI').getRegion(aoi, 30).getInfo()
64
- ndwi_chart = indices.select('NDWI').getRegion(aoi, 30).getInfo()
65
- ndre_chart = indices.select('NDRE').getRegion(aoi, 30).getInfo()
66
- lai_chart = indices.select('LAI').getRegion(aoi, 30).getInfo()
67
-
68
- return ndvi_chart, ndwi_chart, ndre_chart, lai_chart
69
-
70
- # نمایش داده‌های آب و هوا
71
- def get_weather_data(lat, lon):
72
- api_key = 'ed47316a45379e2221a75f813229fb46'
73
- url = f'http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}'
74
- response = requests.get(url)
75
- data = response.json()
76
- return data
77
-
78
- # گزارش‌های هفتگی
79
- def weekly_report(indices, aoi):
80
- lai_chart = indices.select('LAI').getRegion(aoi, 30).getInfo()
81
- return lai_chart
82
-
83
- # کد Streamlit برای نمایش نتایج
84
- st.title('مانیتورینگ مزارع نیشکر')
85
-
86
- # انتخاب مزرعه
87
- farm_name = st.selectbox('انتخاب مزرعه', farm_coordinates['name'].unique())
88
- farm_info = farm_coordinates[farm_coordinates['name'] == farm_name].iloc[0]
89
-
90
- # انتخاب روز هفته
91
- day_of_week = st.selectbox('انتخاب روز هفته', daily_data['روز'].unique())
92
- daily_info = daily_data[daily_data['روز'] == day_of_week]
93
-
94
- # تعیین منطقه جغرافیایی
95
- aoi = ee.Geometry.Point([farm_info['longitude'], farm_info['latitude']]).buffer(500)
96
-
97
- # تعیین دوره زمانی
98
  start_date = '2023-01-01'
99
  end_date = '2023-12-31'
100
-
101
- # جمع‌آوری داده‌ها
102
- indices = get_indices(aoi, start_date, end_date)
103
-
104
- # نمایش نقشه
105
- st.subheader('نقشه شاخص‌ها')
106
- m = display_map(indices, aoi)
107
- st_folium = folium.Map(location=[farm_info['latitude'], farm_info['longitude']], zoom_start=12)
108
- st_folium.add_child(m)
109
- st_data = st_folium._repr_html_()
110
- st.components.v1.html(st_data, height=600)
111
-
112
- # مقایسه شاخص‌ها
113
- st.subheader('مقایسه شاخص‌ها')
114
- ndvi_chart, ndwi_chart, ndre_chart, lai_chart = compare_indices(indices)
115
- st.line_chart(ndvi_chart)
116
- st.line_chart(ndwi_chart)
117
- st.line_chart(ndre_chart)
118
- st.line_chart(lai_chart)
119
-
120
- # نمایش داده‌های آب و هوا
121
- st.subheader('داده‌های آب و هوا')
122
- weather_data = get_weather_data(farm_info['latitude'], farm_info['longitude'])
123
- st.write(f"دما: {weather_data['main']['temp']}°C")
124
- st.write(f"رطوبت: {weather_data['main']['humidity']}%")
125
- st.write(f"سرعت باد: {weather_data['wind']['speed']} m/s")
126
-
127
- # گزارش‌های هفتگی
128
- st.subheader('گزارش‌های هفتگی')
129
- lai_chart = weekly_report(indices, aoi)
130
- st.line_chart(lai_chart)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
 
2
  import pandas as pd
3
+ import folium
4
+ import ee
5
+ import json
6
+ from datetime import datetime
7
  import requests
8
+ import geemap.foliumap as geemap
9
+ from streamlit_folium import st_folium
10
+ import plotly.express as px
11
+ import plotly.graph_objects as go
12
 
13
+ # Set up the Google Earth Engine with service account
14
  service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com'
15
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-cfdea6eaf411.json')
16
  ee.Initialize(credentials)
17
 
18
+ # Function to fetch weather data from OpenWeather API
19
+ def get_weather_data(lat, lon, api_key):
20
+ url = f'http://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=metric'
21
+ response = requests.get(url)
22
+ return response.json()
23
+
24
+ # Function to fetch satellite data and calculate indices
25
+ def get_sentinel_data(aoi, start_date, end_date):
26
+ collection = ee.ImageCollection('COPERNICUS/S2') \
27
+ .filterBounds(aoi) \
28
+ .filterDate(start_date, end_date) \
29
+ .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
30
+
31
  def calculate_indices(image):
32
  ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
33
  ndwi = image.normalizedDifference(['B3', 'B8']).rename('NDWI')
34
  ndre = image.normalizedDifference(['B8', 'B5']).rename('NDRE')
35
+ lai = image.expression('3.618 * ((NIR / RED) - 1)', {'NIR': image.select('B8'), 'RED': image.select('B4')}).rename('LAI')
36
+ chl = image.expression('1.5 * ((NIR / RED) - 1)', {'NIR': image.select('B8'), 'RED': image.select('B4')}).rename('CHL')
37
  return image.addBands([ndvi, ndwi, ndre, lai, chl])
38
+
39
+ return collection.map(calculate_indices)
40
 
41
+ # Load farm coordinates and daily data
42
+ farm_coords = pd.read_csv('farm_coordinates.csv')
 
 
 
 
 
43
  daily_data = pd.read_csv('پایگاه داده (1).csv')
44
 
45
+ # Streamlit UI
46
+ st.title('Sugarcane Farm Monitoring System')
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ # Select farm
49
+ farm_name = st.selectbox('Select a farm', farm_coords['name'].unique())
50
+ selected_farm = farm_coords[farm_coords['name'] == farm_name].iloc[0]
51
 
52
+ # Display weather data
53
+ weather_data = get_weather_data(selected_farm['latitude'], selected_farm['longitude'], 'ed47316a45379e2221a75f813229fb46')
54
+ st.subheader('Weather Data')
55
+ st.write(f"Temperature: {weather_data['main']['temp']} °C")
56
+ st.write(f"Humidity: {weather_data['main']['humidity']} %")
57
+ st.write(f"Wind Speed: {weather_data['wind']['speed']} m/s")
58
 
59
+ # Define Area of Interest (AOI)
60
+ aoi = ee.Geometry.Point([selected_farm['longitude'], selected_farm['latitude']]).buffer(1000).bounds()
61
 
62
+ # Fetch satellite data for the year 2023
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  start_date = '2023-01-01'
64
  end_date = '2023-12-31'
65
+ sentinel_data = get_sentinel_data(aoi, start_date, end_date)
66
+
67
+ # Function to display map with indices
68
+ def display_map(image, index, vis_params):
69
+ map_ = geemap.Map(center=[selected_farm['latitude'], selected_farm['longitude']], zoom=13)
70
+ map_.addLayer(image.select(index), vis_params, index)
71
+ map_.setCenter(selected_farm['longitude'], selected_farm['latitude'], 13)
72
+ return map_
73
+
74
+ # Display maps for NDVI and NDWI
75
+ ndvi_map = display_map(sentinel_data.mean(), 'NDVI', {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']})
76
+ ndwi_map = display_map(sentinel_data.mean(), 'NDWI', {'min': -1, 'max': 1, 'palette': ['blue', 'white', 'green']})
77
+
78
+ st.subheader('NDVI Map')
79
+ st_folium(ndvi_map)
80
+
81
+ st.subheader('NDWI Map')
82
+ st_folium(ndwi_map)
83
+
84
+ # Function to generate comparison charts
85
+ def generate_comparison_charts(data, indices):
86
+ fig = go.Figure()
87
+ for index in indices:
88
+ fig.add_trace(go.Scatter(x=data['date'], y=data[index], mode='lines', name=index))
89
+ return fig
90
+
91
+ # Generate comparison charts
92
+ indices = ['NDVI', 'NDWI', 'NDRE', 'LAI', 'CHL']
93
+ index_data = sentinel_data.reduceRegions(reducer=ee.Reducer.mean(), collection=aoi, scale=10).getInfo()
94
+ index_df = pd.DataFrame(index_data['features'])
95
+ index_df['date'] = pd.to_datetime(index_df['properties.date'])
96
+ index_df.set_index('date', inplace=True)
97
+
98
+ fig = generate_comparison_charts(index_df, indices)
99
+ st.subheader('Index Comparison')
100
+ st.plotly_chart(fig)
101
+
102
+ # Weekly reports
103
+ st.subheader('Weekly Reports')
104
+ weekly_report = index_df.resample('W').mean()
105
+ st.table(weekly_report)
106
+
107
+ # Run the Streamlit app
108
+ if __name__ == '__main__':
109
+ st.run()