Esmaeilkiani commited on
Commit
1ec7272
·
verified ·
1 Parent(s): 6f96fc0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -40
app.py CHANGED
@@ -1,51 +1,76 @@
1
  import streamlit as st
2
- import ee
3
  import pandas as pd
4
- from datetime import date
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
  @st.cache_data
13
- def get_farm_coordinates(farm_name, dataset_url):
14
- # بارگذاری دیتاست
15
- df = pd.read_csv(dataset_url)
16
- # جستجوی مزرعه
17
- farm_data = df[df['Farm'] == farm_name]
18
- if farm_data.empty:
19
- return None
20
- return farm_data[['latitude', 'longitude']].values[0]
21
-
22
- # تابع برای محاسبه شاخص NDVI در بازه زمانی مشخص
23
- def get_ndvi_map(latitude, longitude, start_date, end_date):
24
- point = ee.Geometry.Point([longitude, latitude])
25
- collection = (ee.ImageCollection("COPERNICUS/S2")
26
- .filterBounds(point)
27
- .filterDate(start_date, end_date)
28
- .map(lambda img: img.normalizedDifference(['B8', 'B4']).rename('NDVI')))
29
- ndvi_image = collection.median()
30
- vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'white', 'green']}
31
- return geemap.ee_to_url(ndvi_image.clip(point.buffer(10000)), vis_params)
32
-
33
- # رابط کاربری با Streamlit
34
- st.title("نمایش نقشه شاخص NDVI مزارع نیشکر")
35
- farm_name = st.text_input("نام مزرعه را وارد کنید:")
36
- dataset_url = "https://huggingface.co/datasets/Esmaeilkianii/SugarcaneDataSet/embed/viewer/default/train"
37
 
 
 
38
  if farm_name:
39
- coords = get_farm_coordinates(farm_name, dataset_url)
40
- if coords is not None:
41
- st.success(f"مزرعه یافت شد! مختصات: {coords}")
42
- start_date = st.date_input("تاریخ شروع:", date(2023, 1, 1))
43
- end_date = st.date_input("تاریخ پایان:", date.today())
44
-
45
- if start_date < end_date:
46
- map_url = get_ndvi_map(coords[0], coords[1], start_date.isoformat(), end_date.isoformat())
47
- st.image(map_url, caption=f"نقشه NDVI برای مزرعه {farm_name}")
48
- else:
49
- st.error("تاریخ شروع باید قبل از تاریخ پایان باشد.")
50
  else:
51
- st.error("مزرعه‌ای با این نام یافت نشد.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
 
2
  import pandas as pd
3
+ import ee
4
  import geemap
5
 
6
+ # Earth Engine authentication
7
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
8
  credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani1387-1b2c5e812a1d.json')
9
+ ee.Initialize(credentials)
10
 
11
+ # Load the CSV file
12
  @st.cache_data
13
+ def load_data():
14
+ return pd.read_csv('/home/user/Farm_Details_Export.csv')
15
+
16
+ df = load_data()
17
+
18
+ st.title('Farm Finder and Sentinel-2 Imagery Viewer')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Farm search functionality
21
+ farm_name = st.text_input('Enter farm name:')
22
  if farm_name:
23
+ farm = df[df['farm_name'].str.contains(farm_name, case=False)]
24
+ if not farm.empty:
25
+ st.write(farm)
 
 
 
 
 
 
 
 
26
  else:
27
+ st.write('Farm not found')
28
+
29
+ # Sentinel-2 index selection
30
+ indices = {'NDVI': 'NDVI', 'EVI': 'EVI', 'NDWI': '(B3 - B8) / (B3 + B8)'}
31
+ selected_index = st.selectbox('Select Sentinel-2 index:', list(indices.keys()))
32
+
33
+ # Date range selection
34
+ start_date = st.date_input('Start date')
35
+ end_date = st.date_input('End date')
36
+
37
+ if st.button('Show Map'):
38
+ # Create a map centered on the mean coordinates of all farms
39
+ center_lat = df['latitude'].mean()
40
+ center_lon = df['longitude'].mean()
41
+ m = geemap.Map(center=[center_lat, center_lon], zoom=10)
42
+
43
+ # Add Sentinel-2 imagery with selected index
44
+ s2_collection = (ee.ImageCollection('COPERNICUS/S2_SR')
45
+ .filterDate(start_date, end_date)
46
+ .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)))
47
+
48
+ if selected_index == 'NDVI':
49
+ vis_params = {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']}
50
+ elif selected_index == 'EVI':
51
+ vis_params = {'min': -1, 'max': 1, 'palette': ['blue', 'white', 'green']}
52
+ else: # NDWI
53
+ vis_params = {'min': -1, 'max': 1, 'palette': ['red', 'white', 'blue']}
54
+
55
+ def add_index(image):
56
+ index = image.expression(indices[selected_index], {
57
+ 'B3': image.select('B3'),
58
+ 'B4': image.select('B4'),
59
+ 'B8': image.select('B8'),
60
+ }).rename(selected_index)
61
+ return image.addBands(index)
62
+
63
+ s2_with_index = s2_collection.map(add_index)
64
+ median_index = s2_with_index.select(selected_index).median()
65
+ m.addLayer(median_index, vis_params, selected_index)
66
+
67
+ # Add farm locations to the map
68
+ for idx, row in df.iterrows():
69
+ info = f"Farm: {row['farm_name']}<br>Age: {row['age']}<br>Variety: {row['variety']}"
70
+ m.add_marker(location=[row['latitude'], row['longitude']], popup=info)
71
+
72
+ # Display the map
73
+ m.to_streamlit(height=600)
74
+
75
+ if __name__ == '__main__':
76
+ st.write('App is running')