Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,208 +1,111 @@
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
3 |
-
import
|
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
|
11 |
-
import
|
12 |
-
import
|
13 |
|
14 |
# Initialize Earth Engine
|
15 |
-
|
16 |
-
|
17 |
-
|
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
|
76 |
-
|
77 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
return (ee.ImageCollection('COPERNICUS/S2_SR')
|
93 |
-
.filterDate(start_date, end_date)
|
94 |
.filterBounds(geometry)
|
95 |
-
.
|
96 |
-
.
|
97 |
-
|
98 |
-
|
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 |
-
|
105 |
-
|
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 |
-
|
146 |
-
|
147 |
-
return None
|
148 |
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
return
|
153 |
|
154 |
-
|
|
|
155 |
|
156 |
-
# Date selection
|
157 |
-
col1, col2 = st.columns(2)
|
158 |
with col1:
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
with col2:
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
|
|
|
|
|
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 |
+
|