lokeshloki143 commited on
Commit
a71a948
·
verified ·
1 Parent(s): af61b5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -57
app.py CHANGED
@@ -5,9 +5,19 @@ from transformers import pipeline
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
  from datetime import datetime, timedelta
 
8
 
9
- # Initialize Hugging Face model for diet plan generation
10
- generator = pipeline('text-generation', model='distilgpt2')
 
 
 
 
 
 
 
 
 
11
 
12
  # Mock Salesforce API endpoints (replace with actual endpoints after Phase 1)
13
  SALESFORCE_BASE_URL = "https://your-org.my.salesforce.com/services/apexrest"
@@ -32,22 +42,31 @@ def fetch_workout_plan(user_id):
32
  if response.status_code == 200:
33
  plans = response.json()
34
  return "\n".join([f"Plan: {plan['Plan_Name__c']}, Exercises: {plan['Exercises__c']}, Duration: {plan['Duration__c']} min" for plan in plans])
35
- return "Error fetching workout plan"
36
  except Exception as e:
 
37
  return f"Error: {str(e)}"
38
 
39
  # Function to generate diet plan using Hugging Face AI
40
  def generate_diet_plan(height, weight, goal):
41
- prompt = f"Generate a daily diet plan for a person with height {height} cm, weight {weight} kg, and goal {goal}. Include food items, portion sizes, and nutritional benefits."
42
- diet_plan = generator(prompt, max_length=200, num_return_sequences=1)[0]['generated_text']
43
- return diet_plan
 
 
 
 
44
 
45
  # Function to search food database
46
  def search_food(query):
47
- results = [food for food in FOOD_DATABASE if query.lower() in food['name'].lower()]
48
- if not results:
49
- return "No foods found."
50
- return "\n".join([f"{food['name']}: {food['calories']} kcal, Protein: {food['protein']}g, Carbs: {food['carbs']}g, Fat: {food['fat']}g, Benefits: {food['benefits']}" for food in results])
 
 
 
 
51
 
52
  # Function to save height/weight to Salesforce
53
  def save_metrics(user_id, height, weight):
@@ -64,63 +83,77 @@ def save_metrics(user_id, height, weight):
64
  "Date__c": datetime.now().strftime("%Y-%m-%d")
65
  }
66
  response = requests.post(url, headers=headers, json=data)
67
- return "Metrics saved successfully" if response.status_code == 201 else "Error saving metrics"
68
  except Exception as e:
 
69
  return f"Error: {str(e)}"
70
 
71
  # Function to fetch and plot height/weight progress
72
  def plot_progress(user_id):
73
- # Mock data (replace with Salesforce User_Metrics__c query)
74
- metrics = [
75
- {"Date__c": "2025-05-01", "Height__c": 180, "Weight__c": 80},
76
- {"Date__c": "2025-05-08", "Height__c": 180, "Weight__c": 79},
77
- {"Date__c": "2025-05-15", "Height__c": 180, "Weight__c": 78}
78
- ]
79
- dates = [m["Date__c"] for m in metrics]
80
- weights = [m["Weight__c"] for m in metrics]
81
-
82
- plt.figure(figsize=(8, 4))
83
- plt.plot(dates, weights, 'b-', label='Weight (kg)')
84
- plt.title('Weight Progress')
85
- plt.xlabel('Date')
86
- plt.ylabel('Weight (kg)')
87
- plt.grid(True)
88
- plt.legend()
89
- plt.savefig('progress.png')
90
- return 'progress.png'
 
 
 
 
 
91
 
92
  # Function to generate a simple calendar
93
  def generate_calendar():
94
- today = datetime.now()
95
- calendar = []
96
- for i in range(7):
97
- day = today + timedelta(days=i)
98
- calendar.append(f"{day.strftime('%Y-%m-%d')}: Schedule workout/meal")
99
- return "\n".join(calendar)
 
 
 
 
100
 
101
  # Main Gradio interface
102
  def gym_work_updates_app(user_id, height, weight, goal, food_query):
103
- # Fetch workout plan
104
- workout_plan = fetch_workout_plan(user_id)
105
- # Generate diet plan
106
- diet_plan = generate_diet_plan(height, weight, goal)
107
- # Search food
108
- food_results = search_food(food_query)
109
- # Save metrics
110
- metrics_result = save_metrics(user_id, height, weight)
111
- # Generate calendar
112
- calendar = generate_calendar()
113
- # Plot progress
114
- progress_chart = plot_progress(user_id)
115
-
116
- return (
117
- f"**Workout Plan**\n{workout_plan}\n\n"
118
- f"**Diet Plan**\n{diet_plan}\n\n"
119
- f"**Food Search Results**\n{food_results}\n\n"
120
- f"**Metrics Status**\n{metrics_result}\n\n"
121
- f"**Weekly Calendar**\n{calendar}",
122
- progress_chart
123
- )
 
 
 
 
124
 
125
  # Create Gradio UI
126
  with gr.Blocks(css="body {font-family: Arial; max-width: 800px; margin: auto; padding: 20px;}") as iface:
@@ -140,4 +173,6 @@ with gr.Blocks(css="body {font-family: Arial; max-width: 800px; margin: auto; pa
140
  )
141
 
142
  # Launch the app
143
- iface.launch()
 
 
 
5
  import matplotlib.pyplot as plt
6
  import numpy as np
7
  from datetime import datetime, timedelta
8
+ import logging
9
 
10
+ # Set up logging for debugging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
+ try:
15
+ # Initialize Hugging Face model for diet plan generation
16
+ logger.info("Loading distilgpt2 model...")
17
+ generator = pipeline('text-generation', model='distilgpt2')
18
+ except Exception as e:
19
+ logger.error(f"Failed to load model: {str(e)}")
20
+ raise
21
 
