-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
325 lines (280 loc) · 10.6 KB
/
app.py
File metadata and controls
325 lines (280 loc) · 10.6 KB
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
160
161
162
163
164
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime
# Configuração da página
st.set_page_config(
page_title="Dashboard de Irrigação",
page_icon="💧",
layout="wide",
initial_sidebar_state="expanded"
)
# Título principal
st.title("🌱 Dashboard de Monitoramento de Irrigação")
st.markdown("---")
# Carregar dados
@st.cache_data
def load_data():
df = pd.read_csv('data/irrigation_dataset.csv')
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
try:
df = load_data()
# Sidebar com filtros
st.sidebar.header("⚙️ Filtros")
# Filtro de data
min_date = df['timestamp'].min().date()
max_date = df['timestamp'].max().date()
date_range = st.sidebar.date_input(
"Período",
value=(min_date, max_date),
min_value=min_date,
max_value=max_date
)
# Filtrar dados por data
if len(date_range) == 2:
mask = (df['timestamp'].dt.date >= date_range[0]) & (df['timestamp'].dt.date <= date_range[1])
df_filtered = df[mask]
else:
df_filtered = df
# Métricas principais
st.header("📊 Métricas Principais")
col1, col2, col3, col4 = st.columns(4)
with col1:
avg_humidity = df_filtered['soil_pct'].mean()
st.metric(
label="Umidade Média do Solo",
value=f"{avg_humidity:.1f}%",
delta=f"{avg_humidity - df['soil_pct'].mean():.1f}%"
)
with col2:
avg_ph = df_filtered['ph'].mean()
st.metric(
label="pH Médio",
value=f"{avg_ph:.2f}",
delta=f"{avg_ph - df['ph'].mean():.2f}"
)
with col3:
avg_p = df_filtered['npk_p'].mean()
st.metric(
label="Fósforo Médio (P)",
value=f"{avg_p:.0f}",
delta=f"{avg_p - df['npk_p'].mean():.0f}"
)
with col4:
avg_k = df_filtered['npk_k'].mean()
st.metric(
label="Potássio Médio (K)",
value=f"{avg_k:.0f}",
delta=f"{avg_k - df['npk_k'].mean():.0f}"
)
st.markdown("---")
# Gráficos principais
st.header("📈 Visualizações")
# Linha 1: Umidade e pH
col1, col2 = st.columns(2)
with col1:
st.subheader("💧 Níveis de Umidade do Solo")
fig_humidity = px.line(
df_filtered,
x='timestamp',
y='soil_pct',
title='Evolução da Umidade do Solo (%)',
labels={'soil_pct': 'Umidade (%)', 'timestamp': 'Data/Hora'}
)
fig_humidity.add_hline(
y=50,
line_dash="dash",
line_color="red",
annotation_text="Limite Mínimo (50%)"
)
fig_humidity.update_layout(height=400)
st.plotly_chart(fig_humidity, use_container_width=True)
with col2:
st.subheader("🧪 Níveis de pH")
fig_ph = px.line(
df_filtered,
x='timestamp',
y='ph',
title='Evolução do pH do Solo',
labels={'ph': 'pH', 'timestamp': 'Data/Hora'},
color_discrete_sequence=['#2ecc71']
)
fig_ph.add_hrect(
y0=6.0, y1=7.0,
fillcolor="green",
opacity=0.1,
annotation_text="Faixa Ideal",
annotation_position="top left"
)
fig_ph.update_layout(height=400)
st.plotly_chart(fig_ph, use_container_width=True)
# Linha 2: NPK
st.subheader("🌿 Nutrientes do Solo (NPK)")
col1, col2, col3 = st.columns(3)
with col1:
fig_n = px.line(
df_filtered,
x='timestamp',
y='npk_n',
title='Nitrogênio (N)',
labels={'npk_n': 'N (ppm)', 'timestamp': 'Data/Hora'},
color_discrete_sequence=['#3498db']
)
fig_n.update_layout(height=300)
st.plotly_chart(fig_n, use_container_width=True)
with col2:
fig_p = px.line(
df_filtered,
x='timestamp',
y='npk_p',
title='Fósforo (P)',
labels={'npk_p': 'P (ppm)', 'timestamp': 'Data/Hora'},
color_discrete_sequence=['#e74c3c']
)
fig_p.update_layout(height=300)
st.plotly_chart(fig_p, use_container_width=True)
with col3:
fig_k = px.line(
df_filtered,
x='timestamp',
y='npk_k',
title='Potássio (K)',
labels={'npk_k': 'K (ppm)', 'timestamp': 'Data/Hora'},
color_discrete_sequence=['#f39c12']
)
fig_k.update_layout(height=300)
st.plotly_chart(fig_k, use_container_width=True)
st.markdown("---")
# Status de Irrigação
st.header("💦 Status de Irrigação")
# Análise das condições atuais
latest = df_filtered.iloc[-1]
col1, col2 = st.columns([2, 1])
with col1:
st.subheader("Condições Atuais")
# Criar gráfico de gauge para umidade
fig_gauge = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=latest['soil_pct'],
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "Umidade do Solo (%)"},
delta={'reference': 60},
gauge={
'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 40], 'color': "red"},
{'range': [40, 60], 'color': "yellow"},
{'range': [60, 100], 'color': "lightgreen"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 50
}
}
))
fig_gauge.update_layout(height=300)
st.plotly_chart(fig_gauge, use_container_width=True)
with col2:
st.subheader("Parâmetros Atuais")
st.metric("Umidade", f"{latest['soil_pct']:.1f}%")
st.metric("pH", f"{latest['ph']:.2f}")
st.metric("Nitrogênio (N)", f"{latest['npk_n']:.0f} ppm")
st.metric("Fósforo (P)", f"{latest['npk_p']:.0f} ppm")
st.metric("Potássio (K)", f"{latest['npk_k']:.0f} ppm")
st.markdown("---")
# Sugestões de Irrigação
st.header("🌤️ Sugestões de Irrigação Baseadas em Clima e Condições")
# Análise inteligente
suggestions = []
priority = "info"
# Análise de umidade
if latest['soil_pct'] < 40:
suggestions.append("⚠️ **URGENTE**: Umidade do solo muito baixa. Irrigação necessária imediatamente!")
priority = "error"
elif latest['soil_pct'] < 55:
suggestions.append("⚡ **ATENÇÃO**: Umidade do solo abaixo do ideal. Recomenda-se irrigação em breve.")
priority = "warning"
else:
suggestions.append("✅ Níveis de umidade adequados. Nenhuma irrigação necessária no momento.")
# Análise de pH
if latest['ph'] < 6.0:
suggestions.append("🧪 pH abaixo do ideal (< 6.0). Considere aplicar calcário para correção.")
priority = "warning" if priority == "info" else priority
elif latest['ph'] > 7.5:
suggestions.append("🧪 pH acima do ideal (> 7.5). Considere aplicar enxofre para correção.")
priority = "warning" if priority == "info" else priority
else:
suggestions.append("✅ pH dentro da faixa ideal (6.0-7.5).")
# Análise de nutrientes
if latest['npk_n'] < 200:
suggestions.append("🌿 Níveis de Nitrogênio (N) baixos. Recomenda-se adubação nitrogenada.")
if latest['npk_p'] < 150:
suggestions.append("🌿 Níveis de Fósforo (P) baixos. Recomenda-se adubação fosfatada.")
if latest['npk_k'] < 200:
suggestions.append("🌿 Níveis de Potássio (K) baixos. Recomenda-se adubação potássica.")
# Análise de luz (LDR)
if latest['ldr_mv'] < 500:
suggestions.append("☁️ Baixa luminosidade detectada (período noturno ou nublado). Considere reduzir irrigação.")
else:
suggestions.append("☀️ Boa luminosidade detectada. Condições favoráveis para irrigação se necessário.")
# Exibir sugestões
for suggestion in suggestions:
if "URGENTE" in suggestion or "muito baixa" in suggestion:
st.error(suggestion)
elif "ATENÇÃO" in suggestion or "abaixo do ideal" in suggestion or "acima do ideal" in suggestion:
st.warning(suggestion)
elif "baixos" in suggestion:
st.info(suggestion)
else:
st.success(suggestion)
# Recomendação de irrigação
st.subheader("💡 Recomendação de Ação")
if latest['soil_pct'] < 40:
st.error("🚨 **IRRIGAR AGORA** - Umidade crítica")
recommended_time = "Imediatamente"
elif latest['soil_pct'] < 55:
st.warning("⏰ **IRRIGAR EM BREVE** - Umidade baixa")
recommended_time = "Nas próximas 2-4 horas"
else:
st.success("✅ **AGUARDAR** - Umidade adequada")
recommended_time = "Não necessário no momento"
col1, col2 = st.columns(2)
with col1:
st.info(f"**Próxima irrigação recomendada:** {recommended_time}")
with col2:
if latest['ldr_mv'] < 500:
st.info("**Melhor horário:** Aguardar melhor luminosidade")
else:
st.info("**Melhor horário:** Agora ou início da manhã/final da tarde")
st.markdown("---")
# Dados brutos
with st.expander("📋 Ver Dados Brutos"):
st.dataframe(df_filtered, use_container_width=True)
# Opção de download
csv = df_filtered.to_csv(index=False).encode('utf-8')
st.download_button(
label="📥 Download CSV",
data=csv,
file_name=f"irrigation_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv",
)
# Rodapé
st.markdown("---")
st.markdown(
"""
<div style='text-align: center; color: gray;'>
<p>Dashboard de Irrigação Inteligente | FIAP - Fase 3</p>
<p>Última atualização: {}</p>
</div>
""".format(datetime.now().strftime('%d/%m/%Y %H:%M:%S')),
unsafe_allow_html=True
)
except FileNotFoundError:
st.error("❌ Arquivo 'data/irrigation_dataset.csv' não encontrado!")
st.info("Por favor, verifique se o arquivo de dados está no diretório correto.")
except Exception as e:
st.error(f"❌ Erro ao carregar os dados: {str(e)}")