Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -35,6 +35,7 @@ else:
|
|
| 35 |
best_params_collection_3m = db["BestParams_3m"]
|
| 36 |
impExp = db["impExp"]
|
| 37 |
users_collection = db["user"]
|
|
|
|
| 38 |
|
| 39 |
state_market_dict = {
|
| 40 |
"Karnataka": [
|
|
@@ -691,7 +692,7 @@ def forecast_next_14_days(df, _best_params, key):
|
|
| 691 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 692 |
|
| 693 |
# Pass model to plot_data
|
| 694 |
-
plot_data(original_df, future_df, last_date,
|
| 695 |
download_button(future_df, key)
|
| 696 |
|
| 697 |
def forecast_next_30_days(df, _best_params, key):
|
|
@@ -717,7 +718,7 @@ def forecast_next_30_days(df, _best_params, key):
|
|
| 717 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 718 |
|
| 719 |
# Pass model to plot_data
|
| 720 |
-
plot_data(original_df, future_df, last_date,
|
| 721 |
download_button(future_df, key)
|
| 722 |
|
| 723 |
def forecast_next_90_days(df, _best_params, key):
|
|
@@ -743,30 +744,48 @@ def forecast_next_90_days(df, _best_params, key):
|
|
| 743 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 744 |
|
| 745 |
# Pass model to plot_data
|
| 746 |
-
plot_data(original_df, future_df, last_date,
|
| 747 |
download_button(future_df, key)
|
| 748 |
|
| 749 |
-
def plot_data(original_df, future_df, last_date,
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
future_plot_df = future_df[['Reported Date', 'Modal Price (Rs./Quintal)']].copy()
|
| 757 |
future_plot_df['Type'] = 'Forecasted'
|
| 758 |
-
|
| 759 |
-
|
|
|
|
|
|
|
| 760 |
future_plot_df = pd.concat([last_actual_point, future_plot_df])
|
| 761 |
-
|
| 762 |
-
|
|
|
|
|
|
|
|
|
|
| 763 |
fig = go.Figure()
|
| 764 |
for plot_type, color, dash in [('Actual', 'blue', 'solid'), ('Forecasted', 'red', 'dash')]:
|
| 765 |
data = plot_df[plot_df['Type'] == plot_type]
|
| 766 |
-
fig.add_trace(go.Scatter(
|
| 767 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
st.plotly_chart(fig, use_container_width=True)
|
| 769 |
|
|
|
|
| 770 |
def download_button(future_df, key):
|
| 771 |
# Create a new DataFrame with only 'Reported Date' and 'Modal Price (Rs./Quintal)'
|
| 772 |
download_df = future_df[['Reported Date', 'Modal Price (Rs./Quintal)']].copy()
|
|
@@ -787,7 +806,7 @@ def download_button(future_df, key):
|
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
-
def fetch_and_process_data(query_filter):
|
| 791 |
try:
|
| 792 |
cursor = collection.find(query_filter)
|
| 793 |
data = list(cursor)
|
|
@@ -800,7 +819,7 @@ def fetch_and_process_data(query_filter):
|
|
| 800 |
st.warning("⚠️ No data found for the selected filter.")
|
| 801 |
return None
|
| 802 |
except Exception as e:
|
| 803 |
-
st.error(f"❌ Error fetching data: {e}")
|
| 804 |
return None
|
| 805 |
|
| 806 |
def save_best_params(collection, filter_key, best_params):
|
|
@@ -1056,7 +1075,11 @@ def fetch_and_store_data():
|
|
| 1056 |
from_date = "01 Jan 2000"
|
| 1057 |
|
| 1058 |
to_date = (datetime.now() - timedelta(days=1)).strftime('%d %b %Y')
|
| 1059 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1060 |
# Build the URL to be requested
|
| 1061 |
base_url = "https://agmarknet.gov.in/SearchCmmMkt.aspx"
|
| 1062 |
params = {
|
|
@@ -1088,15 +1111,10 @@ def fetch_and_store_data():
|
|
| 1088 |
if response.status_code == 200:
|
| 1089 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 1090 |
table = soup.find("table", {"class": "tableagmark_new"})
|
| 1091 |
-
|
| 1092 |
if table:
|
| 1093 |
headers = [th.get_text(strip=True) for th in table.find_all("th")]
|
| 1094 |
-
rows = []
|
| 1095 |
-
|
| 1096 |
-
for row in table.find_all("tr")[1:]:
|
| 1097 |
-
cells = [td.get_text(strip=True) for td in row.find_all("td")]
|
| 1098 |
-
if cells:
|
| 1099 |
-
rows.append(cells)
|
| 1100 |
|
| 1101 |
df = pd.DataFrame(rows, columns=headers)
|
| 1102 |
df = df[df['Variety']=="White"]
|
|
@@ -1110,11 +1128,98 @@ def fetch_and_store_data():
|
|
| 1110 |
df["Arrivals (Tonnes)"] = pd.to_numeric(df["Arrivals (Tonnes)"], errors='coerce').astype("float64")
|
| 1111 |
df["state"] = df["state"].astype("string")
|
| 1112 |
df["Market Name"] = df["Market Name"].astype("string")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1113 |
|
| 1114 |
-
|
| 1115 |
-
|
| 1116 |
-
|
| 1117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1118 |
return df
|
| 1119 |
|
| 1120 |
else:
|
|
@@ -1124,13 +1229,8 @@ def fetch_and_store_data():
|
|
| 1124 |
|
| 1125 |
|
| 1126 |
def get_dataframe_from_collection(collection):
|
| 1127 |
-
# Fetch all documents from the collection
|
| 1128 |
data = list(collection.find())
|
| 1129 |
-
|
| 1130 |
-
# Convert the list of documents into a DataFrame
|
| 1131 |
df = pd.DataFrame(data)
|
| 1132 |
-
|
| 1133 |
-
# Drop the MongoDB-specific '_id' column (optional, if not needed)
|
| 1134 |
if "_id" in df.columns:
|
| 1135 |
df = df.drop(columns=["_id"])
|
| 1136 |
|
|
@@ -1142,7 +1242,6 @@ def authenticate_user(username, password):
|
|
| 1142 |
return True
|
| 1143 |
return False
|
| 1144 |
|
| 1145 |
-
# CSS for responsive and professional design
|
| 1146 |
st.markdown("""
|
| 1147 |
<style>
|
| 1148 |
/* Main layout adjustments */
|
|
@@ -1222,6 +1321,7 @@ if st.session_state.authenticated:
|
|
| 1222 |
st.title("🌾 AgriPredict Dashboard")
|
| 1223 |
if st.button("Get Live Data Feed"):
|
| 1224 |
fetch_and_store_data()
|
|
|
|
| 1225 |
# Top-level radio buttons for switching views
|
| 1226 |
view_mode = st.radio("", ["Statistics", "Plots", "Predictions", "Exim"], horizontal=True)
|
| 1227 |
|
|
@@ -1252,7 +1352,7 @@ if st.session_state.authenticated:
|
|
| 1252 |
if market_wise:
|
| 1253 |
markets = state_market_dict.get(selected_state, [])
|
| 1254 |
selected_market = st.sidebar.selectbox("Select Market", markets)
|
| 1255 |
-
query_filter = {"
|
| 1256 |
else:
|
| 1257 |
query_filter = {"state": selected_state}
|
| 1258 |
else:
|
|
@@ -1271,8 +1371,23 @@ if st.session_state.authenticated:
|
|
| 1271 |
|
| 1272 |
# Submit button to trigger the query and plot
|
| 1273 |
if st.sidebar.button("✨ Let's go!"):
|
| 1274 |
-
# Fetch data from MongoDB
|
| 1275 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1276 |
cursor = collection.find(query_filter)
|
| 1277 |
data = list(cursor)
|
| 1278 |
|
|
@@ -1313,16 +1428,20 @@ if st.session_state.authenticated:
|
|
| 1313 |
df_grouped[['Scaled Price', 'Scaled Arrivals']] = scaler.fit_transform(
|
| 1314 |
df_grouped[['Modal Price (Rs./Quintal)', 'Arrivals (Tonnes)']]
|
| 1315 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
|
| 1317 |
fig = go.Figure()
|
| 1318 |
|
| 1319 |
fig.add_trace(go.Scatter(
|
| 1320 |
-
x=
|
| 1321 |
-
y=
|
| 1322 |
mode='lines',
|
| 1323 |
name='Scaled Price',
|
| 1324 |
line=dict(width=1, color='green'),
|
| 1325 |
-
text=
|
| 1326 |
hovertemplate='Date: %{x}<br>Scaled Price: %{y:.2f}<br>Actual Price: %{text:.2f}<extra></extra>'
|
| 1327 |
))
|
| 1328 |
|
|
@@ -1346,16 +1465,28 @@ if st.session_state.authenticated:
|
|
| 1346 |
|
| 1347 |
elif data_type == "Price":
|
| 1348 |
# Plot Modal Price
|
| 1349 |
-
|
| 1350 |
-
|
| 1351 |
-
|
| 1352 |
-
|
| 1353 |
-
|
| 1354 |
-
|
| 1355 |
-
|
| 1356 |
-
|
| 1357 |
-
|
| 1358 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1359 |
|
| 1360 |
elif data_type == "Volume":
|
| 1361 |
# Plot Arrivals (Tonnes)
|
|
@@ -1374,7 +1505,7 @@ if st.session_state.authenticated:
|
|
| 1374 |
st.warning("⚠️ No data found for the selected filters.")
|
| 1375 |
|
| 1376 |
except Exception as e:
|
| 1377 |
-
st.error(f"❌ Error fetching data: {e}")
|
| 1378 |
elif view_mode == "Predictions":
|
| 1379 |
st.subheader("📊 Model Analysis")
|
| 1380 |
sub_option = st.radio("Select one of the following", ["India", "States", "Market"], horizontal=True)
|
|
@@ -1386,7 +1517,7 @@ if st.session_state.authenticated:
|
|
| 1386 |
|
| 1387 |
if st.button("Forecast"):
|
| 1388 |
query_filter = {"state": selected_state}
|
| 1389 |
-
df = fetch_and_process_data(query_filter)
|
| 1390 |
if sub_timeline == "14 days":
|
| 1391 |
forecast(df, filter_key, 14)
|
| 1392 |
elif sub_timeline == "1 month":
|
|
@@ -1399,7 +1530,9 @@ if st.session_state.authenticated:
|
|
| 1399 |
filter_key = f"market_{selected_market}" # Unique key for each market
|
| 1400 |
if st.button("Forecast"):
|
| 1401 |
query_filter = {"Market Name": selected_market}
|
| 1402 |
-
|
|
|
|
|
|
|
| 1403 |
if sub_timeline == "14 days":
|
| 1404 |
forecast(df, filter_key, 14)
|
| 1405 |
elif sub_timeline == "1 month":
|
|
@@ -1412,7 +1545,7 @@ if st.session_state.authenticated:
|
|
| 1412 |
if True:
|
| 1413 |
if st.button("Forecast"):
|
| 1414 |
query_filter = {}
|
| 1415 |
-
df = fetch_and_process_data(query_filter)
|
| 1416 |
if sub_timeline == "14 days":
|
| 1417 |
forecast(df, "India", 14)
|
| 1418 |
elif sub_timeline == "1 month":
|
|
@@ -1422,9 +1555,7 @@ if st.session_state.authenticated:
|
|
| 1422 |
|
| 1423 |
elif view_mode=="Statistics":
|
| 1424 |
document = collection.find_one()
|
| 1425 |
-
print(document)
|
| 1426 |
df = get_dataframe_from_collection(collection)
|
| 1427 |
-
print(df)
|
| 1428 |
display_statistics(df)
|
| 1429 |
elif view_mode == "Exim":
|
| 1430 |
df = collection_to_dataframe(impExp)
|
|
|
|
| 35 |
best_params_collection_3m = db["BestParams_3m"]
|
| 36 |
impExp = db["impExp"]
|
| 37 |
users_collection = db["user"]
|
| 38 |
+
market_price_data = db["new_data_price"]
|
| 39 |
|
| 40 |
state_market_dict = {
|
| 41 |
"Karnataka": [
|
|
|
|
| 692 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 693 |
|
| 694 |
# Pass model to plot_data
|
| 695 |
+
plot_data(original_df, future_df, last_date, 14)
|
| 696 |
download_button(future_df, key)
|
| 697 |
|
| 698 |
def forecast_next_30_days(df, _best_params, key):
|
|
|
|
| 718 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 719 |
|
| 720 |
# Pass model to plot_data
|
| 721 |
+
plot_data(original_df, future_df, last_date, 30)
|
| 722 |
download_button(future_df, key)
|
| 723 |
|
| 724 |
def forecast_next_90_days(df, _best_params, key):
|
|
|
|
| 744 |
future_df['Modal Price (Rs./Quintal)'] = future_predictions
|
| 745 |
|
| 746 |
# Pass model to plot_data
|
| 747 |
+
plot_data(original_df, future_df, last_date, 90)
|
| 748 |
download_button(future_df, key)
|
| 749 |
|
| 750 |
+
def plot_data(original_df, future_df, last_date, days):
|
| 751 |
+
# Filter original_df for the period you want to plot.
|
| 752 |
+
actual_df = original_df[original_df['Reported Date'] >= (last_date - pd.Timedelta(days=days))].copy()
|
| 753 |
+
actual_df['Type'] = 'Actual'
|
| 754 |
+
|
| 755 |
+
# Prepare the future_df (predicted data) and mark it as forecasted.
|
|
|
|
| 756 |
future_plot_df = future_df[['Reported Date', 'Modal Price (Rs./Quintal)']].copy()
|
| 757 |
future_plot_df['Type'] = 'Forecasted'
|
| 758 |
+
|
| 759 |
+
# Get the last actual data point from actual_df.
|
| 760 |
+
# Ensure the DataFrame is sorted by date.
|
| 761 |
+
last_actual_point = actual_df.sort_values('Reported Date').iloc[[-1]].copy()
|
| 762 |
future_plot_df = pd.concat([last_actual_point, future_plot_df])
|
| 763 |
+
|
| 764 |
+
# Combine both actual and forecasted data for plotting.
|
| 765 |
+
plot_df = pd.concat([actual_df, future_plot_df])
|
| 766 |
+
|
| 767 |
+
# Create the plot.
|
| 768 |
fig = go.Figure()
|
| 769 |
for plot_type, color, dash in [('Actual', 'blue', 'solid'), ('Forecasted', 'red', 'dash')]:
|
| 770 |
data = plot_df[plot_df['Type'] == plot_type]
|
| 771 |
+
fig.add_trace(go.Scatter(
|
| 772 |
+
x=data['Reported Date'],
|
| 773 |
+
y=data['Modal Price (Rs./Quintal)'],
|
| 774 |
+
mode='lines',
|
| 775 |
+
name=f"{plot_type} Data",
|
| 776 |
+
line=dict(color=color, dash=dash)
|
| 777 |
+
))
|
| 778 |
+
|
| 779 |
+
fig.update_layout(
|
| 780 |
+
title="Actual vs Forecasted Modal Price (Rs./Quintal)",
|
| 781 |
+
xaxis_title="Date",
|
| 782 |
+
yaxis_title="Modal Price (Rs./Quintal)",
|
| 783 |
+
template="plotly_white"
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
st.plotly_chart(fig, use_container_width=True)
|
| 787 |
|
| 788 |
+
|
| 789 |
def download_button(future_df, key):
|
| 790 |
# Create a new DataFrame with only 'Reported Date' and 'Modal Price (Rs./Quintal)'
|
| 791 |
download_df = future_df[['Reported Date', 'Modal Price (Rs./Quintal)']].copy()
|
|
|
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
+
def fetch_and_process_data(query_filter, collection):
|
| 810 |
try:
|
| 811 |
cursor = collection.find(query_filter)
|
| 812 |
data = list(cursor)
|
|
|
|
| 819 |
st.warning("⚠️ No data found for the selected filter.")
|
| 820 |
return None
|
| 821 |
except Exception as e:
|
| 822 |
+
st.error(f"❌ Error fetching data 1: {e}")
|
| 823 |
return None
|
| 824 |
|
| 825 |
def save_best_params(collection, filter_key, best_params):
|
|
|
|
| 1075 |
from_date = "01 Jan 2000"
|
| 1076 |
|
| 1077 |
to_date = (datetime.now() - timedelta(days=1)).strftime('%d %b %Y')
|
| 1078 |
+
from_date_obj = datetime.strptime(from_date, '%d %b %Y')
|
| 1079 |
+
to_date_obj = datetime.strptime(to_date, '%d %b %Y')
|
| 1080 |
+
if to_date_obj < from_date_obj:
|
| 1081 |
+
print("Data already scraped")
|
| 1082 |
+
return None
|
| 1083 |
# Build the URL to be requested
|
| 1084 |
base_url = "https://agmarknet.gov.in/SearchCmmMkt.aspx"
|
| 1085 |
params = {
|
|
|
|
| 1111 |
if response.status_code == 200:
|
| 1112 |
soup = BeautifulSoup(response.content, 'html.parser')
|
| 1113 |
table = soup.find("table", {"class": "tableagmark_new"})
|
| 1114 |
+
st.write(soup.prettify())
|
| 1115 |
if table:
|
| 1116 |
headers = [th.get_text(strip=True) for th in table.find_all("th")]
|
| 1117 |
+
rows = [[td.get_text(strip=True) for td in row.find_all("td")] for row in table.find_all("tr")[1:]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1118 |
|
| 1119 |
df = pd.DataFrame(rows, columns=headers)
|
| 1120 |
df = df[df['Variety']=="White"]
|
|
|
|
| 1128 |
df["Arrivals (Tonnes)"] = pd.to_numeric(df["Arrivals (Tonnes)"], errors='coerce').astype("float64")
|
| 1129 |
df["state"] = df["state"].astype("string")
|
| 1130 |
df["Market Name"] = df["Market Name"].astype("string")
|
| 1131 |
+
records = df.to_dict(orient="records")
|
| 1132 |
+
if records:
|
| 1133 |
+
collection.insert_many(records)
|
| 1134 |
+
print(f"Inserted {len(records)} new records into MongoDB.")
|
| 1135 |
+
else:
|
| 1136 |
+
print("No new records to insert.")
|
| 1137 |
+
|
| 1138 |
+
return df
|
| 1139 |
+
|
| 1140 |
+
else:
|
| 1141 |
+
print(f"Failed to fetch data with status code: {response.status_code}")
|
| 1142 |
+
return None
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
def fetch_and_store_data_market():
|
| 1146 |
+
latest_doc = market_price_data.find_one(sort=[("Reported Date", -1)])
|
| 1147 |
+
if latest_doc and "Reported Date" in latest_doc:
|
| 1148 |
+
latest_date = latest_doc["Reported Date"]
|
| 1149 |
+
else:
|
| 1150 |
+
latest_date = None
|
| 1151 |
+
|
| 1152 |
+
if latest_date:
|
| 1153 |
+
from_date = (latest_date + timedelta(days=1)).strftime('%d %b %Y')
|
| 1154 |
+
else:
|
| 1155 |
+
# If no latest date, set a default from_date
|
| 1156 |
+
from_date = "01 Jan 2000"
|
| 1157 |
+
|
| 1158 |
+
to_date = (datetime.now() - timedelta(days=1)).strftime('%d %b %Y')
|
| 1159 |
+
from_date_obj = datetime.strptime(from_date, '%d %b %Y')
|
| 1160 |
+
to_date_obj = datetime.strptime(to_date, '%d %b %Y')
|
| 1161 |
+
if to_date_obj < from_date_obj:
|
| 1162 |
+
print("Data already scraped")
|
| 1163 |
+
return None
|
| 1164 |
+
# Build the URL to be requested
|
| 1165 |
+
base_url = "https://agmarknet.gov.in/SearchCmmMkt.aspx"
|
| 1166 |
+
params = {
|
| 1167 |
+
"Tx_Commodity": "11",
|
| 1168 |
+
"Tx_State": "0",
|
| 1169 |
+
"Tx_District": "0",
|
| 1170 |
+
"Tx_Market": "0",
|
| 1171 |
+
"DateFrom": from_date,
|
| 1172 |
+
"DateTo": to_date,
|
| 1173 |
+
"Fr_Date": from_date,
|
| 1174 |
+
"To_Date": to_date,
|
| 1175 |
+
"Tx_Trend": "0",
|
| 1176 |
+
"Tx_CommodityHead": "Sesamum(Sesame,Gingelly,Til)",
|
| 1177 |
+
"Tx_StateHead": "--Select--",
|
| 1178 |
+
"Tx_DistrictHead": "--Select--",
|
| 1179 |
+
"Tx_MarketHead": "--Select--"
|
| 1180 |
+
}
|
| 1181 |
+
|
| 1182 |
+
full_url = f"{base_url}?{'&'.join(f'{k}={v}' for k, v in params.items())}"
|
| 1183 |
+
api_url = "https://api.scraperapi.com"
|
| 1184 |
+
api_key = "bbbbde6b56c0fde1e2a61c914eb22d14"
|
| 1185 |
+
scraperapi_params = {
|
| 1186 |
+
'api_key': api_key,
|
| 1187 |
+
'url': full_url
|
| 1188 |
+
}
|
| 1189 |
+
st.write(full_url)
|
| 1190 |
+
|
| 1191 |
+
response = requests.get(api_url, params=scraperapi_params)
|
| 1192 |
+
|
| 1193 |
+
if response.status_code == 200:
|
| 1194 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
| 1195 |
+
table = soup.find("table", {"class": "tableagmark_new"})
|
| 1196 |
|
| 1197 |
+
if table:
|
| 1198 |
+
headers = [th.get_text(strip=True) for th in table.find_all("th")]
|
| 1199 |
+
rows = []
|
| 1200 |
|
| 1201 |
+
for row in table.find_all("tr")[1:]:
|
| 1202 |
+
cells = [td.get_text(strip=True) for td in row.find_all("td")]
|
| 1203 |
+
if cells:
|
| 1204 |
+
rows.append(cells)
|
| 1205 |
+
st.write(rows)
|
| 1206 |
+
st.write(headers)
|
| 1207 |
+
df = pd.DataFrame(rows, columns=headers)
|
| 1208 |
+
df = df[df['Variety']=="White"]
|
| 1209 |
+
df["Price Date"] = pd.to_datetime(df["Price Date"], format='%d %b %Y', errors='coerce')
|
| 1210 |
+
df.dropna(subset=["Price Date"], inplace=True)
|
| 1211 |
+
df.sort_values(by="Price Date", inplace=True)
|
| 1212 |
+
df = df[df["Grade"]=="FAQ"]
|
| 1213 |
+
# Type casting for the columns
|
| 1214 |
+
df["Modal Price (Rs./Quintal)"] = pd.to_numeric(df["Modal Price (Rs./Quintal)"], errors='coerce').astype("int64")
|
| 1215 |
+
df["Market Name"] = df["Market Name"].astype("string")
|
| 1216 |
+
df.rename(columns={"Price Date": "Reported Date"}, inplace=True)
|
| 1217 |
+
records = df.to_dict(orient="records")
|
| 1218 |
+
if records:
|
| 1219 |
+
collection.insert_many(records)
|
| 1220 |
+
print(f"Inserted {len(records)} new records into MongoDB.")
|
| 1221 |
+
else:
|
| 1222 |
+
print("No new records to insert.")
|
| 1223 |
return df
|
| 1224 |
|
| 1225 |
else:
|
|
|
|
| 1229 |
|
| 1230 |
|
| 1231 |
def get_dataframe_from_collection(collection):
|
|
|
|
| 1232 |
data = list(collection.find())
|
|
|
|
|
|
|
| 1233 |
df = pd.DataFrame(data)
|
|
|
|
|
|
|
| 1234 |
if "_id" in df.columns:
|
| 1235 |
df = df.drop(columns=["_id"])
|
| 1236 |
|
|
|
|
| 1242 |
return True
|
| 1243 |
return False
|
| 1244 |
|
|
|
|
| 1245 |
st.markdown("""
|
| 1246 |
<style>
|
| 1247 |
/* Main layout adjustments */
|
|
|
|
| 1321 |
st.title("🌾 AgriPredict Dashboard")
|
| 1322 |
if st.button("Get Live Data Feed"):
|
| 1323 |
fetch_and_store_data()
|
| 1324 |
+
fetch_and_store_data_market()
|
| 1325 |
# Top-level radio buttons for switching views
|
| 1326 |
view_mode = st.radio("", ["Statistics", "Plots", "Predictions", "Exim"], horizontal=True)
|
| 1327 |
|
|
|
|
| 1352 |
if market_wise:
|
| 1353 |
markets = state_market_dict.get(selected_state, [])
|
| 1354 |
selected_market = st.sidebar.selectbox("Select Market", markets)
|
| 1355 |
+
query_filter = {"Market Name": selected_market}
|
| 1356 |
else:
|
| 1357 |
query_filter = {"state": selected_state}
|
| 1358 |
else:
|
|
|
|
| 1371 |
|
| 1372 |
# Submit button to trigger the query and plot
|
| 1373 |
if st.sidebar.button("✨ Let's go!"):
|
|
|
|
| 1374 |
try:
|
| 1375 |
+
df_market_grouped = []
|
| 1376 |
+
if "Market Name" in query_filter:
|
| 1377 |
+
market_cursor = market_price_data.find(query_filter)
|
| 1378 |
+
market_data = list(market_cursor)
|
| 1379 |
+
df_market = pd.DataFrame(market_data)
|
| 1380 |
+
df_market_grouped = df_market.groupby('Reported Date', as_index=False).agg({
|
| 1381 |
+
'Modal Price (Rs./Quintal)': 'mean'
|
| 1382 |
+
})
|
| 1383 |
+
date_range = pd.date_range(
|
| 1384 |
+
start=df_market_grouped['Reported Date'].min(),
|
| 1385 |
+
end=df_market_grouped['Reported Date'].max()
|
| 1386 |
+
)
|
| 1387 |
+
df_market_grouped = df_market_grouped.set_index('Reported Date').reindex(date_range).rename_axis('Reported Date').reset_index()
|
| 1388 |
+
df_market_grouped['Modal Price (Rs./Quintal)'] = df_market_grouped['Modal Price (Rs./Quintal)'].fillna(method='ffill').fillna(method='bfill')
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
cursor = collection.find(query_filter)
|
| 1392 |
data = list(cursor)
|
| 1393 |
|
|
|
|
| 1428 |
df_grouped[['Scaled Price', 'Scaled Arrivals']] = scaler.fit_transform(
|
| 1429 |
df_grouped[['Modal Price (Rs./Quintal)', 'Arrivals (Tonnes)']]
|
| 1430 |
)
|
| 1431 |
+
if market_data!=[]:
|
| 1432 |
+
df_market_grouped['Scaled Price'] = scaler.fit_transform(
|
| 1433 |
+
df_market_grouped[["Modal Price (Rs./Quintal)"]]
|
| 1434 |
+
)
|
| 1435 |
|
| 1436 |
fig = go.Figure()
|
| 1437 |
|
| 1438 |
fig.add_trace(go.Scatter(
|
| 1439 |
+
x=df_market_grouped['Reported Date'],
|
| 1440 |
+
y=df_market_grouped['Scaled Price'],
|
| 1441 |
mode='lines',
|
| 1442 |
name='Scaled Price',
|
| 1443 |
line=dict(width=1, color='green'),
|
| 1444 |
+
text=df_market_grouped['Modal Price (Rs./Quintal)'],
|
| 1445 |
hovertemplate='Date: %{x}<br>Scaled Price: %{y:.2f}<br>Actual Price: %{text:.2f}<extra></extra>'
|
| 1446 |
))
|
| 1447 |
|
|
|
|
| 1465 |
|
| 1466 |
elif data_type == "Price":
|
| 1467 |
# Plot Modal Price
|
| 1468 |
+
if "Market Name" in query_filter:
|
| 1469 |
+
fig = go.Figure()
|
| 1470 |
+
fig.add_trace(go.Scatter(
|
| 1471 |
+
x=df_market_grouped['Reported Date'],
|
| 1472 |
+
y=df_market_grouped['Modal Price (Rs./Quintal)'],
|
| 1473 |
+
mode='lines',
|
| 1474 |
+
name='Modal Price',
|
| 1475 |
+
line=dict(width=1, color='green')
|
| 1476 |
+
))
|
| 1477 |
+
fig.update_layout(title="Modal Price Trend", xaxis_title='Date', yaxis_title='Price (/Quintall)', template='plotly_white')
|
| 1478 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1479 |
+
else:
|
| 1480 |
+
fig = go.Figure()
|
| 1481 |
+
fig.add_trace(go.Scatter(
|
| 1482 |
+
x=df_grouped['Reported Date'],
|
| 1483 |
+
y=df_grouped['Modal Price (Rs./Quintal)'],
|
| 1484 |
+
mode='lines',
|
| 1485 |
+
name='Modal Price',
|
| 1486 |
+
line=dict(width=1, color='green')
|
| 1487 |
+
))
|
| 1488 |
+
fig.update_layout(title="Modal Price Trend", xaxis_title='Date', yaxis_title='Price (/Quintall)', template='plotly_white')
|
| 1489 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1490 |
|
| 1491 |
elif data_type == "Volume":
|
| 1492 |
# Plot Arrivals (Tonnes)
|
|
|
|
| 1505 |
st.warning("⚠️ No data found for the selected filters.")
|
| 1506 |
|
| 1507 |
except Exception as e:
|
| 1508 |
+
st.error(f"❌ Error fetching data 2: {e}")
|
| 1509 |
elif view_mode == "Predictions":
|
| 1510 |
st.subheader("📊 Model Analysis")
|
| 1511 |
sub_option = st.radio("Select one of the following", ["India", "States", "Market"], horizontal=True)
|
|
|
|
| 1517 |
|
| 1518 |
if st.button("Forecast"):
|
| 1519 |
query_filter = {"state": selected_state}
|
| 1520 |
+
df = fetch_and_process_data(query_filter, collection)
|
| 1521 |
if sub_timeline == "14 days":
|
| 1522 |
forecast(df, filter_key, 14)
|
| 1523 |
elif sub_timeline == "1 month":
|
|
|
|
| 1530 |
filter_key = f"market_{selected_market}" # Unique key for each market
|
| 1531 |
if st.button("Forecast"):
|
| 1532 |
query_filter = {"Market Name": selected_market}
|
| 1533 |
+
comparison_date = pd.to_datetime("18 Feb 2025")
|
| 1534 |
+
df = fetch_and_process_data(query_filter, market_price_data)
|
| 1535 |
+
st.write(df[df["Reported Date"]>comparison_date])
|
| 1536 |
if sub_timeline == "14 days":
|
| 1537 |
forecast(df, filter_key, 14)
|
| 1538 |
elif sub_timeline == "1 month":
|
|
|
|
| 1545 |
if True:
|
| 1546 |
if st.button("Forecast"):
|
| 1547 |
query_filter = {}
|
| 1548 |
+
df = fetch_and_process_data(query_filter, collection)
|
| 1549 |
if sub_timeline == "14 days":
|
| 1550 |
forecast(df, "India", 14)
|
| 1551 |
elif sub_timeline == "1 month":
|
|
|
|
| 1555 |
|
| 1556 |
elif view_mode=="Statistics":
|
| 1557 |
document = collection.find_one()
|
|
|
|
| 1558 |
df = get_dataframe_from_collection(collection)
|
|
|
|
| 1559 |
display_statistics(df)
|
| 1560 |
elif view_mode == "Exim":
|
| 1561 |
df = collection_to_dataframe(impExp)
|