Update app.py
Browse files
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 |
-
#
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
# Function to search food database
|
| 46 |
def search_food(query):
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
# Function to generate a simple calendar
|
| 93 |
def generate_calendar():
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
# Main Gradio interface
|
| 102 |
def gym_work_updates_app(user_id, height, weight, goal, food_query):
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
| 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()
|