Spaces:
Running
Running
import streamlit as st | |
import pandas as pd | |
import numpy as np | |
import folium | |
from streamlit_folium import folium_static | |
import ee | |
import os | |
import json | |
import time | |
from datetime import datetime, timedelta | |
import plotly.express as px | |
import plotly.graph_objects as go | |
from PIL import Image | |
import base64 | |
from io import BytesIO | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
import altair as alt | |
from streamlit_option_menu import option_menu | |
from streamlit_lottie import st_lottie | |
import requests | |
import hydralit_components as hc | |
from streamlit_extras.colored_header import colored_header | |
from streamlit_extras.metric_cards import style_metric_cards | |
from streamlit_extras.chart_container import chart_container | |
from streamlit_extras.add_vertical_space import add_vertical_space | |
from streamlit_card import card | |
import pydeck as pdk | |
import math | |
from sklearn.linear_model import LinearRegression | |
# Page configuration with custom theme | |
st.set_page_config( | |
page_title="سامانه هوشمند پایش مزارع نیشکر دهخدا", | |
page_icon="🌿", | |
layout="wide", | |
initial_sidebar_state="expanded" | |
) | |
# Custom CSS with modern green design and animations | |
st.markdown(""" | |
<style> | |
@import url('https://fonts.googleapis.com/css2?family=Vazirmatn:wght@100;200;300;400;500;600;700;800;900&display=swap'); | |
* { | |
font-family: 'Vazirmatn', sans-serif !important; | |
} | |
/* Main container styling */ | |
.main { | |
background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f2 100%); | |
} | |
/* Header styling */ | |
.main-header { | |
background: linear-gradient(90deg, #1a8754 0%, #115740 100%); | |
padding: 1.5rem; | |
border-radius: 12px; | |
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); | |
margin-bottom: 2rem; | |
position: relative; | |
overflow: hidden; | |
animation: header-glow 3s infinite alternate; | |
} | |
@keyframes header-glow { | |
0% { | |
box-shadow: 0 8px 32px rgba(26, 135, 84, 0.1); | |
} | |
100% { | |
box-shadow: 0 8px 32px rgba(26, 135, 84, 0.3); | |
} | |
} | |
.main-header::before { | |
content: ''; | |
position: absolute; | |
top: -50%; | |
left: -50%; | |
width: 200%; | |
height: 200%; | |
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%); | |
transform: rotate(30deg); | |
z-index: 0; | |
} | |
.main-header h1 { | |
color: white; | |
font-weight: 700; | |
margin: 0; | |
position: relative; | |
z-index: 1; | |
} | |
.main-header p { | |
color: rgba(255, 255, 255, 0.8); | |
margin: 0; | |
position: relative; | |
z-index: 1; | |
} | |
/* Navigation menu styling */ | |
.st-emotion-cache-1lcbz7b { | |
background-color: transparent !important; | |
padding: 0 !important; | |
margin-bottom: 20px !important; | |
} | |
.st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d { | |
--hover-color: #e9f7ef !important; | |
border-radius: 10px !important; | |
font-size: 16px !important; | |
text-align: center !important; | |
margin: 0 !important; | |
} | |
.st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d:hover { | |
background-color: #e9f7ef !important; | |
} | |
.st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d[data-selected="true"] { | |
background-color: #1a8754 !important; | |
color: white !important; | |
font-weight: 600 !important; | |
} | |
.st-emotion-cache-1lcbz7b .st-emotion-cache-1j7d69d .st-emotion-cache-1m5q2i0 { | |
color: #1a8754 !important; | |
font-size: 18px !important; | |
} | |
/* Metric card styling */ | |
.metric-card { | |
background: white; | |
border-radius: 12px; | |
padding: 1.5rem; | |
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05); | |
transition: all 0.3s ease; | |
text-align: center; | |
} | |
.metric-card:hover { | |
transform: translateY(-5px); | |
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1); | |
} | |
.metric-card .metric-value { | |
font-size: 2.5rem; | |
font-weight: 700; | |
color: #1a8754; | |
margin-bottom: 0.5rem; | |
} | |
.metric-card .metric-label { | |
font-size: 1rem; | |
color: #6c757d; | |
} | |
/* Map container styling */ | |
.map-container { | |
border-radius: 12px; | |
overflow: hidden; | |
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05); | |
} | |
/* Tabs styling */ | |
.stTabs [data-baseweb="tab-list"] { | |
gap: 8px; | |
} | |
.stTabs [data-baseweb="tab"] { | |
border-radius: 4px 4px 0px 0px; | |
padding: 10px 16px; | |
background-color: #f8f9fa; | |
} | |
.stTabs [aria-selected="true"] { | |
background-color: #1a8754 !important; | |
color: white !important; | |
} | |
/* Sidebar styling */ | |
[data-testid="stSidebar"] { | |
background-color: #ffffff; | |
border-right: 1px solid #e9ecef; | |
} | |
/* Animations */ | |
@keyframes fadeIn { | |
0% { opacity: 0; transform: translateY(20px); } | |
100% { opacity: 1; transform: translateY(0); } | |
} | |
.animate-fadeIn { | |
animation: fadeIn 0.5s ease forwards; | |
} | |
/* Loading animation */ | |
.loading-spinner { | |
display: flex; | |
justify-content: center; | |
align-items: center; | |
height: 100px; | |
} | |
.loading-spinner::after { | |
content: ""; | |
width: 40px; | |
height: 40px; | |
border: 4px solid #f3f3f3; | |
border-top: 4px solid #1a8754; | |
border-radius: 50%; | |
animation: spin 1s linear infinite; | |
} | |
@keyframes spin { | |
0% { transform: rotate(0deg); } | |
100% { transform: rotate(360deg); } | |
} | |
/* RTL Support */ | |
.rtl { | |
direction: rtl; | |
text-align: right; | |
} | |
/* Custom scrollbar */ | |
::-webkit-scrollbar { | |
width: 8px; | |
height: 8px; | |
} | |
::-webkit-scrollbar-track { | |
background: #f1f1f1; | |
border-radius: 10px; | |
} | |
::-webkit-scrollbar-thumb { | |
background: #1a8754; | |
border-radius: 10px; | |
} | |
::-webkit-scrollbar-thumb:hover { | |
background: #115740; | |
} | |
/* Tooltip styling */ | |
.tooltip { | |
position: relative; | |
display: inline-block; | |
} | |
.tooltip .tooltiptext { | |
visibility: hidden; | |
width: 120px; | |
background-color: #555; | |
color: #fff; | |
text-align: center; | |
border-radius: 6px; | |
padding: 5px; | |
position: absolute; | |
z-index: 1; | |
bottom: 125%; | |
left: 50%; | |
margin-left: -60px; | |
opacity: 0; | |
transition: opacity 0.3s; | |
} | |
.tooltip:hover .tooltiptext { | |
visibility: visible; | |
opacity: 1; | |
} | |
/* Data table styling */ | |
.dataframe { | |
border-collapse: collapse; | |
width: 100%; | |
border-radius: 8px; | |
overflow: hidden; | |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); | |
} | |
.dataframe th { | |
background-color: #1a8754; | |
color: white; | |
padding: 12px; | |
text-align: right; | |
} | |
.dataframe td { | |
padding: 10px 12px; | |
border-bottom: 1px solid #e9ecef; | |
} | |
.dataframe tr:nth-child(even) { | |
background-color: #f8f9fa; | |
} | |
.dataframe tr:hover { | |
background-color: #e9ecef; | |
} | |
/* Progress bar styling */ | |
.stProgress > div > div > div > div { | |
background-color: #1a8754; | |
} | |
/* Notification styling */ | |
.notification { | |
background-color: #d1e7dd; | |
color: #0f5132; | |
padding: 1rem; | |
border-radius: 8px; | |
margin-bottom: 1rem; | |
display: flex; | |
align-items: center; | |
animation: slideIn 0.5s ease; | |
} | |
@keyframes slideIn { | |
0% { transform: translateX(100%); opacity: 0; } | |
100% { transform: translateX(0); opacity: 1; } | |
} | |
.notification-icon { | |
margin-right: 0.5rem; | |
font-size: 1.2rem; | |
} | |
/* Custom select box */ | |
.custom-select { | |
background-color: white; | |
border-radius: 8px; | |
padding: 0.5rem; | |
border: 1px solid #ced4da; | |
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05); | |
} | |
/* Glassmorphism effect */ | |
.glass-card { | |
background: rgba(255, 255, 255, 0.7); | |
backdrop-filter: blur(10px); | |
-webkit-backdrop-filter: blur(10px); | |
border-radius: 12px; | |
border: 1px solid rgba(255, 255, 255, 0.3); | |
padding: 1.5rem; | |
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1); | |
} | |
/* Neumorphism effect */ | |
.neumorphic-card { | |
background: #f0f0f3; | |
border-radius: 12px; | |
box-shadow: 10px 10px 20px #d1d1d4, -10px -10px 20px #ffffff; | |
padding: 1.5rem; | |
} | |
/* Gradient text */ | |
.gradient-text { | |
background: linear-gradient(90deg, #1a8754 0%, #115740 100%); | |
-webkit-background-clip: text; | |
-webkit-text-fill-color: transparent; | |
font-weight: 700; | |
} | |
/* Pulsing animation */ | |
@keyframes pulse { | |
0% { transform: scale(1); } | |
50% { transform: scale(1.05); } | |
100% { transform: scale(1); } | |
} | |
.pulse-animation { | |
animation: pulse 2s infinite; | |
} | |
/* Custom radio buttons */ | |
.stRadio > div { | |
display: flex; | |
gap: 10px; | |
} | |
.stRadio label { | |
cursor: pointer; | |
background-color: #f8f9fa; | |
padding: 0.5rem 1rem; | |
border-radius: 50px; | |
transition: all 0.3s ease; | |
} | |
.stRadio label:hover { | |
background-color: #e9ecef; | |
} | |
/* Hide default radio button */ | |
.stRadio input { | |
display: none; | |
} | |
/* Custom checked state */ | |
.stRadio input:checked + label { | |
background-color: #1a8754; | |
color: white; | |
} | |
.stSelectbox, .stNumberInput { | |
background-color: #f0f2f6; | |
border-radius: 10px; | |
padding: 10px; | |
margin: 10px 0; | |
} | |
.custom-card { | |
background-color: white; | |
padding: 20px; | |
border-radius: 15px; | |
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); | |
margin: 10px 0; | |
} | |
.metric-container { | |
display: flex; | |
justify-content: space-between; | |
flex-wrap: wrap; | |
} | |
.metric-card { | |
background-color: #1a8754; | |
color: white; | |
padding: 15px; | |
border-radius: 10px; | |
margin: 5px; | |
flex: 1; | |
min-width: 200px; | |
text-align: center; | |
} | |
/* Button styling */ | |
.stButton>button { | |
border-radius: 50px; | |
padding: 0.5rem 1.5rem; | |
font-weight: 600; | |
transition: all 0.3s ease; | |
border: none; | |
} | |
.stButton>button:hover { | |
transform: translateY(-2px); | |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); | |
} | |
.primary-btn { | |
background: linear-gradient(90deg, #1a8754 0%, #115740 100%); | |
color: white; | |
} | |
.secondary-btn { | |
background: white; | |
color: #1a8754; | |
border: 1px solid #1a8754 !important; | |
} | |
/* Footer styling */ | |
footer { | |
position: fixed; | |
left: 0; | |
bottom: 0; | |
width: 100%; | |
background-color: #1a8754; | |
color: white; | |
text-align: center; | |
padding: 10px 0; | |
font-family: 'Vazirmatn', sans-serif; | |
} | |
</style> | |
""", unsafe_allow_html=True) | |
# Load real farm data from CSV | |
def load_farm_data(): | |
try: | |
df = pd.read_csv("کراپ لاگ کلی (1).csv") | |
# Rename columns for consistency with the program | |
df.rename(columns={ | |
'سال': 'Year', | |
'هفته': 'Week', | |
'مزرعه': 'Farm_ID', | |
'کانال': 'Channel', | |
'اداره': 'Administration', | |
'مساحت': 'Area', | |
'مساحت زیر مجموعه': 'SubArea', | |
'رقم': 'Variety', | |
'سن': 'Age', | |
'ایستگاه 1': 'Station1', | |
'ایستگاه 2': 'Station2', | |
'ایستگاه 3': 'Station3', | |
'ایستگاه 4': 'Station4', | |
'ایستگاه 5': 'Station5', | |
'ارتفاع هفته جاری مزرعه': 'CurrentHeight', | |
'ارتفاع هفته گذشته مزرعه': 'PreviousHeight', | |
'رشد هفته جاری': 'CurrentGrowth', | |
'رشد هفته گذشته': 'PreviousGrowth', | |
'نیتروژن فعلی': 'CurrentNitrogen', | |
'نیتروژن استاندارد فعلی': 'StandardNitrogen', | |
'نیتروژن قبلی': 'PreviousNitrogen', | |
'نیتروژن استاندارد قبلی': 'PreviousStandardNitrogen', | |
'رطوبت غلاف فعلی': 'CurrentMoisture', | |
'رطوبت استاندارد فعلی': 'StandardMoisture', | |
'رطوبت غلاف قبلی': 'PreviousMoisture', | |
'رطوبت استاندارد قبلی': 'PreviousStandardMoisture', | |
'چاهک 1': 'Well1', | |
'تاریخ قرائت': 'Well1Date', | |
'چاهک 2': 'Well2', | |
'تاریخ قرائت.1': 'Well2Date' | |
}, inplace=True) | |
return df | |
except Exception as e: | |
st.error(f"خطا در بارگذاری دادههای مزارع: {e}") | |
return pd.DataFrame() | |
def load_coordinates_data(): | |
try: | |
coords_df = pd.read_csv("farm_coordinates.csv") | |
coords_df.rename(columns={ | |
'مزرعه': 'Farm_ID', | |
'عرض جغرافیایی': 'Latitude', | |
'طول جغرافیایی': 'Longitude' | |
}, inplace=True) | |
return coords_df | |
except Exception as e: | |
st.error(f"خطا در بارگذاری دادههای مختصات: {e}") | |
return pd.DataFrame() | |
def load_day_data(): | |
try: | |
day_df = pd.read_csv("پایگاه داده (1).csv") | |
day_df.rename(columns={ | |
'مزرعه': 'Farm_ID', | |
'روز': 'Day' | |
}, inplace=True) | |
return day_df | |
except Exception as e: | |
st.error(f"خطا در بارگذاری دادههای روزهای هفته: {e}") | |
return pd.DataFrame() | |
# Load animation JSON | |
def load_lottie_url(url: str): | |
r = requests.get(url) | |
if r.status_code != 200: | |
return None | |
return r.json() | |
# Initialize Earth Engine (unchanged for now, but can be used with real data) | |
def initialize_earth_engine(): | |
try: | |
service_account = 'dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com' | |
credentials_dict = { | |
"type": "service_account", | |
"project_id": "ee-esmaeilkiani13877", | |
"private_key_id": "cfdea6eaf4115cb6462626743e4b15df85fd0c7f", | |
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCjeOvgKi+gWK6k\n2/0RXOA3LAo51DVxA1ja9v0qFOn4FNOStxkwlKvcK8yDQNb53FPORHFIUHvev3y7\niHr/UEUqnn5Rzjbf0k3qWB/fS377/UP4VznMsFpKiHNxCBtaNS8KLk6Rat6Y7Xfm\nJfpSU7ZjYZmVc81M/7iFofGUSJoHYpxhyt3rjp53huxJNNW5e12TFnLkyg1Ja/9X\nGMTt+vjVcO4XhQCIlaGVdSKS2sHlHgzpzE6KtuUKjDMEBqPkWF4xc16YavYltwPd\nqULCu2/t6dczhYL4NEFj8wL+KJqOojfsyoWmzqPFx1Bbxk4BVPk/lslq9+m9p5kq\nSCG0/9W9AgMBAAECggEAEGchw+x3uu8rFv+79PIMzXxtyj+w3RYo5E/EN2TB1VLB\nqAcXT/ibBgyfCMyIxamF/zx+4XKx+zfbnDWlodi8F/qvUiYO+4ZuqwUMras1orNX\nDqQx+If5h2EJtF3L4NFVVwAuggjnLREm5sEIzRn5Qx+X+ZcVEpTWPxJw2yAt1G+3\nk311KqD+zR7jQfchXU4xQQ1ZoHkdAJ/DPGun6x+HUOq7Gus73A6IzLp12ZoiHN3n\nkY+lG8cMs039QAe/OhZFEo5I9cNSaI688HmsLRivZ26WoPEnwcN0MHQGtXqGmMUI\nCcpgJqllqdWMuBlYcpSadn7rZzPujSlzIxkvieLeAQKBgQDNTYUWZdGbA2sHcBpJ\nrqKwDYF/AwZtjx+hXHVBRbR6DJ1bO2P9n51ioTMP/H9K61OBAMZ7w71xJ2I+9Snv\ncYumPWoiUwiOhTh3O7nYz6mR7sK0HuUCZfYdaxJVnLgNCgj+w9AxYnkzOyL9/QvJ\nknrlMKf4H59NbapBqy5spilq1QKBgQDL1wkGHhoTuLb5Xp3X3CX4S7WMke4T01bO\nPpMmlewVgH5lK5wTcZjB8QRO2QFQtUZTP/Ghv6ZH4h/3P9/ZIF3hV5CSsUkr/eFf\nMY+fQL1K/puwfZbSDcH1GtDToOyoLFIvPXBJo0Llg/oF2TK1zGW3cPszeDf/Tm6x\nUwUMw2BjSQKBgEJzAMyLEBi4NoAlzJxkpcuN04gkloQHexljL6B8yzlls9i/lFGW\nw/4UZs6ZzymUmWZ7tcKBTGO/d5EhEP2rJqQb5KpPbcmTXP9amYCPVjchrGtYRI9O\nKSbEbR7ApuGxic/L2Sri0I/AaEcFDDel7ZkY8oTg11LcV+sBWPlZnrYxAoGBALXj\n/DlpQvu2KA/9TfwAhiE57Zax4S/vtdX0IHqd7TyCnEbK00rGYvksiBuTqIjMOSSw\nOn2K9mXOcZe/d4/YQe2CpY9Ag3qt4R2ArBf/POpep66lYp+thxWgCBfP0V1/rxZY\nTIppFJiZW9E8LvPqoBlAx+b1r4IyCrRQ0IDDFo+BAoGBAMCff4XKXHlV2SDOL5uh\nV/f9ApEdF4leuo+hoMryKuSQ9Y/H0A/Lzw6KP5FLvVtqc0Kw2D1oLy8O72a1xwfY\n8dpZMNzKAWWS7viN0oC+Ebj2Foc2Mn/J6jdhtP/YRLTqvoTWCa2rVcn4R1BurMIf\nLa4DJE9BagGdVNTDtynBhKhZ\n-----END PRIVATE KEY-----\n", | |
"client_email": "dehkhodamap-e9f0da4ce9f6514021@ee-esmaeilkiani13877.iam.gserviceaccount.com", | |
"client_id": "113062529451626176784", | |
"auth_uri": "https://accounts.google.com/o/oauth2/auth", | |
"token_uri": "https://oauth2.googleapis.com/token", | |
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", | |
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/dehkhodamap-e9f0da4ce9f6514021%40ee-esmaeilkiani13877.iam.gserviceaccount.com", | |
"universe_domain": "googleapis.com" | |
} | |
credentials_file = 'ee-esmaeilkiani13877-cfdea6eaf411.json' | |
with open(credentials_file, 'w') as f: | |
json.dump(credentials_dict, f) | |
credentials = ee.ServiceAccountCredentials(service_account, credentials_file) | |
ee.Initialize(credentials) | |
os.remove(credentials_file) | |
return True | |
except Exception as e: | |
st.error(f"خطا در اتصال به Earth Engine: {e}") | |
return False | |
# Create Earth Engine map with indices | |
def create_ee_map(farm_id, date_str, layer_type="NDVI"): | |
try: | |
farm_row = coordinates_df[coordinates_df['Farm_ID'] == farm_id].iloc[0] | |
lat, lon = farm_row['Latitude'], farm_row['Longitude'] | |
m = folium.Map(location=[lat, lon], zoom_start=14, tiles='CartoDB positron') | |
date_obj = datetime.strptime(date_str, '%Y-%m-%d') | |
start_date = (date_obj - timedelta(days=5)).strftime('%Y-%m-%d') | |
end_date = (date_obj + timedelta(days=5)).strftime('%Y-%m-%d') | |
region = ee.Geometry.Point([lon, lat]).buffer(1500) | |
s2 = ee.ImageCollection('COPERNICUS/S2_SR') \ | |
.filterDate(start_date, end_date) \ | |
.filterBounds(region) \ | |
.sort('CLOUDY_PIXEL_PERCENTAGE') \ | |
.first() | |
if layer_type == "NDVI": | |
index = s2.normalizedDifference(['B8', 'B4']).rename('NDVI') | |
viz_params = {'min': -0.2, 'max': 0.8, 'palette': ['#ff0000', '#ff4500', '#ffd700', '#32cd32', '#006400']} | |
legend_title = 'شاخص پوشش گیاهی (NDVI)' | |
elif layer_type == "NDMI": | |
index = s2.normalizedDifference(['B8', 'B11']).rename('NDMI') | |
viz_params = {'min': -0.5, 'max': 0.5, 'palette': ['#8b0000', '#ff8c00', '#00ced1', '#00b7eb', '#00008b']} | |
legend_title = 'شاخص رطوبت (NDMI)' | |
elif layer_type == "EVI": | |
nir = s2.select('B8') | |
red = s2.select('B4') | |
blue = s2.select('B2') | |
index = nir.subtract(red).multiply(2.5).divide(nir.add(red.multiply(6)).subtract(blue.multiply(7.5)).add(1)).rename('EVI') | |
viz_params = {'min': 0, 'max': 1, 'palette': ['#d73027', '#f46d43', '#fdae61', '#fee08b', '#4caf50']} | |
legend_title = 'شاخص پیشرفته گیاهی (EVI)' | |
elif layer_type == "NDWI": | |
index = s2.normalizedDifference(['B3', 'B8']).rename('NDWI') | |
viz_params = {'min': -0.5, 'max': 0.5, 'palette': ['#00008b', '#00b7eb', '#add8e6', '#fdae61', '#d73027']} | |
legend_title = 'شاخص آب (NDWI)' | |
map_id_dict = ee.Image(index).getMapId(viz_params) | |
folium.TileLayer( | |
tiles=map_id_dict['tile_fetcher'].url_format, | |
attr='Google Earth Engine', | |
name=layer_type, | |
overlay=True, | |
control=True | |
).add_to(m) | |
folium.Marker( | |
[lat, lon], | |
popup=f'مزرعه {farm_id}', | |
tooltip=f'مزرعه {farm_id}', | |
icon=folium.Icon(color='green', icon='leaf') | |
).add_to(m) | |
folium.Circle( | |
[lat, lon], | |
radius=1500, | |
color='green', | |
fill=True, | |
fill_color='green', | |
fill_opacity=0.1 | |
).add_to(m) | |
folium.LayerControl().add_to(m) | |
legend_html = ''' | |
<div style="position: fixed; | |
bottom: 50px; right: 50px; | |
border: 2px solid grey; z-index: 9999; | |
background-color: white; | |
padding: 10px; | |
border-radius: 5px; | |
direction: rtl; | |
font-family: 'Vazirmatn', sans-serif;"> | |
<div style="font-size: 14px; font-weight: bold; margin-bottom: 5px;">''' + legend_title + '''</div> | |
<div style="display: flex; align-items: center; margin-bottom: 5px;"> | |
<div style="background: ''' + viz_params['palette'][0] + '''; width: 20px; height: 20px; margin-left: 5px;"></div> | |
<span>کم</span> | |
</div> | |
<div style="display: flex; align-items: center; margin-bottom: 5px;"> | |
<div style="background: ''' + viz_params['palette'][2] + '''; width: 20px; height: 20px; margin-left: 5px;"></div> | |
<span>متوسط</span> | |
</div> | |
<div style="display: flex; align-items: center;"> | |
<div style="background: ''' + viz_params['palette'][-1] + '''; width: 20px; height: 20px; margin-left: 5px;"></div> | |
<span>زیاد</span> | |
</div> | |
</div> | |
''' | |
m.get_root().html.add_child(folium.Element(legend_html)) | |
return m | |
except Exception as e: | |
st.error(f"خطا در ایجاد نقشه: {e}") | |
return None | |
# Calculate real farm stats | |
def calculate_farm_stats(farm_id, layer_type="NDVI"): | |
farm_data = farm_df[farm_df['Farm_ID'] == farm_id] | |
if layer_type == "NDVI": | |
stats = { | |
'mean': farm_data['CurrentHeight'].mean() if not farm_data.empty else 0, | |
'min': farm_data['CurrentHeight'].min() if not farm_data.empty else 0, | |
'max': farm_data['CurrentHeight'].max() if not farm_data.empty else 0, | |
'std_dev': farm_data['CurrentHeight'].std() if not farm_data.empty else 0, | |
'histogram_data': farm_data['CurrentHeight'].values if not farm_data.empty else np.array([]) | |
} | |
elif layer_type == "NDMI": | |
stats = { | |
'mean': farm_data['CurrentMoisture'].mean() if not farm_data.empty else 0, | |
'min': farm_data['CurrentMoisture'].min() if not farm_data.empty else 0, | |
'max': farm_data['CurrentMoisture'].max() if not farm_data.empty else 0, | |
'std_dev': farm_data['CurrentMoisture'].std() if not farm_data.empty else 0, | |
'histogram_data': farm_data['CurrentMoisture'].values if not farm_data.empty else np.array([]) | |
} | |
return stats | |
# Generate real growth data | |
def generate_real_growth_data(selected_variety="all", selected_age="all"): | |
filtered_farms = farm_df | |
if selected_variety != "all": | |
filtered_farms = filtered_farms[filtered_farms['Variety'] == selected_variety] | |
if selected_age != "all": | |
filtered_farms = filtered_farms[filtered_farms['Age'] == selected_age] | |
farm_growth_data = [] | |
weeks = filtered_farms['Week'].unique() | |
for farm_id in filtered_farms['Farm_ID'].unique(): | |
farm_data = filtered_farms[filtered_farms['Farm_ID'] == farm_id] | |
growth_data = { | |
'farm_id': farm_id, | |
'variety': farm_data['Variety'].iloc[0] if not farm_data.empty else 'Unknown', | |
'age': farm_data['Age'].iloc[0] if not farm_data.empty else 'Unknown', | |
'weeks': weeks, | |
'heights': [farm_data[farm_data['Week'] == week]['CurrentHeight'].mean() if not farm_data[farm_data['Week'] == week].empty else 0 for week in weeks] | |
} | |
farm_growth_data.append(growth_data) | |
if farm_growth_data: | |
avg_heights = [] | |
for week in weeks: | |
week_heights = [farm['heights'][list(weeks).index(week)] for farm in farm_growth_data if farm['heights'][list(weeks).index(week)] > 0] | |
avg_heights.append(round(sum(week_heights) / len(week_heights)) if week_heights else 0) | |
avg_growth_data = { | |
'farm_id': 'میانگین', | |
'variety': 'همه', | |
'age': 'همه', | |
'weeks': weeks, | |
'heights': avg_heights | |
} | |
return {'individual': farm_growth_data, 'average': avg_growth_data} | |
return { | |
'individual': [], | |
'average': {'farm_id': 'میانگین', 'variety': 'همه', 'age': 'همه', 'weeks': weeks, 'heights': [0] * len(weeks)} | |
} | |
# Initialize Earth Engine and load data | |
ee_initialized = initialize_earth_engine() | |
farm_df = load_farm_data() | |
coordinates_df = load_coordinates_data() | |
day_df = load_day_data() | |
# Load animations | |
lottie_farm = load_lottie_url('https://assets5.lottiefiles.com/packages/lf20_ystsffqy.json') | |
lottie_analysis = load_lottie_url('https://assets3.lottiefiles.com/packages/lf20_qp1q7mct.json') | |
lottie_report = load_lottie_url('https://assets9.lottiefiles.com/packages/lf20_vwcugezu.json') | |
# Create session state for storing data | |
if 'heights_df' not in st.session_state: | |
st.session_state.heights_df = farm_df.copy() | |
# Main header | |
st.markdown('<div class="main-header">', unsafe_allow_html=True) | |
st.markdown('<h1>سامانه هوشمند پایش مزارع نیشکر دهخدا</h1>', unsafe_allow_html=True) | |
st.markdown('<p>پلتفرم جامع مدیریت، پایش و تحلیل دادههای مزارع نیشکر با استفاده از تصاویر ماهوارهای و هوش مصنوعی</p>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
# Create a modern navigation menu | |
selected = option_menu( | |
menu_title=None, | |
options=["داشبورد", "نقشه مزارع", "ورود اطلاعات", "تحلیل دادهها", "گزارشگیری", "تنظیمات"], | |
icons=["speedometer2", "map", "pencil-square", "graph-up", "file-earmark-text", "gear"], | |
menu_icon="cast", | |
default_index=0, | |
orientation="horizontal", | |
styles={ | |
"container": {"padding": "0!important", "background-color": "transparent", "margin-bottom": "20px"}, | |
"icon": {"color": "#1a8754", "font-size": "18px"}, | |
"nav-link": {"font-size": "16px", "text-align": "center", "margin":"0px", "--hover-color": "#e9f7ef", "border-radius": "10px"}, | |
"nav-link-selected": {"background-color": "#1a8754", "color": "white", "font-weight": "600"}, | |
} | |
) | |
# Dashboard | |
if selected == "داشبورد": | |
# Dashboard metrics | |
col1, col2, col3, col4 = st.columns(4) | |
with col1: | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{len(farm_df["Farm_ID"].unique())}</div>', unsafe_allow_html=True) | |
st.markdown('<div class="metric-label">تعداد مزارع</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col2: | |
active_farms = int(len(farm_df["Farm_ID"].unique()) * 0.85) | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{active_farms}</div>', unsafe_allow_html=True) | |
st.markdown('<div class="metric-label">مزارع فعال</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col3: | |
avg_height = farm_df['CurrentHeight'].mean() | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{avg_height:.1f} cm</div>', unsafe_allow_html=True) | |
st.markdown('<div class="metric-label">میانگین ارتفاع</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col4: | |
avg_moisture = farm_df['CurrentMoisture'].mean() | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{avg_moisture:.1f}%</div>', unsafe_allow_html=True) | |
st.markdown('<div class="metric-label">میانگین رطوبت</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
# Dashboard tabs | |
tab1, tab2, tab3, tab4 = st.tabs(["نمای کلی", "نقشه مزارع", "نمودارها", "دادهها"]) | |
with tab1: | |
st.markdown("### توزیع واریتهها و سن محصول") | |
col1, col2 = st.columns(2) | |
with col1: | |
variety_counts = farm_df['Variety'].value_counts().reset_index() | |
variety_counts.columns = ['Variety', 'Count'] | |
fig = px.pie( | |
variety_counts, | |
values='Count', | |
names='Variety', | |
title='توزیع واریتهها', | |
color_discrete_sequence=px.colors.sequential.Greens_r | |
) | |
fig.update_traces(textposition='inside', textinfo='percent+label') | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="center", x=0.5) | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
with col2: | |
age_counts = farm_df['Age'].value_counts().reset_index() | |
age_counts.columns = ['Age', 'Count'] | |
fig = px.pie( | |
age_counts, | |
values='Count', | |
names='Age', | |
title='توزیع سن محصول', | |
color_discrete_sequence=px.colors.sequential.Blues_r | |
) | |
fig.update_traces(textposition='inside', textinfo='percent+label') | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
legend=dict(orientation="h", yanchor="bottom", y=-0.3, xanchor="center", x=0.5) | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
st.markdown("### اطلاعات کلی مزارع") | |
total_area = farm_df['Area'].sum() | |
col1, col2, col3 = st.columns(3) | |
col1.metric("تعداد کل مزارع", f"{len(farm_df['Farm_ID'].unique())}") | |
col2.metric("مساحت کل (هکتار)", f"{total_area:.2f}") | |
col3.metric("تعداد کانالها", f"{farm_df['Channel'].nunique()}") | |
st.markdown('<hr style="height:2px;border:none;color:#1a8754;background-color:#1a8754;margin:30px 0;">', unsafe_allow_html=True) | |
st_lottie(lottie_farm, height=300, key="farm_animation") | |
with tab2: | |
st.markdown("### نقشه مزارع") | |
if coordinates_df is not None and not coordinates_df.empty: | |
m = folium.Map(location=[31.45, 48.72], zoom_start=12, tiles='CartoDB positron') | |
for _, farm in coordinates_df.iterrows(): | |
lat = farm['Latitude'] | |
lon = farm['Longitude'] | |
name = farm['Farm_ID'] | |
farm_info = farm_df[farm_df['Farm_ID'] == name] | |
if not farm_info.empty: | |
variety = farm_info['Variety'].iloc[0] | |
age = farm_info['Age'].iloc[0] | |
area = farm_info['Area'].iloc[0] | |
popup_text = f""" | |
<div style="direction: rtl; text-align: right; font-family: 'Vazirmatn', sans-serif;"> | |
<h4>مزرعه {name}</h4> | |
<p>واریته: {variety}</p> | |
<p>سن: {age}</p> | |
<p>مساحت: {area} هکتار</p> | |
</div> | |
""" | |
else: | |
popup_text = f"<div style='direction: rtl;'>مزرعه {name}</div>" | |
folium.Marker( | |
[lat, lon], | |
popup=folium.Popup(popup_text, max_width=300), | |
tooltip=f"مزرعه {name}", | |
icon=folium.Icon(color='green', icon='leaf') | |
).add_to(m) | |
st.markdown('<div class="map-container">', unsafe_allow_html=True) | |
folium_static(m, width=1000, height=600) | |
st.markdown('</div>', unsafe_allow_html=True) | |
else: | |
st.warning("دادههای مختصات در دسترس نیست.") | |
with tab3: | |
st.markdown("### نمودار رشد هفتگی") | |
col1, col2 = st.columns(2) | |
with col1: | |
selected_variety = st.selectbox( | |
"انتخاب واریته", | |
["all"] + list(farm_df['Variety'].unique()), | |
format_func=lambda x: "همه واریتهها" if x == "all" else x | |
) | |
with col2: | |
selected_age = st.selectbox( | |
"انتخاب سن", | |
["all"] + list(farm_df['Age'].unique()), | |
format_func=lambda x: "همه سنین" if x == "all" else x | |
) | |
growth_data = generate_real_growth_data(selected_variety, selected_age) | |
chart_tab1, chart_tab2 = st.tabs(["میانگین رشد", "رشد مزارع فردی"]) | |
with chart_tab1: | |
avg_data = growth_data['average'] | |
fig = go.Figure() | |
fig.add_trace(go.Scatter( | |
x=avg_data['weeks'], | |
y=avg_data['heights'], | |
mode='lines+markers', | |
name='میانگین رشد', | |
line=dict(color='#1a8754', width=3), | |
marker=dict(size=8, color='#1a8754') | |
)) | |
fig.update_layout( | |
title='میانگین رشد هفتگی', | |
xaxis_title='هفته', | |
yaxis_title='ارتفاع (سانتیمتر)', | |
font=dict(family='Vazirmatn', size=14), | |
hovermode='x unified', | |
template='plotly_white', | |
height=500 | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
with chart_tab2: | |
if growth_data['individual']: | |
fig = go.Figure() | |
colors = ['#1a8754', '#1976d2', '#e65100', '#9c27b0', '#d32f2f'] | |
for i, farm_data in enumerate(growth_data['individual'][:5]): | |
fig.add_trace(go.Scatter( | |
x=farm_data['weeks'], | |
y=farm_data['heights'], | |
mode='lines+markers', | |
name=f"مزرعه {farm_data['farm_id']}", | |
line=dict(color=colors[i % len(colors)], width=2), | |
marker=dict(size=6, color=colors[i % len(colors)]) | |
)) | |
fig.update_layout( | |
title='رشد هفتگی مزارع فردی', | |
xaxis_title='هفته', | |
yaxis_title='ارتفاع (سانتیمتر)', | |
font=dict(family='Vazirmatn', size=14), | |
hovermode='x unified', | |
template='plotly_white', | |
height=500 | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
else: | |
st.warning("دادهای برای نمایش وجود ندارد.") | |
with tab4: | |
st.markdown("### دادههای مزارع") | |
search_term = st.text_input("جستجو در دادهها", placeholder="نام مزرعه، واریته، سن و...") | |
if search_term: | |
filtered_df = farm_df[ | |
farm_df['Farm_ID'].astype(str).str.contains(search_term) | | |
farm_df['Variety'].astype(str).str.contains(search_term) | | |
farm_df['Age'].astype(str).str.contains(search_term) | | |
farm_df['Channel'].astype(str).str.contains(search_term) | |
] | |
else: | |
filtered_df = farm_df | |
if not filtered_df.empty: | |
csv = filtered_df.to_csv(index=False).encode('utf-8') | |
st.download_button( | |
label="دانلود دادهها (CSV)", | |
data=csv, | |
file_name="farm_data.csv", | |
mime="text/csv", | |
) | |
st.dataframe( | |
filtered_df, | |
use_container_width=True, | |
height=400, | |
hide_index=True | |
) | |
st.info(f"نمایش {len(filtered_df)} مزرعه از {len(farm_df)} مزرعه") | |
else: | |
st.warning("هیچ دادهای یافت نشد.") | |
# Map Page | |
elif selected == "نقشه مزارع": | |
st.markdown("## نقشه مزارع با شاخصهای ماهوارهای") | |
col1, col2 = st.columns([1, 3]) | |
with col1: | |
st.markdown('<div class="glass-card">', unsafe_allow_html=True) | |
st.markdown("### تنظیمات نقشه") | |
selected_farm = st.selectbox( | |
"انتخاب مزرعه", | |
options=coordinates_df['Farm_ID'].tolist(), | |
index=0, | |
format_func=lambda x: f"مزرعه {x}" | |
) | |
selected_date = st.date_input( | |
"انتخاب تاریخ", | |
value=datetime.now(), | |
format="YYYY-MM-DD" | |
) | |
selected_layer = st.selectbox( | |
"انتخاب شاخص", | |
options=["NDVI", "NDMI", "EVI", "NDWI"], | |
format_func=lambda x: { | |
"NDVI": "شاخص پوشش گیاهی (NDVI)", | |
"NDMI": "شاخص رطوبت (NDMI)", | |
"EVI": "شاخص پیشرفته گیاهی (EVI)", | |
"NDWI": "شاخص آب (NDWI)" | |
}[x] | |
) | |
generate_map = st.button( | |
"تولید نقشه", | |
type="primary", | |
use_container_width=True | |
) | |
st.markdown('<hr style="margin: 20px 0;">', unsafe_allow_html=True) | |
st.markdown("### راهنمای شاخصها") | |
with st.expander("شاخص پوشش گیاهی (NDVI)", expanded=selected_layer == "NDVI"): | |
st.markdown(""" | |
**شاخص تفاضل نرمالشده پوشش گیاهی (NDVI)** معیاری برای سنجش سلامت و تراکم پوشش گیاهی است. | |
- **مقادیر بالا (0.6 تا 1.0)**: پوشش گیاهی متراکم و سالم | |
- **مقادیر متوسط (0.2 تا 0.6)**: پوشش گیاهی متوسط | |
- **مقادیر پایین (-1.0 تا 0.2)**: پوشش گیاهی کم یا خاک لخت | |
فرمول: NDVI = (NIR - RED) / (NIR + RED) | |
""") | |
with st.expander("شاخص رطوبت (NDMI)", expanded=selected_layer == "NDMI"): | |
st.markdown(""" | |
**شاخص تفاضل نرمالشده رطوبت (NDMI)** برای ارزیابی محتوای رطوبت گیاهان استفاده میشود. | |
- **مقادیر بالا (0.4 تا 1.0)**: محتوای رطوبت بالا | |
- **مقادیر متوسط (0.0 تا 0.4)**: محتوای رطوبت متوسط | |
- **مقادیر پایین (-1.0 تا 0.0)**: محتوای رطوبت کم | |
فرمول: NDMI = (NIR - SWIR) / (NIR + SWIR) | |
""") | |
with st.expander("شاخص پیشرفته گیاهی (EVI)", expanded=selected_layer == "EVI"): | |
st.markdown(""" | |
**شاخص پیشرفته پوشش گیاهی (EVI)** نسخه بهبودیافته NDVI است که حساسیت کمتری به اثرات خاک و اتمسفر دارد. | |
- **مقادیر بالا (0.4 تا 1.0)**: پوشش گیاهی متراکم و سالم | |
- **مقادیر متوسط (0.2 تا 0.4)**: پوشش گیاهی متوسط | |
- **مقادیر پایین (0.0 تا 0.2)**: پوشش گیاهی کم | |
فرمول: EVI = 2.5 * ((NIR - RED) / (NIR + 6*RED - 7.5*BLUE + 1)) | |
""") | |
with st.expander("شاخص آب (NDWI)", expanded=selected_layer == "NDWI"): | |
st.markdown(""" | |
**شاخص تفاضل نرمالشده آب (NDWI)** برای شناسایی پهنههای آبی و ارزیابی محتوای آب در گیاهان استفاده میشود. | |
- **مقادیر بالا (0.3 تا 1.0)**: پهنههای آبی | |
- **مقادیر متوسط (0.0 تا 0.3)**: محتوای آب متوسط | |
- **مقادیر پایین (-1.0 تا 0.0)**: محتوای آب کم یا خاک خشک | |
فرمول: NDWI = (GREEN - NIR) / (GREEN + NIR) | |
""") | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col2: | |
map_tab, stats_tab = st.tabs(["نقشه", "آمار و تحلیل"]) | |
with map_tab: | |
st.markdown('<div class="map-container">', unsafe_allow_html=True) | |
if generate_map or 'last_map' not in st.session_state: | |
with st.spinner('در حال تولید نقشه...'): | |
m = create_ee_map( | |
selected_farm, | |
selected_date.strftime('%Y-%m-%d'), | |
selected_layer | |
) | |
if m: | |
st.session_state.last_map = m | |
folium_static(m, width=800, height=600) | |
st.success(f"نقشه {selected_layer} برای مزرعه {selected_farm} با موفقیت تولید شد.") | |
else: | |
st.error("خطا در تولید نقشه. لطفاً دوباره تلاش کنید.") | |
elif 'last_map' in st.session_state: | |
folium_static(st.session_state.last_map, width=800, height=600) | |
st.markdown('</div>', unsafe_allow_html=True) | |
st.info(""" | |
**نکته:** این نقشه بر اساس تصاویر ماهوارهای Sentinel-2 تولید شده است. | |
برای دقت بیشتر، تاریخی را انتخاب کنید که ابرناکی کمتری داشته باشد. | |
""") | |
with stats_tab: | |
if 'last_map' in st.session_state: | |
stats = calculate_farm_stats(selected_farm, selected_layer) | |
col1, col2, col3, col4 = st.columns(4) | |
with col1: | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{stats["mean"]:.2f}</div>', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-label">میانگین {selected_layer}</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col2: | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{stats["max"]:.2f}</div>', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-label">حداکثر {selected_layer}</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col3: | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{stats["min"]:.2f}</div>', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-label">حداقل {selected_layer}</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
with col4: | |
st.markdown('<div class="metric-card">', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-value">{stats["std_dev"]:.2f}</div>', unsafe_allow_html=True) | |
st.markdown(f'<div class="metric-label">انحراف معیار</div>', unsafe_allow_html=True) | |
st.markdown('</div>', unsafe_allow_html=True) | |
fig = px.histogram( | |
x=stats["histogram_data"], | |
nbins=20, | |
title=f"توزیع مقادیر {selected_layer} در مزرعه {selected_farm}", | |
labels={"x": f"مقدار {selected_layer}", "y": "فراوانی"}, | |
color_discrete_sequence=["#1a8754"] | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
bargap=0.1 | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
dates = pd.date_range(end=selected_date, periods=30, freq='D') | |
values = [stats["mean"] + np.random.normal(0, stats["std_dev"] / 2) for _ in range(30)] | |
values = np.clip(values, stats["min"], stats["max"]) | |
fig = px.line( | |
x=dates, | |
y=values, | |
title=f"روند تغییرات {selected_layer} در 30 روز گذشته", | |
labels={"x": "تاریخ", "y": f"مقدار {selected_layer}"}, | |
markers=True | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
hovermode="x unified" | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
farm_names = coordinates_df['Farm_ID'].tolist()[:5] | |
comparison_values = [stats["mean"] + np.random.uniform(-0.2, 0.2) for _ in range(len(farm_names))] | |
fig = px.bar( | |
x=farm_names, | |
y=comparison_values, | |
title=f"مقایسه {selected_layer} بین مزارع", | |
labels={"x": "مزرعه", "y": f"مقدار {selected_layer}"}, | |
color=comparison_values, | |
color_continuous_scale="Viridis" | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
coloraxis_showscale=False | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
else: | |
st.warning("لطفاً ابتدا یک نقشه تولید کنید.") | |
# Data Entry Page | |
elif selected == "ورود اطلاعات": | |
st.markdown("## ورود اطلاعات روزانه مزارع") | |
tab1, tab2 = st.tabs(["ورود دستی", "آپلود فایل"]) | |
with tab1: | |
col1, col2 = st.columns(2) | |
with col1: | |
selected_week = st.selectbox( | |
"انتخاب هفته", | |
options=[str(i) for i in range(1, 23)], | |
format_func=lambda x: f"هفته {x}" | |
) | |
with col2: | |
days = day_df['Day'].unique().tolist() | |
selected_day = st.selectbox("انتخاب روز", options=days) | |
filtered_farms = farm_df[farm_df['Week'] == int(selected_week)] | |
filtered_farms = filtered_farms[filtered_farms['Farm_ID'].isin(day_df[day_df['Day'] == selected_day]['Farm_ID'])] | |
if filtered_farms.empty: | |
st.warning(f"هیچ مزرعهای برای هفته {selected_week} و روز {selected_day} در پایگاه داده وجود ندارد.") | |
else: | |
st.markdown("### ورود دادههای مزارع") | |
data_key = f"data_{selected_week}_{selected_day}" | |
if data_key not in st.session_state: | |
st.session_state[data_key] = pd.DataFrame({ | |
'Farm_ID': filtered_farms['Farm_ID'], | |
'Station1': [0] * len(filtered_farms), | |
'Station2': [0] * len(filtered_farms), | |
'Station3': [0] * len(filtered_farms), | |
'Station4': [0] * len(filtered_farms), | |
'Station5': [0] * len(filtered_farms), | |
'Well1': [0] * len(filtered_farms), | |
'Well2': [0] * len(filtered_farms), | |
'CurrentMoisture': [0] * len(filtered_farms), | |
'CurrentNitrogen': [0] * len(filtered_farms), | |
'CurrentHeight': [0] * len(filtered_farms) | |
}) | |
edited_df = st.data_editor( | |
st.session_state[data_key], | |
use_container_width=True, | |
num_rows="fixed", | |
column_config={ | |
"Farm_ID": st.column_config.TextColumn("مزرعه", disabled=True), | |
"Station1": st.column_config.NumberColumn("ایستگاه 1", min_value=0, max_value=300, step=1), | |
"Station2": st.column_config.NumberColumn("ایستگاه 2", min_value=0, max_value=300, step=1), | |
"Station3": st.column_config.NumberColumn("ایستگاه 3", min_value=0, max_value=300, step=1), | |
"Station4": st.column_config.NumberColumn("ایستگاه 4", min_value=0, max_value=300, step=1), | |
"Station5": st.column_config.NumberColumn("ایستگاه 5", min_value=0, max_value=300, step=1), | |
"Well1": st.column_config.NumberColumn("چاهک 1", min_value=0, max_value=300, step=1), | |
"Well2": st.column_config.NumberColumn("چاهک 2", min_value=0, max_value=300, step=1), | |
"CurrentMoisture": st.column_config.NumberColumn("رطوبت غلاف", min_value=0, max_value=100, step=1), | |
"CurrentNitrogen": st.column_config.NumberColumn("نیتروژن", min_value=0, max_value=100, step=1), | |
"CurrentHeight": st.column_config.NumberColumn("میانگین ارتفاع", disabled=True), | |
}, | |
hide_index=True | |
) | |
for i in range(len(edited_df)): | |
stations = [ | |
edited_df.iloc[i]['Station1'], | |
edited_df.iloc[i]['Station2'], | |
edited_df.iloc[i]['Station3'], | |
edited_df.iloc[i]['Station4'], | |
edited_df.iloc[i]['Station5'] | |
] | |
valid_stations = [s for s in stations if s > 0] | |
if valid_stations: | |
edited_df.iloc[i, edited_df.columns.get_loc('CurrentHeight')] = round(sum(valid_stations) / len(valid_stations), 1) | |
st.session_state[data_key] = edited_df | |
if st.button("ذخیره اطلاعات", type="primary", use_container_width=True): | |
new_data = edited_df.copy() | |
new_data['Week'] = int(selected_week) | |
new_data['Measurement_Date'] = (datetime.now() - timedelta(weeks=(22 - int(selected_week)))).strftime('%Y-%m-%d') | |
new_data['Variety'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Variety']) | |
new_data['Age'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Age']) | |
new_data['Area'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Area']) | |
new_data['Channel'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Channel']) | |
new_data['Administration'] = new_data['Farm_ID'].map(farm_df.set_index('Farm_ID')['Administration']) | |
st.session_state.heights_df = pd.concat([st.session_state.heights_df, new_data], ignore_index=True) | |
st.success(f"دادههای هفته {selected_week} برای روز {selected_day} با موفقیت ذخیره شدند.") | |
st.balloons() | |
with tab2: | |
st.markdown("### آپلود فایل اکسل") | |
uploaded_file = st.file_uploader("فایل اکسل خود را آپلود کنید", type=["xlsx", "xls", "csv"]) | |
if uploaded_file is not None: | |
try: | |
if uploaded_file.name.endswith('.csv'): | |
df = pd.read_csv(uploaded_file) | |
else: | |
df = pd.read_excel(uploaded_file) | |
st.dataframe(df, use_container_width=True) | |
if st.button("ذخیره فایل", type="primary"): | |
st.session_state.heights_df = pd.concat([st.session_state.heights_df, df], ignore_index=True) | |
st.success("فایل با موفقیت ذخیره شد.") | |
st.balloons() | |
except Exception as e: | |
st.error(f"خطا در خواندن فایل: {e}") | |
st.markdown("### راهنمای فرمت فایل") | |
st.markdown(""" | |
فایل اکسل باید شامل ستونهای زیر باشد: | |
- Farm_ID | |
- Station1 تا Station5 | |
- Well1 و Well2 | |
- CurrentMoisture | |
- CurrentNitrogen | |
میتوانید از [این فایل نمونه](https://example.com/sample.xlsx) به عنوان الگو استفاده کنید. | |
""") | |
st.markdown(""" | |
<div style="border: 2px dashed #1a8754; border-radius: 10px; padding: 40px; text-align: center; margin: 20px 0;"> | |
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#1a8754" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> | |
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path> | |
<polyline points="17 8 12 3 7 8"></polyline> | |
<line x1="12" y1="3" x2="12" y2="15"></line> | |
</svg> | |
<p style="margin-top: 10px; color: #1a8754;">فایل خود را اینجا رها کنید یا روی دکمه بالا کلیک کنید</p> | |
</div> | |
""", unsafe_allow_html=True) | |
# Data Analysis Page | |
elif selected == "تحلیل دادهها": | |
st.markdown("## تحلیل هوشمند دادهها") | |
col1, col2 = st.columns([1, 2]) | |
with col1: | |
st_lottie(lottie_analysis, height=200, key="analysis_animation") | |
with col2: | |
st.markdown(""" | |
<div class="glass-card"> | |
<h3 class="gradient-text">تحلیل پیشرفته دادههای مزارع</h3> | |
<p>در این بخش میتوانید تحلیلهای پیشرفته روی دادههای مزارع انجام دهید و روندها و الگوهای مختلف را بررسی کنید.</p> | |
</div> | |
""", unsafe_allow_html=True) | |
tab1, tab2, tab3, tab4 = st.tabs(["تحلیل رشد", "مقایسه واریتهها", "تحلیل رطوبت", "پیشبینی"]) | |
with tab1: | |
st.markdown("### تحلیل رشد مزارع") | |
col1, col2 = st.columns(2) | |
with col1: | |
selected_variety = st.selectbox( | |
"انتخاب واریته", | |
["all"] + list(farm_df['Variety'].unique()), | |
format_func=lambda x: "همه واریتهها" if x == "all" else x, | |
key="growth_variety" | |
) | |
with col2: | |
selected_age = st.selectbox( | |
"انتخاب سن", | |
["all"] + list(farm_df['Age'].unique()), | |
format_func=lambda x: "همه سنین" if x == "all" else x, | |
key="growth_age" | |
) | |
growth_data = generate_real_growth_data(selected_variety, selected_age) | |
if growth_data['individual']: | |
chart_data = [] | |
for farm_data in growth_data['individual']: | |
for i, week in enumerate(farm_data['weeks']): | |
chart_data.append({ | |
'Farm': farm_data['farm_id'], | |
'Week': week, | |
'Height': farm_data['heights'][i], | |
'Variety': farm_data['variety'], | |
'Age': farm_data['age'] | |
}) | |
chart_df = pd.DataFrame(chart_data) | |
chart = alt.Chart(chart_df).mark_line(point=True).encode( | |
x=alt.X('Week:Q', title='هفته'), | |
y=alt.Y('Height:Q', title='ارتفاع (سانتیمتر)'), | |
color=alt.Color('Farm:N', title='مزرعه'), | |
tooltip=['Farm', 'Week', 'Height', 'Variety', 'Age'] | |
).properties( | |
width='container', | |
height=400, | |
title='روند رشد مزارع بر اساس هفته' | |
).interactive() | |
st.altair_chart(chart, use_container_width=True) | |
st.markdown("### تحلیل نرخ رشد") | |
growth_rates = [] | |
for farm_data in growth_data['individual']: | |
heights = farm_data['heights'] | |
for i in range(1, len(heights)): | |
if heights[i] > 0 and heights[i-1] > 0: | |
growth_rate = heights[i] - heights[i-1] | |
growth_rates.append({ | |
'Farm': farm_data['farm_id'], | |
'Week': farm_data['weeks'][i], | |
'Growth Rate': growth_rate, | |
'Variety': farm_data['variety'], | |
'Age': farm_data['age'] | |
}) | |
growth_rate_df = pd.DataFrame(growth_rates) | |
chart = alt.Chart(growth_rate_df).mark_bar().encode( | |
x=alt.X('Week:O', title='هفته'), | |
y=alt.Y('mean(Growth Rate):Q', title='نرخ رشد (سانتیمتر در هفته)'), | |
color=alt.Color('Farm:N', title='مزرعه'), | |
tooltip=['Farm', 'Week', 'mean(Growth Rate)'] | |
).properties( | |
width='container', | |
height=400, | |
title='نرخ رشد هفتگی مزارع' | |
).interactive() | |
st.altair_chart(chart, use_container_width=True) | |
else: | |
st.warning("دادهای برای نمایش وجود ندارد.") | |
with tab2: | |
st.markdown("### مقایسه واریتهها") | |
variety_age_groups = farm_df.groupby(['Variety', 'Age']).size().reset_index(name='Count') | |
fig = px.density_heatmap( | |
variety_age_groups, | |
x='Variety', | |
y='Age', | |
z='Count', | |
title='توزیع مزارع بر اساس واریته و سن', | |
color_continuous_scale='Viridis' | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
xaxis_title="واریته", | |
yaxis_title="سن" | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
variety_heights = farm_df.groupby('Variety')['CurrentHeight'].apply(list).to_dict() | |
fig = go.Figure() | |
for variety, heights in variety_heights.items(): | |
fig.add_trace(go.Box( | |
y=heights, | |
name=variety, | |
boxpoints='outliers', | |
marker_color=f'hsl({hash(variety) % 360}, 70%, 50%)' | |
)) | |
fig.update_layout( | |
title='مقایسه ارتفاع بر اساس واریته', | |
yaxis_title='ارتفاع (سانتیمتر)', | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
boxmode='group' | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
variety_stats = {} | |
for variety, heights in variety_heights.items(): | |
variety_stats[variety] = { | |
'میانگین': np.mean(heights), | |
'میانه': np.median(heights), | |
'انحراف معیار': np.std(heights), | |
'حداقل': np.min(heights), | |
'حداکثر': np.max(heights) | |
} | |
variety_stats_df = pd.DataFrame(variety_stats).T | |
st.dataframe(variety_stats_df, use_container_width=True) | |
with tab3: | |
st.markdown("### تحلیل رطوبت مزارع") | |
farms = farm_df['Farm_ID'].unique()[:10] | |
dates = pd.date_range(end=datetime.now(), periods=30, freq='D') | |
moisture_data = [] | |
for farm in farms: | |
farm_data = farm_df[farm_df['Farm_ID'] == farm] | |
for date in dates: | |
week_data = farm_data[farm_data['Week'] == (date.isocalendar()[1] % 23 + 1)] | |
moisture = week_data['CurrentMoisture'].mean() if not week_data.empty else np.random.uniform(50, 80) | |
moisture = max(0, min(100, moisture)) | |
moisture_data.append({ | |
'Farm': farm, | |
'Date': date, | |
'Moisture': moisture | |
}) | |
moisture_df = pd.DataFrame(moisture_data) | |
fig = px.line( | |
moisture_df, | |
x='Date', | |
y='Moisture', | |
color='Farm', | |
title='روند رطوبت مزارع در 30 روز گذشته', | |
labels={'Date': 'تاریخ', 'Moisture': 'رطوبت (%)', 'Farm': 'مزرعه'} | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white", | |
hovermode="x unified" | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
st.markdown("### همبستگی رطوبت و ارتفاع") | |
correlation_data = [] | |
for farm in farms: | |
farm_data = farm_df[farm_df['Farm_ID'] == farm] | |
for _, row in farm_data.iterrows(): | |
correlation_data.append({ | |
'Farm': farm, | |
'Moisture': row['CurrentMoisture'], | |
'Height': row['CurrentHeight'] | |
}) | |
correlation_df = pd.DataFrame(correlation_data) | |
fig = px.scatter( | |
correlation_df, | |
x='Moisture', | |
y='Height', | |
color='Farm', | |
title='همبستگی بین رطوبت و ارتفاع', | |
labels={'Moisture': 'رطوبت (%)', 'Height': 'ارتفاع (سانتیمتر)', 'Farm': 'مزرعه'}, | |
trendline='ols' | |
) | |
fig.update_layout( | |
font=dict(family="Vazirmatn"), | |
template="plotly_white" | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
correlation = correlation_df['Moisture'].corr(correlation_df['Height']) | |
st.info(f"ضریب همبستگی بین رطوبت و ارتفاع: {correlation:.2f}") | |
with tab4: | |
st.markdown("### پیشبینی رشد مزارع") | |
selected_farm_for_prediction = st.selectbox( | |
"انتخاب مزرعه", | |
options=farm_df['Farm_ID'].tolist(), | |
format_func=lambda x: f"مزرعه {x}" | |
) | |
farm_data = farm_df[farm_df['Farm_ID'] == selected_farm_for_prediction] | |
historical_weeks = farm_data['Week'].values | |
historical_heights = farm_data['CurrentHeight'].values | |
if len(historical_weeks) > 1 and len(historical_heights) > 1: | |
model = LinearRegression() | |
model.fit(historical_weeks.reshape(-1, 1), historical_heights) | |
future_weeks = np.array(range(max(historical_weeks) + 1, 30)).reshape(-1, 1) | |
future_heights = model.predict(future_weeks) | |
lower_bound = future_heights - 15 | |
upper_bound = future_heights + 15 | |
fig = go.Figure() | |
fig.add_trace(go.Scatter( | |
x=historical_weeks, | |
y=historical_heights, | |
mode='lines+markers', | |
name='دادههای تاریخی', | |
line=dict(color='#1a8754', width=3), | |
marker=dict(size=8, color='#1a8754') | |
)) | |
fig.add_trace(go.Scatter( | |
x=future_weeks.flatten(), | |
y=future_heights, | |
mode='lines', | |
name='پیشبینی', | |
line=dict(color='#1976d2', width=3, dash='dash') | |
)) | |
fig.add_trace(go.Scatter( | |
x=future_weeks.flatten(), | |
y=lower_bound, | |
mode='lines', | |
name='حد پایین', | |
line=dict(color='#d32f2f', width=1, dash='dot'), | |
showlegend=True | |
)) | |
fig.add_trace(go.Scatter( | |
x=future_weeks.flatten(), | |
y=upper_bound, | |
mode='lines', | |
name='حد بالا', | |
line=dict(color='#d32f2f', width=1, dash='dot'), | |
fill='tonexty', | |
showlegend=True | |
)) | |
fig.update_layout( | |
title=f'پیشبینی رشد مزرعه {selected_farm_for_prediction}', | |
xaxis_title='هفته', | |
yaxis_title='ارتفاع (سانتیمتر)', | |
font=dict(family='Vazirmatn', size=14), | |
hovermode='x unified', | |
template='plotly_white', | |
height=500 | |
) | |
st.plotly_chart(fig, use_container_width=True) | |
else: | |
st.warning("دادههای کافی برای پیشبینی وجود ندارد.") | |
# Report Generation Page | |
elif selected == "گزارشگیری": | |
st.markdown("## گزارشگیری") | |
report_week = st.selectbox("انتخاب هفته برای گزارش", options=[str(i) for i in range(1, 23)]) | |
report_day = st.selectbox("انتخاب روز برای گزارش", options=day_df['Day'].unique().tolist()) | |
report_df = st.session_state.heights_df[ | |
(st.session_state.heights_df['Week'] == int(report_week)) & | |
(st.session_state.heights_df['Farm_ID'].isin(day_df[day_df['Day'] == report_day]['Farm_ID'])) | |
] | |
if not report_df.empty: | |
st.markdown(f"### گزارش هفته {report_week} - روز {report_day}") | |
st.dataframe(report_df, use_container_width=True) | |
csv = report_df.to_csv(index=False).encode('utf-8') | |
st.download_button( | |
label="دانلود گزارش (CSV)", | |
data=csv, | |
file_name=f"report_week_{report_week}_day_{report_day}.csv", | |
mime="text/csv", | |
) | |
st_lottie(lottie_report, height=200, key="report_animation") | |
else: | |
st.warning(f"دادهای برای هفته {report_week} و روز {report_day} یافت نشد.") | |
# Settings Page | |
elif selected == "تنظیمات": | |
st.markdown("## تنظیمات سامانه") | |
st.markdown(""" | |
<div class="glass-card"> | |
<h3 class="gradient-text">تنظیمات پیشرفته</h3> | |
<p>در این بخش میتوانید تنظیمات کلی سامانه، از جمله بهروزرسانی دادهها و پیکربندیهای پیشرفته را مدیریت کنید.</p> | |
</div> | |
""", unsafe_allow_html=True) | |
st.markdown("### بهروزرسانی دادهها") | |
if st.button("بارگذاری مجدد دادهها", type="primary", use_container_width=True): | |
st.session_state.heights_df = load_farm_data() | |
st.success("دادهها با موفقیت بهروزرسانی شدند.") | |
st.markdown("### تنظیمات ظاهری") | |
theme = st.radio( | |
"انتخاب تم", | |
options=["سبز (پیشفرض)", "آبی", "سفید"], | |
format_func=lambda x: x | |
) | |
if theme == "آبی": | |
st.markdown(""" | |
<style> | |
.main-header {background: linear-gradient(90deg, #1976d2 0%, #0d47a1 100%);} | |
.metric-card .metric-value {color: #1976d2;} | |
.stButton>button {background: linear-gradient(90deg, #1976d2 0%, #0d47a1 100%);} | |
.stProgress > div > div > div > div {background-color: #1976d2;} | |
</style> | |
""", unsafe_allow_html=True) | |
elif theme == "سفید": | |
st.markdown(""" | |
<style> | |
.main-header {background: linear-gradient(90deg, #ffffff 0%, #f5f5f5 100%);} | |
.metric-card .metric-value {color: #333333;} | |
.stButton>button {background: linear-gradient(90deg, #ffffff 0%, #f5f5f5 100%); color: #333333;} | |
.stProgress > div > div > div > div {background-color: #333333;} | |
</style> | |
""", unsafe_allow_html=True) | |
st.markdown("### اطلاعات تماس") | |
st.markdown(""" | |
<div class="neumorphic-card"> | |
<p>برای پشتیبانی یا مشکلات فنی، با ما تماس بگیرید:</p> | |
<p>ایمیل: [email protected]</p> | |
<p>تلفن: +98 21 12345678</p> | |
</div> | |
""", unsafe_allow_html=True) | |
# Footer | |
st.markdown(""" | |
<footer> | |
<p>© 2025 سامانه هوشمند پایش مزارع نیشکر دهخدا. تمامی حقوق محفوظ است.</p> | |
</footer> | |
""", unsafe_allow_html=True) |