Files changed (1) hide show
  1. app.py +78 -75
app.py CHANGED
@@ -1,82 +1,85 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import joblib
4
- import ee
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
- # Load model and farm data
13
- model = joblib.load('updated_model.pkl')
14
- farm_data = pd.read_csv('Farm_NDRE_TimeSeries.csv')
15
- farm_names = farm_data['Farm'].tolist()
16
-
17
- # Function to calculate NDRE
18
- def calculate_ndre(coordinates, start_date, end_date):
19
- try:
20
- # Convert start_date and end_date to strings
21
- start_date_str = start_date.strftime('%Y-%m-%d')
22
- end_date_str = end_date.strftime('%Y-%m-%d')
23
-
24
- roi = ee.Geometry.Point(coordinates)
25
- imageCollection = ee.ImageCollection('COPERNICUS/S2_SR') \
26
- .filterBounds(roi) \
27
- .filterDate(start_date_str, end_date_str) \
28
- .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
29
-
30
- def ndre(image):
31
- red_edge = image.select('B8A')
32
- red = image.select('B4')
33
- return image.addBands(red_edge.subtract(red).divide(red_edge.add(red)).rename('NDRE'))
34
-
35
- ndre_image = imageCollection.map(ndre).median().select('NDRE')
36
-
37
- ndre_value = ndre_image.reduceRegion(
38
- reducer=ee.Reducer.first(),
39
- geometry=roi,
40
- scale=10
41
- ).getInfo()
42
-
43
- return ndre_value.get('NDRE') if ndre_value else None
44
-
45
- except Exception as e:
46
- st.error(f"Error calculating NDRE: {e}")
47
- return None
48
-
49
- # Streamlit User Interface
50
- st.title("Farm Parameter Prediction App")
51
- selected_farm = st.selectbox("Select Farm", farm_names)
52
- farm_age = st.number_input("Farm Age (years)", min_value=0)
53
- farm_variety = st.text_input("Farm Variety")
54
- start_date = st.date_input("Start Date")
55
- end_date = st.date_input("End Date")
56
-
57
- # Handling Farm Data Selection and NDRE Calculation
58
- selected_farm_data = farm_data[farm_data['Farm'] == selected_farm]
59
- coordinates = (selected_farm_data['longitude'].iloc[0], selected_farm_data['latitude'].iloc[0])
60
-
61
- if st.button('نمایش نقشه NDRE'):
62
- NDRE = calculate_ndre(coordinates, start_date, end_date)
63
- if NDRE is not None:
64
- st.session_state.ndre_value = NDRE # Store NDRE in session state
65
- st.write(f'شاخص NDRE: {NDRE}')
66
-
67
- Map = geemap.Map()
68
- Map.centerObject(ee.Geometry.Point(coordinates), 12)
69
-
70
- vis_params = {'min': 0, 'max': 1, 'palette': ['blue', 'green', 'yellow', 'red']}
71
- Map.addLayer(ee.Image(NDRE), vis_params, 'NDRE')
72
- Map.to_streamlit(height=500)
73
  else:
74
- st.error("Unable to calculate NDRE.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- # Making Predictions Using the Loaded Model
77
- if st.button("Predict"):
78
- ndre_value = st.session_state.get('ndre_value', 0)
79
-
80
  user_input = pd.DataFrame({
81
  'Age': [farm_age],
82
  'Variety': [farm_variety],
 
1
+ import streamlit as st
2
+ import ee
3
+ import geemap.foliumap as geemap
4
+ import pandas as pd
5
+ import datetime
6
 
7
+ # اعتبار سنجی و اتصال به Google Earth Engine
8
  service_account = 'earth-engine-service-account@ee-esmaeilkiani1387.iam.gserviceaccount.com'
9
+ credentials = ee.ServiceAccountCredentials(service_account, 'path-to-your-private-key.json')
10
+ ee.Initialize(credentials)
11
+
12
+ # خواندن فایل CSV مزارع
13
+ farms_data = pd.read_csv('path-to-your-farms-data.csv')
14
+
15
+ # تعریف ناحیه مورد مطالعه با مختصات جدید
16
+ region = ee.Geometry.Polygon(
17
+ [[[48.681879, 31.417603], [48.721447, 31.413209], [48.724279, 31.420826], [48.726768, 31.427418],
18
+ [48.728228, 31.435694], [48.736382, 31.42837], [48.739557, 31.435657], [48.742261, 31.441772],
19
+ [48.752303, 31.452243], [48.75226, 31.459784], [48.759127, 31.473657], [48.766809, 31.472413],
20
+ [48.773203, 31.491188], [48.77758, 31.534579], [48.785563, 31.540797], [48.792601, 31.59696],
21
+ [48.694668, 31.60756], [48.691921, 31.603466], [48.697586, 31.534067], [48.69381, 31.507727],
22
+ [48.685226, 31.468496], [48.681879, 31.417603]]]
23
+ )
24
+
25
+ # تابع برای دریافت نقشه NDVI
26
+ def get_ndvi_map(start_date, end_date):
27
+ s2 = ee.ImageCollection('COPERNICUS/S2').filterBounds(region).filterDate(start_date, end_date)
28
+ ndvi = s2.map(lambda image: image.normalizedDifference(['B8', 'B4']).rename('NDVI')).median()
29
+ ndvi_params = {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']}
30
+ return ndvi, ndvi_params
31
+
32
+ # تابع برای دریافت نقشه NDMI (شاخص رطوبت)
33
+ def get_ndmi_map(start_date, end_date):
34
+ s2 = ee.ImageCollection('COPERNICUS/S2').filterBounds(region).filterDate(start_date, end_date)
35
+ ndmi = s2.map(lambda image: image.normalizedDifference(['B8', 'B11']).rename('NDMI')).median()
36
+ ndmi_params = {'min': -1, 'max': 1, 'palette': ['brown', 'white', 'blue']}
37
+ return ndmi, ndmi_params
38
+
39
+ # ساخت برنامه Streamlit
40
+ st.title("نقشه NDVI و NDMI برای مزارع شرکت دهخدا")
41
+
42
+ # انتخاب بازه زمانی
43
+ start_date = st.date_input("تاریخ شروع", datetime.date(2023, 1, 1))
44
+ end_date = st.date_input("تاریخ پایان", datetime.date(2023, 12, 31))
45
+
46
+ # انتخاب شاخص
47
+ index_option = st.selectbox("شاخص مورد نظر را انتخاب کنید:", ["NDVI", "NDMI"])
48
+
49
+ # انتخاب مزرعه از فایل CSV
50
+ farm_name = st.sidebar.selectbox("نام مزرعه را انتخاب کنید:", farms_data['farm_name'].unique())
51
+
52
+ # پیدا کردن مختصات مزرعه انتخاب شده
53
+ selected_farm = farms_data[farms_data['farm_name'] == farm_name]
54
+ latitude = selected_farm['latitude'].values[0]
55
+ longitude = selected_farm['longitude'].values[0]
56
+ farm_age = selected_farm['age'].values[0]
57
+ farm_variety = selected_farm['variety'].values[0]
58
+
59
+ # دکمه برای نمایش نقشه
60
+ if st.button("نمایش نقشه"):
61
+ # بسته به شاخص انتخاب شده، نقشه را بارگذاری کنید
62
+ if index_option == "NDVI":
63
+ index_map, vis_params = get_ndvi_map(start_date.isoformat(), end_date.isoformat())
 
 
 
 
 
 
 
 
 
64
  else:
65
+ index_map, vis_params = get_ndmi_map(start_date.isoformat(), end_date.isoformat())
66
+
67
+ # ایجاد نقشه با Geemap
68
+ map_ = geemap.Map(center=[latitude, longitude], zoom=12)
69
+ map_.addLayer(index_map, vis_params, index_option)
70
+
71
+ # افزودن نوار رنگ به نقشه
72
+ map_.add_colorbar(vis_params, label=index_option)
73
+
74
+ # افزودن مزرعه به نقشه
75
+ map_.add_marker([latitude, longitude], popup=f"نام: {farm_name}\nسن: {farm_age}\nواریته: {farm_variety}")
76
+
77
+ # نمایش نقشه در Streamlit
78
+ map_.to_streamlit()
79
+
80
+ # امکان دانلود نقشه
81
+ st.download_button(label="دانلود نقشه", data=map_.to_image(), file_name="map.png", mime="image/png")
82
 
 
 
 
 
83
  user_input = pd.DataFrame({
84
  'Age': [farm_age],
85
  'Variety': [farm_variety],