22
  # Mock Salesforce API endpoints (replace with actual endpoints after Phase 1)
23
  SALESFORCE_BASE_URL = "https://your-org.my.salesforce.com/services/apexrest"
 
42
  if response.status_code == 200:
43
  plans = response.json()
44
  return "\n".join([f"Plan: {plan['Plan_Name__c']}, Exercises: {plan['Exercises__c']}, Duration: {plan['Duration__c']} min" for plan in plans])
45
+ return f"Error fetching workout plan: {response.status_code}"
46
  except Exception as e:
47
+ logger.error(f"Error fetching workout plan: {str(e)}")
48
  return f"Error: {str(e)}"
49
 
50
  # Function to generate diet plan using Hugging Face AI
51
  def generate_diet_plan(height, weight, goal):
52
+ try:
53
+ prompt = f"Generate a daily diet plan for a person with height {height} cm, weight {weight} kg, and goal {goal}. Include food items, portion sizes, and nutritional benefits."
54
+ diet_plan = generator(prompt, max_length=200, num_return_sequences=1)[0]['generated_text']
55
+ return diet_plan
56
+ except Exception as e:
57
+ logger.error(f"Error generating diet plan: {str(e)}")
58
+ return f"Error generating diet plan: {str(e)}"
59
 
60
  # Function to search food database
61
  def search_food(query):
62
+ try:
63
+ results = [food for food in FOOD_DATABASE if query.lower() in food['name'].lower()]
64
+ if not results:
65
+ return "No foods found."
66
+ return "\n".join([f"{food['name']}: {food['calories']} kcal, Protein: {food['protein']}g, Carbs: {food['carbs']}g, Fat: {food['fat']}g, Benefits: {food['benefits']}" for food in results])
67
+ except Exception as e:
68
+ logger.error(f"Error searching food: {str(e)}")
69
+ return f"Error: {str(e)}"
70
 
71
  # Function to save height/weight to Salesforce
72
  def save_metrics(user_id, height, weight):
 
83
  "Date__c": datetime.now().strftime("%Y-%m-%d")
84
  }
85
  response = requests.post(url, headers=headers, json=data)
86
+ return "Metrics saved successfully" if response.status_code == 201 else f"Error saving metrics: {response.status_code}"
87
  except Exception as e:
88
+ logger.error(f"Error saving metrics: {str(e)}")
89
  return f"Error: {str(e)}"
90
 
91
  # Function to fetch and plot height/weight progress
92
  def plot_progress(user_id):
93
+ try:
94
+ # Mock data (replace with Salesforce User_Metrics__c query)
95
+ metrics = [
96
+ {"Date__c": "2025-05-01", "Height__c": 180, "Weight__c": 80},
97
+ {"Date__c": "2025-05-08", "Height__c": 180, "Weight__c": 79},
98
+ {"Date__c": "2025-05-15", "Height__c": 180, "Weight__c": 78}
99
+ ]
100
+ dates = [m["Date__c"] for m in metrics]
101
+ weights = [m["Weight__c"] for m in metrics]
102
+
103
+ plt.figure(figsize=(8, 4))
104
+ plt.plot(dates, weights, 'b-', label='Weight (kg)')
105
+ plt.title('Weight Progress')
106
+ plt.xlabel('Date')
107
+ plt.ylabel('Weight (kg)')
108
+ plt.grid(True)
109
+ plt.legend()
110
+ plt.savefig('progress.png')
111
+ plt.close()
112
+ return 'progress.png'
113
+ except Exception as e:
114
+ logger.error(f"Error plotting progress: {str(e)}")
115
+ return None
116
 
117
  # Function to generate a simple calendar
118
  def generate_calendar():
119
+ try:
120
+ today = datetime.now()
121
+ calendar = []
122
+ for i in range(7):
123
+ day = today + timedelta(days=i)
124
+ calendar.append(f"{day.strftime('%Y-%m-%d')}: Schedule workout/meal")
125
+ return "\n".join(calendar)
126
+ except Exception as e:
127
+ logger.error(f"Error generating calendar: {str(e)}")
128
+ return f"Error: {str(e)}"
129
 
130
  # Main Gradio interface
131
  def gym_work_updates_app(user_id, height, weight, goal, food_query):
132
+ try:
133
+ # Fetch workout plan
134
+ workout_plan = fetch_workout_plan(user_id)
135
+ # Generate diet plan
136
+ diet_plan = generate_diet_plan(height, weight, goal)
137
+ # Search food
138
+ food_results = search_food(food_query)
139
+ # Save metrics
140
+ metrics_result = save_metrics(user_id, height, weight)
141
+ # Generate calendar
142
+ calendar = generate_calendar()
143
+ # Plot progress
144
+ progress_chart = plot_progress(user_id)
145
+
146
+ return (
147
+ f"**Workout Plan**\n{workout_plan}\n\n"
148
+ f"**Diet Plan**\n{diet_plan}\n\n"
149
+ f"**Food Search Results**\n{food_results}\n\n"
150
+ f"**Metrics Status**\n{metrics_result}\n\n"
151
+ f"**Weekly Calendar**\n{calendar}",
152
+ progress_chart
153
+ )
154
+ except Exception as e:
155
+ logger.error(f"Error in app: {str(e)}")
156
+ return f"Error: {str(e)}", None
157
 
158
  # Create Gradio UI
159
  with gr.Blocks(css="body {font-family: Arial; max-width: 800px; margin: auto; padding: 20px;}") as iface:
 
173
  )
174
 
175
  # Launch the app
176
+ if __name__ == "__main__":
177
+ logger.info("Launching Gradio app...")
178
+ iface.launch()