Shivya0410 commited on
Commit
27132ea
·
verified ·
1 Parent(s): bb63002

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +347 -0
app.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Download latest version
2
+ path = kagglehub.dataset_download("irkaal/foodcom-recipes-and-reviews") # Changed this line to only include the dataset handle
3
+
4
+ # Access the recipes.csv file within the downloaded dataset
5
+ recipes_csv_path = os.path.join(path, "recipes.csv")
6
+ dataset_dir = '/root/.cache/kagglehub/datasets/irkaal/foodcom-recipes-and-reviews/versions/2/' # Changed to the directory containing recipes.csv
7
+
8
+ # Find the CSV file within the directory
9
+ for filename in os.listdir(dataset_dir):
10
+ if filename.endswith('.csv'):
11
+ csv_file = os.path.join(dataset_dir, filename)
12
+ break
13
+
14
+ # Load the dataset from the identified CSV file
15
+ data = pd.read_csv(recipes_csv_path)
16
+ df = data.copy()
17
+ # Select and reorder columns in the dataset for further analysis
18
+ selected_columns = ['RecipeId', 'Calories', 'FatContent', 'SaturatedFatContent',
19
+ 'CholesterolContent', 'SodiumContent', 'CarbohydrateContent',
20
+ 'FiberContent', 'SugarContent', 'ProteinContent']
21
+
22
+ # Check if all selected columns exist in the DataFrame
23
+ missing_columns = [col for col in selected_columns if col not in df.columns]
24
+
25
+ if missing_columns:
26
+ print(f"The following columns are not in the DataFrame: {missing_columns}")
27
+ # Option 1: Raise an error to stop execution
28
+ # raise KeyError(f"Missing columns: {missing_columns}")
29
+ # Option 2: Select only the available columns
30
+ selected_columns = [col for col in selected_columns if col in df.columns]
31
+ print(f"Proceeding with available columns: {selected_columns}")
32
+
33
+ # Apply the selected columns to the DataFrame
34
+ df = df[selected_columns]
35
+ # Display summary statistics of the DataFrame, including specified percentiles
36
+ # Transpose the result for better readability
37
+ summary_statistics = df.describe(percentiles=[0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95]).T
38
+ # Define the columns to filter based on the 95th percentile
39
+ # Ensure these column names exactly match the names in your DataFrame
40
+ # Check for case sensitivity and typos
41
+ filter_columns = ['Calories', 'FatContent', 'SaturatedFatContent',
42
+ 'CholesterolContent', 'SodiumContent',
43
+ 'CarbohydrateContent', 'FiberContent',
44
+ 'SugarContent', 'ProteinContent']
45
+
46
+ # Before calculating quantiles, check if the columns exist in the DataFrame:
47
+ for column in filter_columns:
48
+ if column not in df.columns:
49
+ print(f"Column '{column}' not found in DataFrame. Please check the column names.")
50
+ # You might want to raise an exception or handle the missing column in a way that suits your needs.
51
+
52
+ # Compute the 95th percentile values for each specified column
53
+ percentile_95_thresholds = df[filter_columns].quantile(0.95)
54
+ # Apply filtering to the DataFrame based on the 95th percentile values
55
+ filtered_df = df[(df[filter_columns] <= percentile_95_thresholds).all(axis=1)]
56
+ # Drop the 'RecipeId' column from the DataFrame and assign the result to X
57
+ X = df.drop(columns=['RecipeId'])
58
+
59
+ # Assign the 'RecipeId' column to y
60
+ y = df['RecipeId']
61
+ # Initialize the MinMaxScaler
62
+ scaler = MinMaxScaler()
63
+
64
+ # Fit the scaler to X and transform it
65
+ X_scaled = scaler.fit_transform(X)
66
+ # Split the already scaled data into training and evaluation sets
67
+ X_train_scaled, X_eval_scaled = train_test_split(X_scaled, train_size=0.8, random_state=42)
68
+ # Neural Network Model Architecture
69
+ num_features = X_train_scaled.shape[1] # Number of features in the input data
70
+
71
+ # Define the autoencoder model
72
+ model = Sequential([
73
+ # Encoder
74
+ Dense(256, input_shape=(num_features,)), # Input layer with 256 neurons
75
+ LeakyReLU(), # Activation function with a small slope for negative inputs
76
+ Dropout(0.2), # Dropout layer with 20% dropout rate to prevent overfitting
77
+ Dense(128), # Hidden layer with 128 neurons
78
+ LeakyReLU(), # Activation function
79
+ Dropout(0.2), # Dropout layer
80
+ Dense(64), # Hidden layer with 64 neurons
81
+ LeakyReLU(), # Activation function
82
+ Dropout(0.2), # Dropout layer
83
+
84
+ # Bottleneck
85
+ Dense(32), # Bottleneck layer with 32 neurons, this is the compressed representation of the input data
86
+ # The bottleneck layer reduces the dimensionality of the input data, capturing essential features
87
+
88
+ # Decoder
89
+ Dense(64), # Hidden layer in the decoder with 64 neurons
90
+ LeakyReLU(), # Activation function
91
+ Dropout(0.2), # Dropout layer
92
+ Dense(128), # Hidden layer with 128 neurons
93
+ LeakyReLU(), # Activation function
94
+ Dropout(0.2), # Dropout layer
95
+ Dense(256), # Hidden layer with 256 neurons
96
+ LeakyReLU(), # Activation function
97
+
98
+ # Output layer
99
+ Dense(num_features, activation='linear') # Output layer with the same number of neurons as features, linear activation
100
+ # The linear activation function in the output layer allows the network to reconstruct the input data directly
101
+ ])
102
+ # Define the optimizer with a learning rate
103
+ optimizer = Adam(learning_rate=0.0001)
104
+ # Compile the model
105
+ model.compile(optimizer=optimizer,
106
+ loss='mse', # Mean Squared Error for regression
107
+ metrics=['mae']) # Mean Absolute Error for regression evaluation
108
+ # Fit the model with scaled training data as both input and target
109
+ training_history = model.fit(X_train_scaled, X_train_scaled,
110
+ validation_data=(X_eval_scaled, X_eval_scaled),
111
+ epochs=10)
112
+
113
+ # Extract validation loss from the training history
114
+ validation_loss = training_history.history['val_loss']
115
+ # Predict latent features using the trained model
116
+ predicted_latent_features = model.predict(X_scaled)
117
+ # Manual calculation of cosine similarity
118
+
119
+ # Compute the Dot Product:
120
+ # This calculates the dot product between each pair of latent feature vectors.
121
+ # The result is a matrix where each entry represents the dot product (or similarity) between two feature vectors.
122
+ similarity_matrix = np.dot(predicted_latent_features, predicted_latent_features.T)
123
+
124
+ # Calculate the Norms:
125
+ # The norm (or magnitude) of each latent feature vector is calculated.
126
+ # 'axis=1' indicates that the norm is computed for each row (each feature vector).
127
+ # 'keepdims=True' keeps the dimensions of the output the same for broadcasting purposes.
128
+ norms = np.linalg.norm(predicted_latent_features, axis=1, keepdims=True)
129
+
130
+ # Normalize the Similarity Matrix:
131
+ # Each entry in the similarity matrix is divided by the product of the norms of the vectors being compared.
132
+ # This normalizes the similarity scores to cosine similarity, which ranges from -1 to 1.
133
+ similarity_matrix /= np.dot(norms, norms.T)
134
+ similarity_matrix_sklearn = cosine_similarity(predicted_latent_features)
135
+ # Initialize a dictionary to store recommendations
136
+ recommendations_dict = {}
137
+
138
+ # Iterate over each item in the dataset
139
+ for item_index in range(len(X_scaled)):
140
+ # Sort indices based on similarity in descending order
141
+ sorted_indices = similarity_matrix[item_index].argsort()[::-1]
142
+
143
+ # Create a list of tuples with similarity scores and indices, excluding the item itself
144
+ similar_items_list = [(similarity_matrix[item_index][idx], idx) for idx in sorted_indices if idx != item_index]
145
+
146
+ # Store the list of similar items for the current item in the recommendations dictionary
147
+ recommendations_dict[item_index] = similar_items_list
148
+ # Calculate Basal Metabolic Rate (BMR)
149
+ def compute_bmr(gender, body_weight, body_height, age):
150
+ """
151
+ Calculate Basal Metabolic Rate (BMR) based on gender, body weight, body height, and age.
152
+
153
+ Args:
154
+ gender (str): Gender of the individual ('male' or 'female').
155
+ body_weight (float): Body weight of the individual in kilograms.
156
+ body_height (float): Body height of the individual in centimeters.
157
+ age (int): Age of the individual in years.
158
+
159
+ Return:
160
+ float: Basal Metabolic Rate (BMR) value.
161
+ """
162
+ if gender == 'male':
163
+ # For Men: BMR = (10 x weight in kg) + (6.25 x height in cm) - (5 x age in years) + 5
164
+ bmr_value = 10 * body_weight + 6.25 * body_height - 5 * age + 5
165
+ elif gender == 'female':
166
+ # For Women: BMR = (10 x weight in kg) + (6.25 x height in cm) - (5 x age in years) - 161
167
+ bmr_value = 10 * body_weight + 6.25 * body_height - 5 * age - 161
168
+ else:
169
+ raise ValueError("Invalid gender. Please choose 'male' or 'female'.")
170
+ return bmr_value
171
+
172
+ def compute_daily_caloric_intake(bmr, activity_intensity, objective):
173
+ """
174
+ Calculate total daily caloric intake based on Basal Metabolic Rate (BMR), activity level, and personal goal.
175
+
176
+ Args:
177
+ bmr (float): Basal Metabolic Rate (BMR) value.
178
+ activity_intensity (str): Activity level of the individual ('sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active').
179
+ objective (str): Personal goal of the individual ('weight_loss', 'muscle_gain', 'health_maintenance').
180
+
181
+ Return:
182
+ int: Total daily caloric intake.
183
+ """
184
+ # Define activity multipliers based on intensity
185
+ intensity_multipliers = {
186
+ 'sedentary': 1.2,
187
+ 'lightly_active': 1.375,
188
+ 'moderately_active': 1.55,
189
+ 'very_active': 1.725,
190
+ 'extra_active': 1.9
191
+ }
192
+
193
+ # Define goal adjustments based on objective
194
+ objective_adjustments = {
195
+ 'weight_loss': 0.8,
196
+ 'muscle_gain': 1.2,
197
+ 'health_maintenance': 1
198
+ }
199
+
200
+ # Calculate maintenance calories based on activity intensity
201
+ maintenance_calories = bmr * intensity_multipliers[activity_intensity]
202
+
203
+ # Adjust maintenance calories based on personal objective
204
+ total_caloric_intake = maintenance_calories * objective_adjustments[objective]
205
+
206
+ return round(total_caloric_intake)
207
+
208
+ def suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective):
209
+ """
210
+ Generate food recommendations based on the user's profile and dietary goals.
211
+
212
+ Args:
213
+ category (str): Gender category of the user ('male' or 'female').
214
+ body_weight (float): Weight of the user in kilograms.
215
+ body_height (float): Height of the user in centimeters.
216
+ age (int): Age of the user in years.
217
+ activity_intensity (str): Physical activity level of the user ('sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active').
218
+ objective (str): Dietary objective of the user ('weight_loss', 'muscle_gain', 'health_maintenance').
219
+
220
+ Return:
221
+ pd.DataFrame: Recommended recipes including name and calorie content.
222
+ """
223
+ # Calculate the Basal Metabolic Rate (BMR) for the user
224
+ bmr = compute_bmr(category, body_weight, body_height, age)
225
+
226
+ # Calculate the total daily caloric intake based on activity intensity and dietary objective
227
+ total_calories = compute_daily_caloric_intake(bmr, activity_intensity, objective)
228
+
229
+ # Prepare input data for the model with desired total calories
230
+ user_input_features = np.array([[total_calories, 0, 0, 0, 0, 0, 0, 0, 0]])
231
+
232
+ # Scale the input data to match the model's training scale
233
+ scaled_input_features = scaler.transform(user_input_features)
234
+
235
+ # Predict latent features for the input data
236
+ predicted_latent_features = model.predict(scaled_input_features)
237
+
238
+ # Find the index with the highest prediction probability
239
+ top_prediction_index = np.argmax(predicted_latent_features.flatten())
240
+
241
+ # Retrieve recommended recipes based on the highest prediction
242
+ similar_recipe_indices = np.array(recommendations_dict[top_prediction_index])
243
+ recommended_recipes = data.iloc[similar_recipe_indices[:, 1].astype(int)][['Name', 'Calories']]
244
+
245
+ return recommended_recipes.head(5)
246
+
247
+ # Define the input values
248
+ user_category = 'male'
249
+ user_body_weight = 80 # in kilograms
250
+ user_body_height = 170 # in centimeters
251
+ user_age = 50 # in years
252
+ user_activity_intensity = 'moderately_active'
253
+ user_objective = 'weight_loss'
254
+
255
+ # Generate suggested recipes
256
+ suggested_recipes = suggest_recipes(
257
+ category=user_category,
258
+ body_weight=user_body_weight,
259
+ body_height=user_body_height,
260
+ age=user_age,
261
+ activity_intensity=user_activity_intensity,
262
+ objective=user_objective
263
+ )
264
+
265
+ # Calculate required daily calories
266
+ required_calories = compute_daily_caloric_intake(
267
+ bmr=compute_bmr(user_category, user_body_weight, user_body_height, user_age),
268
+ activity_intensity=user_activity_intensity,
269
+ objective=user_objective
270
+ )
271
+
272
+ # Function to calculate BMR
273
+ def compute_bmr(gender, body_weight, body_height, age):
274
+ if gender == 'male':
275
+ return 10 * body_weight + 6.25 * body_height - 5 * age + 5
276
+ elif gender == 'female':
277
+ return 10 * body_weight + 6.25 * body_height - 5 * age - 161
278
+ else:
279
+ raise ValueError("Invalid gender. Choose 'male' or 'female'.")
280
+
281
+ # Function to calculate daily caloric intake
282
+ def compute_daily_caloric_intake(bmr, activity_intensity, objective):
283
+ intensity_multipliers = {
284
+ 'sedentary': 1.2,
285
+ 'lightly_active': 1.375,
286
+ 'moderately_active': 1.55,
287
+ 'very_active': 1.725,
288
+ 'extra_active': 1.9
289
+ }
290
+ objective_adjustments = {
291
+ 'weight_loss': 0.8,
292
+ 'muscle_gain': 1.2,
293
+ 'health_maintenance': 1
294
+ }
295
+ maintenance_calories = bmr * intensity_multipliers[activity_intensity]
296
+ return round(maintenance_calories * objective_adjustments[objective])
297
+
298
+ # Function to suggest recipes
299
+ def suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective):
300
+ # Calculate BMR and daily caloric intake
301
+ bmr = compute_bmr(category, body_weight, body_height, age)
302
+ total_calories = compute_daily_caloric_intake(bmr, activity_intensity, objective)
303
+
304
+ # Prepare input for the model
305
+ user_input_features = np.array([[total_calories, 0, 0, 0, 0, 0, 0, 0, 0]])
306
+ scaled_input_features = scaler.transform(user_input_features)
307
+
308
+ # Predict latent features
309
+ predicted_latent_features = model.predict(scaled_input_features)
310
+
311
+ # Find recommendations
312
+ top_prediction_index = np.argmax(predicted_latent_features.flatten())
313
+ similar_recipe_indices = np.array(recommendations_dict[top_prediction_index])
314
+ recommended_recipes = data.iloc[similar_recipe_indices[:, 1].astype(int)][['Name', 'Calories']]
315
+
316
+ # Return the top 5 suggested recipes
317
+ return recommended_recipes.head(5).to_dict(orient='records')
318
+
319
+ # Define the Gradio interface function
320
+ def gradio_diet_recommender(category, body_weight, body_height, age, activity_intensity, objective):
321
+ try:
322
+ recommendations = suggest_recipes(category, body_weight, body_height, age, activity_intensity, objective)
323
+ result = f"Top Recommended Recipes:\n\n"
324
+ for idx, recipe in enumerate(recommendations):
325
+ result += f"{idx + 1}. {recipe['Name']} - {recipe['Calories']} Calories\n"
326
+ return result
327
+ except Exception as e:
328
+ return str(e)
329
+
330
+ # Create the Gradio interface
331
+ interface = gr.Interface(
332
+ fn=gradio_diet_recommender,
333
+ inputs=[
334
+ gr.Radio(choices=['male', 'female'], label="Gender"),
335
+ gr.Number(label="Body Weight (kg)"),
336
+ gr.Number(label="Body Height (cm)"),
337
+ gr.Number(label="Age (years)"),
338
+ gr.Dropdown(choices=['sedentary', 'lightly_active', 'moderately_active', 'very_active', 'extra_active'], label="Activity Intensity"),
339
+ gr.Dropdown(choices=['weight_loss', 'muscle_gain', 'health_maintenance'], label="Objective")
340
+ ],
341
+ outputs="text",
342
+ title="Diet Recommender System",
343
+ description="Provide your details to receive a customized diet plan."
344
+ )
345
+
346
+ # Launch the Gradio app
347
+ interface.launch()