File size: 5,330 Bytes
4b22250
d6c077d
0d6ff3d
d6c077d
 
 
 
 
ed67403
d6c077d
 
 
473d3b5
d109f8b
d6c077d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import streamlit as st
import pandas as pd
import plotly.express as px
import folium
from streamlit_folium import folium_static
import ee
import datetime
import os

# Set up Google Earth Engine
service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com'
credentials = ee.ServiceAccountCredentials(service_account, 'ee-esmaeilkiani13877-cfdea6eaf411.json')
ee.Initialize(credentials)

# Load farm data
@st.cache_data
def load_farm_data():
    return pd.read_csv('farm_coordinates.csv')

farms = load_farm_data()

# Streamlit app
st.title('Sugarcane Farm Dashboard')

# Sidebar
st.sidebar.title('Navigation')
page = st.sidebar.radio('Go to', ['Map', 'Comparative Charts', 'Weekly Reports'])

if page == 'Map':
    st.header('Sugarcane Farm Map')
    
    # Create map
    m = folium.Map(location=[farms['latitude'].mean(), farms['longitude'].mean()], zoom_start=10)
    
    # Add markers for each farm
    for idx, row in farms.iterrows():
        folium.Marker(
            location=[row['latitude'], row['longitude']],
            popup=f"Farm: {row['name']}, Age: {row['age']}, Variety: {row['variety']}",
            icon=folium.Icon(color='green', icon='leaf')
        ).add_to(m)
    
    # Display map
    folium_static(m)
    
    # Farm search
    search_farm = st.text_input('Search for a farm:')
    if search_farm:
        farm = farms[farms['name'].str.contains(search_farm, case=False)]
        if not farm.empty:
            st.write(f"Farm found: {farm['name'].values[0]}")
            st.map(farm)
        else:
            st.write("Farm not found.")

elif page == 'Comparative Charts':
    st.header('Comparative Charts')
    
    # Function to get NDVI data
    def get_ndvi_data(geometry, start_date, end_date):
        collection = ee.ImageCollection('COPERNICUS/S2_SR') \
            .filterBounds(geometry) \
            .filterDate(start_date, end_date) \
            .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
        
        def addNDVI(image):
            ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI')
            return image.addBands(ndvi)
        
        ndvi_collection = collection.map(addNDVI)
        ndvi_values = ndvi_collection.select('NDVI').mean().reduceRegion(
            reducer=ee.Reducer.mean(),
            geometry=geometry,
            scale=10
        ).get('NDVI')
        
        return ndvi_values.getInfo()
    
    # Function to get LAI data
    def get_lai_data(geometry, start_date, end_date):
        collection = ee.ImageCollection('MODIS/006/MOD15A2H') \
            .filterBounds(geometry) \
            .filterDate(start_date, end_date)
        
        lai_values = collection.select('Lai_500m').mean().reduceRegion(
            reducer=ee.Reducer.mean(),
            geometry=geometry,
            scale=500
        ).get('Lai_500m')
        
        return lai_values.getInfo()
    
    # Date range selection
    start_date = st.date_input('Start date', datetime.date(2023, 1, 1))
    end_date = st.date_input('End date', datetime.date.today())
    
    if start_date < end_date:
        # Get NDVI and LAI data for each farm
        ndvi_data = []
        lai_data = []
        for idx, row in farms.iterrows():
            geometry = ee.Geometry.Point([row['longitude'], row['latitude']])
            ndvi = get_ndvi_data(geometry, start_date.isoformat(), end_date.isoformat())
            lai = get_lai_data(geometry, start_date.isoformat(), end_date.isoformat())
            ndvi_data.append({'Farm': row['name'], 'NDVI': ndvi})
            lai_data.append({'Farm': row['name'], 'LAI': lai})
        
        ndvi_df = pd.DataFrame(ndvi_data)
        lai_df = pd.DataFrame(lai_data)
        
        # NDVI chart
        fig_ndvi = px.bar(ndvi_df, x='Farm', y='NDVI', title='NDVI Comparison')
        st.plotly_chart(fig_ndvi)
        
        # LAI chart
        fig_lai = px.bar(lai_df, x='Farm', y='LAI', title='LAI Comparison')
        st.plotly_chart(fig_lai)
    else:
        st.error('Error: End date must fall after start date.')

elif page == 'Weekly Reports':
    st.header('Weekly Reports')
    
    # Farm selection
    selected_farm = st.selectbox('Select a farm:', farms['name'])
    
    # Week selection
    week = st.slider('Select week:', 1, 52, 1)
    
    # Simulate weekly data (replace this with actual data processing)
    def get_weekly_data(farm, week):
        return {
            'NDVI': 0.5 + 0.1 * week,  # Simulated increasing NDVI
            'LAI': 2 + 0.2 * week,  # Simulated increasing LAI
        }
    
    data = get_weekly_data(selected_farm, week)
    
    # Display weekly report
    st.subheader(f'Weekly Report for {selected_farm} - Week {week}')
    
    col1, col2 = st.columns(2)
    with col1:
        st.metric(label="NDVI 🌱", value=f"{data['NDVI']:.2f}")
    with col2:
        st.metric(label="LAI 🌡", value=f"{data['LAI']:.2f}")
    
    # Trend chart
    weeks = list(range(1, week + 1))
    trend_data = [get_weekly_data(selected_farm, w) for w in weeks]
    trend_df = pd.DataFrame(trend_data)
    trend_df['Week'] = weeks
    
    fig = px.line(trend_df, x='Week', y=['NDVI', 'LAI'], title=f'Trend for {selected_farm}')
    st.plotly_chart(fig)

# Footer
st.sidebar.markdown('---')
st.sidebar.text('Dashboard created with Streamlit')