File size: 4,913 Bytes
8bd7fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5b2220
d235c3a
 
8bd7fcc
 
bd637b6
8bd7fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import streamlit as st  
import datetime  
import pandas as pd  
import geemap  
import ee  # Ensure that Earth Engine is initialized  
from sklearn.preprocessing import StandardScaler  # Example import, adjust based on your model  

try:  
    service_account = '[email protected]'  
    credentials_path = 'ee-esmaeilkiani1387-1b2c5e812a1d.json'  
    ee.Initialize(ee.ServiceAccountCredentials(service_account, credentials_path))  
except Exception as e:  
    st.error(f"Error initializing Earth Engine: {e}")  
    st.stop() # Stop execution if authentication fails 
    #Load your farms data  
    Make sure to define `farms_data` DataFrame with columns ['farm_name', 'latitude', 'longitude', 'age', 'variety']  
    farms_data = pd.read_csv('Farm_Details_Export.csv')  

# تابع برای دریافت نقشه NDVI  
def get_ndvi_map(start_date, end_date):  
    s2 = ee.ImageCollection('COPERNICUS/S2').filterBounds(region).filterDate(start_date, end_date)  
    ndvi = s2.map(lambda image: image.normalizedDifference(['B8', 'B4']).rename('NDVI')).median()  
    ndvi_params = {'min': 0, 'max': 1, 'palette': ['red', 'yellow', 'green']}  
    return ndvi, ndvi_params  

# تابع برای دریافت نقشه NDMI (شاخص رطوبت)  
def get_ndmi_map(start_date, end_date):  
    s2 = ee.ImageCollection('COPERNICUS/S2').filterBounds(region).filterDate(start_date, end_date)  
    ndmi = s2.map(lambda image: image.normalizedDifference(['B8', 'B11']).rename('NDMI')).median()  
    ndmi_params = {'min': -1, 'max': 1, 'palette': ['brown', 'white', 'blue']}  
    return ndmi, ndmi_params  

# ساخت برنامه Streamlit  
st.title("نقشه NDVI و NDMI برای مزارع شرکت دهخدا")  

# انتخاب بازه زمانی  
start_date = st.date_input("تاریخ شروع", datetime.date(2023, 1, 1))  
end_date = st.date_input("تاریخ پایان", datetime.date(2023, 12, 31))  

# انتخاب شاخص  
index_option = st.selectbox("شاخص مورد نظر را انتخاب کنید:", ["NDVI", "NDMI"])  

# انتخاب مزرعه از فایل CSV  
farm_name = st.sidebar.selectbox("نام مزرعه را انتخاب کنید:", farms_data['farm_name'].unique())  

# پیدا کردن مختصات مزرعه انتخاب شده  
selected_farm = farms_data[farms_data['farm_name'] == farm_name]  
latitude = selected_farm['latitude'].values[0]  
longitude = selected_farm['longitude'].values[0]  
farm_age = selected_farm['age'].values[0]  
farm_variety = selected_farm['variety'].values[0]  

# دکمه برای نمایش نقشه  
if st.button("نمایش نقشه"):  
    # بسته به شاخص انتخاب شده، نقشه را بارگذاری کنید  
    if index_option == "NDVI":  
        index_map, vis_params = get_ndvi_map(start_date.isoformat(), end_date.isoformat())  
    else:  
        index_map, vis_params = get_ndmi_map(start_date.isoformat(), end_date.isoformat())  

    # ایجاد نقشه با Geemap  
    map_ = geemap.Map(center=[latitude, longitude], zoom=12)  
    map_.addLayer(index_map, vis_params, index_option)  

    # افزودن نوار رنگ به نقشه  
    map_.add_colorbar(vis_params, label=index_option)  

    # افزودن مزرعه به نقشه  
    map_.add_marker([latitude, longitude], popup=f"نام: {farm_name}\nسن: {farm_age}\nواریته: {farm_variety}")  

    # نمایش نقشه در Streamlit  
    map_.to_streamlit()  

    # امکان دانلود نقشه (توجه: كد ایجاد تصویر ممکن است نیاز به بررسی داشته باشد)  
    map_image = map_.to_image()  # Adjust if `to_image` doesn't exist or not functioning correctly  
    st.download_button(label="دانلود نقشه", data=map_image, file_name="map.png", mime="image/png")  

    # Preparation for the prediction model  
    # Ensure you have defined `model` and `ndre_value`, which are not included in the provided code  
    user_input = pd.DataFrame({  
        'Age': [farm_age],  
        'Variety': [farm_variety],  
        'NDRE': [None]  # Assign ndre_value once computed if applicable  
    })  
    
    if start_date:  
        day_of_year = start_date.timetuple().tm_yday  
        month = start_date.month  
        user_input['DayOfYear'] = [day_of_year]  
        user_input['Month'] = [month]  

    user_input = user_input[['Age', 'DayOfYear', 'Month', 'Variety', 'NDRE']]  

    # Ensure that your model is properly defined and imported as necessary  
    if 'model' in locals():  
        prediction = model.predict(user_input)  
        st.write("Predictions:")  
        st.write(f"Brix: {prediction[0][0]}")  
        st.write(f"Pol: {prediction[0][1]}")  
        st.write(f"Purity: {prediction[0][2]}")  
        st.write(f"RS: {prediction[0][3]}")  
    else:  
        st.warning("مدل پیش‌بینی تعریف نشده است.")