Esmaeilkiani commited on
Commit
ddd1a18
·
verified ·
1 Parent(s): d05fcc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -188
app.py CHANGED
@@ -1,208 +1,111 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import numpy as np
4
  import ee
5
  import geemap
6
- import geopandas as gpd
7
- from datetime import datetime, timedelta
8
  import folium
9
  from streamlit_folium import folium_static
10
- import plotly.express as px
11
- import io
12
- import requests
13
 
14
  # Initialize Earth Engine
15
- def initialize_ee():
16
- try:
17
- service_account = 'esmaeil-kiani1387-gmail-com@ee-esmaeilkiani13877.iam.gserviceaccount.com'
18
- credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-9a054809a4bb.json')
19
- ee.Initialize(credentials)
20
- return True
21
- except Exception as e:
22
- st.error(f"خطا در راه‌اندازی Earth Engine: {str(e)}")
23
- return False
24
-
25
- # Set page config
26
- st.set_page_config(
27
- page_title="تحلیل پوشش گیاهی مزارع",
28
- layout="wide",
29
- initial_sidebar_state="expanded"
30
- )
31
-
32
- # Custom styling
33
- st.markdown("""
34
- <style>
35
- .main {
36
- background-color: #f5f5f5;
37
- }
38
- .stButton>button {
39
- background-color: #2E4057;
40
- color: white;
41
- border-radius: 8px;
42
- padding: 0.75rem 1.5rem;
43
- font-weight: 600;
44
- }
45
- .stSelectbox {
46
- background-color: white;
47
- border-radius: 8px;
48
- }
49
- .plot-container {
50
- background-color: white;
51
- border-radius: 15px;
52
- padding: 1rem;
53
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
54
- }
55
- body {
56
- direction: rtl;
57
- font-family: 'Vazirmatn', sans-serif;
58
- }
59
- </style>
60
- """, unsafe_allow_html=True)
61
-
62
- # Constants
63
- DEFAULT_LOCATION = {
64
- "latitude": 31.534442,
65
- "longitude": 48.724416,
66
- "name": "شرکت کشت و صنعت نیشکر دهخدا"
67
- }
68
-
69
- NDVI_PALETTE = [
70
- '#d73027', '#f46d43', '#fdae61', '#fee08b', '#ffffbf',
71
- '#d9ef8b', '#a6d96a', '#66bd63', '#1a9850'
72
- ]
73
 
 
74
  @st.cache_data
75
- def load_farm_data():
76
- try:
77
- CSV_URL = "https://hebbkx1anhila5yf.public.blob.vercel-storage.com/tableConvert.com_wftamx-1UC3HLMMTZ9WN2ePEhHQLU2Knn0ACl.csv"
78
- response = requests.get(CSV_URL)
79
- response.raise_for_status()
80
- csv_content = response.content.decode('utf-8')
81
- df = pd.read_csv(io.StringIO(csv_content))
82
- return df
83
- except Exception as e:
84
- st.error(f"خطا در بارگیری داده‌های مزارع: {str(e)}")
85
- return None
86
-
87
- def calculate_ndvi(image):
88
- ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
89
- return image.addBands(ndvi)
90
 
91
- def get_sentinel_collection(start_date, end_date, geometry):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  return (ee.ImageCollection('COPERNICUS/S2_SR')
93
- .filterDate(start_date, end_date)
94
  .filterBounds(geometry)
95
- .map(calculate_ndvi)
96
- .select('NDVI'))
97
-
98
- def create_ndvi_visualization(start_date, end_date, wheat_only=False):
99
- try:
100
- # Create geometry from default location
101
- point = ee.Geometry.Point([DEFAULT_LOCATION['longitude'], DEFAULT_LOCATION['latitude']])
102
- region = point.buffer(5000) # 5km buffer
103
 
