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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import plotly.graph_objects as go
|
| 3 |
+
from pymongo import MongoClient
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 7 |
+
import certifi
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
mongo_uri = "mongodb+srv://Agripredict:TjXSvMhOis49qH8E@cluster0.gek7n.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
|
| 12 |
+
|
| 13 |
+
if not mongo_uri:
|
| 14 |
+
st.error("MongoDB URI is not set!")
|
| 15 |
+
st.stop()
|
| 16 |
+
else:
|
| 17 |
+
# Connect to MongoDB with SSL certificate validation
|
| 18 |
+
client = MongoClient(mongo_uri, tlsCAFile=certifi.where())
|
| 19 |
+
db = client["AgriPredict"]
|
| 20 |
+
collection = db["WhiteSesame"]
|
| 21 |
+
|
| 22 |
+
# CSS to increase the width of the container
|
| 23 |
+
st.markdown("""
|
| 24 |
+
<style>
|
| 25 |
+
/* Adjust the width of the main container */
|
| 26 |
+
.main {
|
| 27 |
+
max-width: 1200px; /* Increase the width */
|
| 28 |
+
margin: 0 auto; /* Center the container */
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
/* Main background */
|
| 32 |
+
body {
|
| 33 |
+
background-color: #f9f9f9;
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
/* Title styling */
|
| 37 |
+
h1 {
|
| 38 |
+
color: #4CAF50;
|
| 39 |
+
font-family: 'Arial Black', sans-serif;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/* Buttons */
|
| 43 |
+
.stButton>button {
|
| 44 |
+
background-color: #4CAF50;
|
| 45 |
+
color: white;
|
| 46 |
+
font-size: 14px;
|
| 47 |
+
border-radius: 8px;
|
| 48 |
+
padding: 10px 20px;
|
| 49 |
+
margin: 5px;
|
| 50 |
+
white-space: nowrap;
|
| 51 |
+
}
|
| 52 |
+
.stButton>button:hover {
|
| 53 |
+
background-color: #45a049;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
/* Selectbox styling */
|
| 57 |
+
.stSelectbox>div {
|
| 58 |
+
padding: 10px;
|
| 59 |
+
background-color: #ffffff;
|
| 60 |
+
border: 1px solid #e6e6e6;
|
| 61 |
+
border-radius: 8px;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/* Checkbox styling */
|
| 65 |
+
.stCheckbox>label {
|
| 66 |
+
font-size: 14px;
|
| 67 |
+
color: #555;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
/* Containers */
|
| 71 |
+
.stContainer {
|
| 72 |
+
border-radius: 12px;
|
| 73 |
+
padding: 20px;
|
| 74 |
+
background-color: #ffffff;
|
| 75 |
+
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
/* Chart area */
|
| 79 |
+
.plotly-graph-div {
|
| 80 |
+
border-radius: 12px;
|
| 81 |
+
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
/* Footer */
|
| 85 |
+
footer {
|
| 86 |
+
font-size: 12px;
|
| 87 |
+
text-align: center;
|
| 88 |
+
color: #888;
|
| 89 |
+
padding: 10px;
|
| 90 |
+
}
|
| 91 |
+
</style>
|
| 92 |
+
""", unsafe_allow_html=True)
|
| 93 |
+
|
| 94 |
+
st.title("🌾 AgriPredict Dashboard")
|
| 95 |
+
|
| 96 |
+
# Load the state-market dictionary from the JSON file
|
| 97 |
+
with open('all_state_market_dict.json', 'r') as file:
|
| 98 |
+
state_market_dict = json.load(file)
|
| 99 |
+
|
| 100 |
+
# UI for Dashboard
|
| 101 |
+
with st.container():
|
| 102 |
+
with st.expander("AgriPredict Dashboard", expanded=True):
|
| 103 |
+
# Adjust the columns to fit more elements within the container
|
| 104 |
+
col1, col2, col3, col4, col5, col6, col7 = st.columns([1.5, 1.5, 1.5, 1.5, 1.5, 3, 3])
|
| 105 |
+
|
| 106 |
+
# Buttons for periods
|
| 107 |
+
with col1:
|
| 108 |
+
if st.button('2W', key='2_weeks'):
|
| 109 |
+
st.session_state.selected_period = 14
|
| 110 |
+
|
| 111 |
+
with col2:
|
| 112 |
+
if st.button('1M', key='1_month'):
|
| 113 |
+
st.session_state.selected_period = 30
|
| 114 |
+
|
| 115 |
+
with col3:
|
| 116 |
+
if st.button('3M', key='3_months'):
|
| 117 |
+
st.session_state.selected_period = 90
|
| 118 |
+
|
| 119 |
+
with col4:
|
| 120 |
+
if st.button('1Y', key='1_year'):
|
| 121 |
+
st.session_state.selected_period = 365
|
| 122 |
+
|
| 123 |
+
with col5:
|
| 124 |
+
if st.button('5Y', key='5_year'):
|
| 125 |
+
st.session_state.selected_period = 1825
|
| 126 |
+
|
| 127 |
+
# Dropdown for states
|
| 128 |
+
with col6:
|
| 129 |
+
states = list(state_market_dict.keys())
|
| 130 |
+
selected_state = st.selectbox(
|
| 131 |
+
"Choose a state",
|
| 132 |
+
states,
|
| 133 |
+
key="state_selectbox",
|
| 134 |
+
index=0
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# Dropdown for selecting between Price, Volume, or Both
|
| 138 |
+
with col7:
|
| 139 |
+
data_type = st.selectbox(
|
| 140 |
+
"Select Data Type",
|
| 141 |
+
["Price", "Volume", "Both"]
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# Checkbox for market-wise analysis
|
| 145 |
+
st.write("")
|
| 146 |
+
with st.container():
|
| 147 |
+
market_wise = st.checkbox("Market wise", key="market_checkbox")
|
| 148 |
+
|
| 149 |
+
if market_wise:
|
| 150 |
+
# Get markets for the selected state
|
| 151 |
+
markets = state_market_dict.get(selected_state, [])
|
| 152 |
+
selected_market = st.selectbox(
|
| 153 |
+
"Choose a market",
|
| 154 |
+
markets,
|
| 155 |
+
key="market_selectbox",
|
| 156 |
+
index=0
|
| 157 |
+
)
|
| 158 |
+
query_filter = {"state": selected_state, "Market Name": selected_market}
|
| 159 |
+
else:
|
| 160 |
+
query_filter = {"state": selected_state}
|
| 161 |
+
|
| 162 |
+
# Add date filtering based on selected period
|
| 163 |
+
if 'selected_period' in st.session_state:
|
| 164 |
+
days_period = st.session_state.selected_period
|
| 165 |
+
query_filter["Reported Date"] = {
|
| 166 |
+
"$gte": datetime.now() - timedelta(days=days_period)
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
# Fetch data from MongoDB
|
| 170 |
+
try:
|
| 171 |
+
cursor = collection.find(query_filter)
|
| 172 |
+
data = list(cursor)
|
| 173 |
+
|
| 174 |
+
if data:
|
| 175 |
+
# Convert MongoDB data to a DataFrame
|
| 176 |
+
df = pd.DataFrame(data)
|
| 177 |
+
df['Reported Date'] = pd.to_datetime(df['Reported Date'])
|
| 178 |
+
|
| 179 |
+
# Group by Reported Date
|
| 180 |
+
df_grouped = (
|
| 181 |
+
df.groupby('Reported Date', as_index=False)
|
| 182 |
+
.agg({
|
| 183 |
+
'Arrivals (Tonnes)': 'sum',
|
| 184 |
+
'Modal Price (Rs./Quintal)': 'mean'
|
| 185 |
+
})
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# Create a complete date range
|
| 189 |
+
date_range = pd.date_range(
|
| 190 |
+
start=df_grouped['Reported Date'].min(),
|
| 191 |
+
end=df_grouped['Reported Date'].max()
|
| 192 |
+
)
|
| 193 |
+
df_grouped = df_grouped.set_index('Reported Date').reindex(date_range).rename_axis('Reported Date').reset_index()
|
| 194 |
+
|
| 195 |
+
# Fill missing values
|
| 196 |
+
df_grouped['Arrivals (Tonnes)'] = df_grouped['Arrivals (Tonnes)'].fillna(
|
| 197 |
+
method='ffill').fillna(method='bfill')
|
| 198 |
+
df_grouped['Modal Price (Rs./Quintal)'] = df_grouped['Modal Price (Rs./Quintal)'].fillna(
|
| 199 |
+
method='ffill').fillna(method='bfill')
|
| 200 |
+
|
| 201 |
+
st.subheader(f"📈 Trend Graph for {selected_state} ({'Market: ' + selected_market if market_wise else 'State'})")
|
| 202 |
+
|
| 203 |
+
if data_type == "Both":
|
| 204 |
+
# Min-Max Scaling
|
| 205 |
+
scaler = MinMaxScaler()
|
| 206 |
+
df_grouped[['Scaled Price', 'Scaled Arrivals']] = scaler.fit_transform(
|
| 207 |
+
df_grouped[['Modal Price (Rs./Quintal)', 'Arrivals (Tonnes)']]
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
fig = go.Figure()
|
| 211 |
+
|
| 212 |
+
# Plot Scaled Price with actual values on hover
|
| 213 |
+
fig.add_trace(go.Scatter(
|
| 214 |
+
x=df_grouped['Reported Date'],
|
| 215 |
+
y=df_grouped['Scaled Price'],
|
| 216 |
+
mode='lines',
|
| 217 |
+
name='Scaled Price',
|
| 218 |
+
line=dict(width=1, color='green'),
|
| 219 |
+
text=df_grouped['Modal Price (Rs./Quintal)'], # Actual Modal Price values
|
| 220 |
+
hovertemplate='Date: %{x}<br>Scaled Price: %{y:.2f}<br>Actual Price: %{text:.2f}<extra></extra>'
|
| 221 |
+
))
|
| 222 |
+
|
| 223 |
+
# Plot Scaled Arrivals with actual values on hover
|
| 224 |
+
fig.add_trace(go.Scatter(
|
| 225 |
+
x=df_grouped['Reported Date'],
|
| 226 |
+
y=df_grouped['Scaled Arrivals'],
|
| 227 |
+
mode='lines',
|
| 228 |
+
name='Scaled Arrivals',
|
| 229 |
+
line=dict(width=1, color='blue'),
|
| 230 |
+
text=df_grouped['Arrivals (Tonnes)'], # Actual Arrivals values
|
| 231 |
+
hovertemplate='Date: %{x}<br>Scaled Arrivals: %{y:.2f}<br>Actual Arrivals: %{text:.2f}<extra></extra>'
|
| 232 |
+
))
|
| 233 |
+
|
| 234 |
+
fig.update_layout(
|
| 235 |
+
title="Price and Arrivals Trend",
|
| 236 |
+
xaxis_title='Date',
|
| 237 |
+
yaxis_title='Scaled Values',
|
| 238 |
+
template='plotly_white'
|
| 239 |
+
)
|
| 240 |
+
st.plotly_chart(fig)
|
| 241 |
+
|
| 242 |
+
elif data_type == "Price":
|
| 243 |
+
# Plot Modal Price
|
| 244 |
+
fig = go.Figure()
|
| 245 |
+
fig.add_trace(go.Scatter(
|
| 246 |
+
x=df_grouped['Reported Date'],
|
| 247 |
+
y=df_grouped['Modal Price (Rs./Quintal)'],
|
| 248 |
+
mode='lines',
|
| 249 |
+
name='Modal Price',
|
| 250 |
+
line=dict(width=1, color='green')
|
| 251 |
+
))
|
| 252 |
+
fig.update_layout(title="Modal Price Trend", xaxis_title='Date', yaxis_title='Price', template='plotly_white')
|
| 253 |
+
st.plotly_chart(fig)
|
| 254 |
+
|
| 255 |
+
elif data_type == "Volume":
|
| 256 |
+
# Plot Arrivals (Tonnes)
|
| 257 |
+
fig = go.Figure()
|
| 258 |
+
fig.add_trace(go.Scatter(
|
| 259 |
+
x=df_grouped['Reported Date'],
|
| 260 |
+
y=df_grouped['Arrivals (Tonnes)'],
|
| 261 |
+
mode='lines',
|
| 262 |
+
name='Arrivals',
|
| 263 |
+
line=dict(width=1, color='blue')
|
| 264 |
+
))
|
| 265 |
+
fig.update_layout(title="Arrivals Trend", xaxis_title='Date', yaxis_title='Volume', template='plotly_white')
|
| 266 |
+
st.plotly_chart(fig)
|
| 267 |
+
|
| 268 |
+
else:
|
| 269 |
+
st.warning("⚠️ No relevant data found for the selected options.")
|
| 270 |
+
else:
|
| 271 |
+
st.warning("⚠️ No data found for the selected filters.")
|
| 272 |
+
|
| 273 |
+
except Exception as e:
|
| 274 |
+
st.error(f"❌ Error fetching data: {e}")
|