BeeBasic commited on
Commit
36de921
·
verified ·
1 Parent(s): da4b5b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -23
app.py CHANGED
@@ -1,32 +1,115 @@
1
  import gradio as gr
2
  import pickle
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- def load_and_display_data():
5
- """Loads the pickled data and formats it for display."""
6
  try:
7
- with open('canteen_surplus_data.pkl', 'rb') as f:
8
- data = pickle.load(f)
9
- # Format the dictionary for better display in Gradio
10
- formatted_output = ""
11
- for canteen_id, info in data.items():
12
- formatted_output += f"Canteen ID: {canteen_id}\n"
13
- formatted_output += f" Canteen Name: {info['canteen_name']}\n"
14
- formatted_output += f" Predicted Surplus: {info['predicted_surplus']}\n"
15
- formatted_output += f" NGO Requirement: {info['ngo_requirement']}\n"
16
- formatted_output += "-" * 20 + "\n"
17
- return formatted_output
18
- except FileNotFoundError:
19
- return "Error: canteen_surplus_data.pkl not found."
20
- except Exception as e:
21
- return f"An error occurred: {e}"
22
-
23
- # Create a Gradio interface to display the data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  iface = gr.Interface(
25
- fn=load_and_display_data,
26
- inputs=None, # No input needed to display the data
 
 
 
 
27
  outputs="text",
28
- title="Canteen Surplus and NGO Requirements",
29
- description="Displays the predicted surplus units and NGO requirements for each canteen."
30
  )
31
 
32
  iface.launch()
 
1
  import gradio as gr
2
  import pickle
3
+ import pandas as pd
4
+ from datetime import datetime
5
+ import joblib # Import joblib
6
+
7
+ # Load the trained model and necessary data structures
8
+ try:
9
+ # Load the trained model
10
+ best_model = joblib.load('best_model.joblib')
11
+
12
+ # Recreate unique_canteen_info and training_columns based on the original data structure
13
+ # In a real deployment, these should be saved during training and loaded here.
14
+ # For this example, we will create dummy data structures based on the assumption of 10 canteens.
15
+ canteen_ids = [f'C00{i+1}' for i in range(10)]
16
+ canteen_names = [
17
+ 'VIT University Main Canteen', 'SRM Campus Canteen', 'Anna University Mess',
18
+ 'IIT Madras Hostel Mess', 'Sangeetha Veg Restaurant', 'Murugan Idli Shop',
19
+ 'Adyar Ananda Bhavan (A2B)', 'The Marina Café', 'Buhari Hotel Canteen',
20
+ 'Crescent College Cafeteria'
21
+ ]
22
+ unique_canteen_info = pd.DataFrame({'canteen_id': canteen_ids, 'canteen_name': canteen_names})
23
+
24
+ # Create a dummy DataFrame with all possible categories to get the column structure for one-hot encoding
25
+ dummy_data_for_cols = pd.DataFrame(columns=['canteen_id', 'canteen_name'])
26
+ for cid in canteen_ids:
27
+ for cname in canteen_names:
28
+ dummy_data_for_cols = pd.concat([dummy_data_for_cols, pd.DataFrame({'canteen_id': [cid], 'canteen_name': [cname]})], ignore_index=True)
29
+
30
+ dummy_encoded_for_cols = pd.get_dummies(dummy_data_for_cols, columns=['canteen_id', 'canteen_name'], drop_first=True)
31
+ training_columns = dummy_encoded_for_cols.columns.tolist()
32
+
33
+
34
+ except FileNotFoundError:
35
+ best_model = None
36
+ unique_canteen_info = None
37
+ training_columns = None
38
+ print("Error: best_model.joblib not found. Model loading failed.")
39
+ except Exception as e:
40
+ best_model = None
41
+ unique_canteen_info = None
42
+ training_columns = None
43
+ print(f"An error occurred during model loading: {e}")
44
+
45
+
46
+ def predict_surplus(day, month, year):
47
+ """Predicts surplus units for all canteens for a given date."""
48
+ if best_model is None or unique_canteen_info is None or training_columns is None:
49
+ return "Model or necessary data not loaded. Cannot make predictions."
50
 
 
 
51
  try:
52
+ prediction_date = datetime(year, month, day)
53
+ except ValueError:
54
+ return "Invalid date provided. Please enter valid day, month, and year."
55
+
56
+ # Create prediction DataFrame
57
+ prediction_df = unique_canteen_info.copy()
58
+ prediction_df['year'] = prediction_date.year
59
+ prediction_df['month'] = prediction_date.month
60
+ prediction_df['day'] = prediction_date.day
61
+ prediction_df['day_of_week'] = prediction_date.weekday() + 1 # Monday is 0, so add 1 to match the original data
62
+ prediction_df['day_of_year'] = prediction_date.timetuple().tm_yday
63
+
64
+ # One-hot encode and align columns with training data
65
+ prediction_encoded = pd.get_dummies(prediction_df, columns=['canteen_id', 'canteen_name'], drop_first=True)
66
+
67
+ for col in training_columns:
68
+ if col not in prediction_encoded.columns:
69
+ prediction_encoded[col] = False
70
+
71
+ # Ensure the order of columns matches the training data features (excluding the target)
72
+ # Recreate the feature columns list based on the training_columns plus the time features
73
+ feature_columns = ['day', 'month', 'year', 'day_of_week', 'day_of_year'] + training_columns
74
+ prediction_encoded = prediction_encoded[feature_columns]
75
+
76
+ # Make predictions
77
+ predicted_surplus_values = best_model.predict(prediction_encoded)
78
+
79
+ # Create a dictionary for output
80
+ output_data = {}
81
+ for i, row in unique_canteen_info.iterrows():
82
+ canteen_id = row['canteen_id']
83
+ canteen_name = row['canteen_name']
84
+ predicted_surplus = max(0, int(round(predicted_surplus_values[i]))) # Ensure non-negative integer
85
+
86
+ output_data[canteen_id] = {
87
+ 'canteen_name': canteen_name,
88
+ 'predicted_surplus': predicted_surplus
89
+ }
90
+
91
+ # Format the dictionary for better display in Gradio
92
+ formatted_output = "Predicted Surplus Units:\n\n"
93
+ for canteen_id, info in output_data.items():
94
+ formatted_output += f"Canteen ID: {canteen_id}\n"
95
+ formatted_output += f" Canteen Name: {info['canteen_name']}\n"
96
+ formatted_output += f" Predicted Surplus: {info['predicted_surplus']}\n"
97
+ formatted_output += "-" * 20 + "\n"
98
+
99
+ return formatted_output
100
+
101
+
102
+ # Create a Gradio interface with inputs for day, month, and year
103
  iface = gr.Interface(
104
+ fn=predict_surplus,
105
+ inputs=[
106
+ gr.Number(label="Day", precision=0),
107
+ gr.Number(label="Month", precision=0),
108
+ gr.Number(label="Year", precision=0)
109
+ ],
110
  outputs="text",
111
+ title="Predict Canteen Surplus Units",
112
+ description="Enter a date (day, month, year) to predict the surplus units for each canteen."
113
  )
114
 
115
  iface.launch()