104
- # Get Sentinel-2 collection
105
- collection = get_sentinel_collection(start_date, end_date, region)
106
-
107
- # Calculate mean NDVI
108
- ndvi = collection.mean()
109
-
110
- # Visualization parameters
111
- vis_params = {
112
- 'min': -1,
113
- 'max': 1,
114
- 'palette': NDVI_PALETTE
115
- }
116
-
117
- if wheat_only:
118
- # Load wheat farm locations
119
- farms_df = load_farm_data()
120
- wheat_farms = farms_df[farms_df['crop_type'] == 'wheat']
121
-
122
- # Create mask for wheat farms
123
- wheat_mask = ee.FeatureCollection(
124
- wheat_farms.apply(
125
- lambda x: ee.Feature(
126
- ee.Geometry.Point([x['longitude'], x['latitude']])
127
- ),
128
- axis=1
129
- ).tolist()
130
- ).geometry().buffer(100) # 100m buffer around wheat farms
131
-
132
- # Apply mask
133
- ndvi = ndvi.updateMask(wheat_mask)
134
-
135
- # Create the map
136
- Map = geemap.Map(center=[DEFAULT_LOCATION['latitude'], DEFAULT_LOCATION['longitude']], zoom=12)
137
- Map.add_layer(ndvi, vis_params, 'NDVI')
138
-
139
- # Add legend
140
- Map.add_legend(title="NDVI Values", colors=NDVI_PALETTE,
141
- labels=[f"{i:.1f}" for i in np.linspace(-1, 1, len(NDVI_PALETTE))])
142
-
143
- return Map
144
 
145
- except Exception as e:
146
- st.error(f"خطا در محاسبه NDVI: {str(e)}")
147
- return None
148
 
149
- def main():
150
- # Initialize Earth Engine
151
- if not initialize_ee():
152
- return
153
 
154
- st.title("تحلیل شاخص NDVI مزارع")
 
155
 
156
- # Date selection
157
- col1, col2 = st.columns(2)
158
  with col1:
159
- start_date = st.date_input(
160
- "تاریخ شروع",
161
- datetime.now() - timedelta(days=30),
162
- help="تاریخ شروع برای محاسبه NDVI"
163
- )
164
  with col2:
165
- end_date = st.date_input(
166
- "تاریخ پایان",
167
- datetime.now(),
168
- help="تاریخ پایان برای محاسبه NDVI"
169
- )
170
-
171
- # Wheat farms filter
172
- wheat_only = st.checkbox("نمایش فقط مزارع گندم", help="فیلتر کردن نقشه برای نمایش فقط مزارع گندم")
173
-
174
- if st.button("محاسبه NDVI"):
175
- with st.spinner("در حال محاسبه NDVI..."):
176
- start_time = datetime.now()
177
-
178
- # Create NDVI visualization
179
- Map = create_ndvi_visualization(
180
- start_date.strftime("%Y-%m-%d"),
181
- end_date.strftime("%Y-%m-%d"),
182
- wheat_only
183
- )
184
-
185
- if Map:
186
- # Display the map
187
- Map.to_streamlit(height=600)
188
-
189
- # Display processing time
190
- end_time = datetime.now()
191
- processing_time = (end_time - start_time).total_seconds()
192
- st.info(f"زمان پردازش: {processing_time:.2f} ثانیه")
193
-
194
- # Display NDVI information
195
- st.markdown("""
196
- <div class="plot-container">
197
- <h3>راهنمای تفسیر NDVI</h3>
198
- <ul>
199
- <li>مقادیر نزدیک به 1 (سبز تیره): پوشش گیاهی متراکم</li>
200
- <li>مقادیر متوسط (زرد تا سبز روشن): پوشش گیاهی متوسط</li>
201
- <li>مقادیر نزدیک به 0 (نارنجی): پوشش گیاهی کم یا خاک لخت</li>
202
- <li>مقادیر منفی (قرمز): آب یا ابر</li>
203
- </ul>
204
- </div>
205
- """, unsafe_allow_html=True)
206
-
207
- if __name__ == "__main__":
208
- main()
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import geopandas as gpd
4
  import ee
5
  import geemap
 
 
6
  import folium
7
  from streamlit_folium import folium_static
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+ from datetime import datetime, timedelta
11
 
12
  # Initialize Earth Engine
13
+ service_account = 'esmaeil-kiani1387-gmail-com@ee-esmaeilkiani13877.iam.gserviceaccount.com'
14
+ credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-9a054809a4bb.json')
15
+ ee.Initialize(credentials)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Load farm data
18
  @st.cache_data
19
+ def load_data():
20
+ df = pd.read_csv('tableConvert.com_wftamx (1).csv')
21
+ return df
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Calculate vegetation indices
24
+ def calculate_indices(image):
25
+ ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
26
+ evi2 = image.expression(
27
+ '2.5 * ((NIR - RED) / (NIR + 2.4 * RED + 1))',
28
+ {'NIR': image.select('B8'), 'RED': image.select('B4')}
29
+ ).rename('EVI2')
30
+ lai = image.expression(
31
+ '3.618 * EVI - 0.118',
32
+ {'EVI': image.select('EVI2')}
33
+ ).rename('LAI')
34
+ return image.addBands([ndvi, evi2, lai])
35
+
36
+ # Get Sentinel-2 imagery
37
+ def get_sentinel_imagery(geometry, start_date, end_date):
38
  return (ee.ImageCollection('COPERNICUS/S2_SR')
 
39
  .filterBounds(geometry)
40
+ .filterDate(start_date, end_date)
41
+ .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
42
+ .map(calculate_indices)
43
+ .median())
 
 
 
 
44
 
45
+ # Main app
46
+ def main():
47
+ st.title('Sugarcane Farm Analysis')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Load data
50
+ df = load_data()
 
51
 
52
+ # Sidebar
53
+ st.sidebar.title('Farm Selection')
54
+ selected_farm = st.sidebar.selectbox('Select a farm', df['name'])
 
55
 
56
+ # Main content
57
+ col1, col2 = st.columns([1, 2])
58
 
 
 
59
  with col1:
60
+ st.subheader('Farm Information')
61
+ farm_data = df[df['name'] == selected_farm].iloc[0]
62
+ st.write(f"Age: {farm_data['age']}")
63
+ st.write(f"Variety: {farm_data['variety']}")
64
+
65
  with col2:
66
+ st.subheader('Farm Location')
67
+ m = folium.Map(location=[farm_data['latitude'], farm_data['longitude']], zoom_start=12)
68
+ folium.Marker(
69
+ [farm_data['latitude'], farm_data['longitude']],
70
+ popup=farm_data['name']
71
+ ).add_to(m)
72
+ folium_static(m)
73
+
74
+ # Vegetation indices analysis
75
+ st.subheader('Vegetation Indices Analysis')
76
+
77
+ # Date range selection
78
+ today = datetime.now()
79
+ start_date = st.date_input('Start date', today - timedelta(days=30))
80
+ end_date = st.date_input('End date', today)
81
+
82
+ if start_date and end_date:
83
+ geometry = ee.Geometry.Point([farm_data['longitude'], farm_data['latitude']])
84
+ image = get_sentinel_imagery(geometry, start_date.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
85
+
86
+ # Display NDVI map
87
+ ndvi_map = geemap.Map(center=[farm_data['latitude'], farm_data['longitude']], zoom=14)
88
+ ndvi_map.add_layer(image.select('NDVI'), {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']}, 'NDVI')
89
+ ndvi_map.add_child(folium.LayerControl())
90
+ folium_static(ndvi_map)
91
+
92
+ # Plot time series of indices
93
+ indices = ['NDVI', 'EVI2', 'LAI']
94
+ fig, ax = plt.subplots(figsize=(10, 6))
95
+
96
+ for index in indices:
97
+ values = image.select(index).reduceRegion(
98
+ reducer=ee.Reducer.mean(),
99
+ geometry=geometry,
100
+ scale=10
101
+ ).getInfo()[index]
102
+ ax.plot([start_date, end_date], [values, values], label=index)
103
+
104
+ ax.set_xlabel('Date')
105
+ ax.set_ylabel('Index Value')
106
+ ax.legend()
107
+ st.pyplot(fig)
108
+
109
+ if __name__ == '__main__':
110
+ main()
111
+