File size: 7,162 Bytes
eb7f886 ded6130 a71a948 ded6130 a71a948 ded6130 0032334 ded6130 070f012 ded6130 a71a948 17de6a3 a71a948 ded6130 a71a948 ded6130 a71a948 ded6130 17de6a3 ded6130 17de6a3 ded6130 a71a948 070f012 a71a948 ded6130 a71a948 ded6130 a71a948 ded6130 a71a948 ded6130 a71a948 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
import gradio as gr
import requests
import json
from transformers import pipeline
import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime, timedelta
import logging
# Set up logging for debugging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
# Initialize Hugging Face model for diet plan generation
logger.info("Loading distilgpt2 model...")
generator = pipeline('text-generation', model='distilgpt2')
except Exception as e:
logger.error(f"Failed to load model: {str(e)}")
raise
# Mock Salesforce API endpoints (replace with actual endpoints after Phase 1)
SALESFORCE_BASE_URL = "https://your-org.my.salesforce.com/services/apexrest"
SALESFORCE_TOKEN = "YOUR_SALESFORCE_ACCESS_TOKEN" # Obtain via OAuth in Phase 1
# Mock food database (to be replaced with Salesforce Food_Item__c data)
FOOD_DATABASE = [
{"name": "Chicken Breast", "calories": 165, "protein": 31, "carbs": 0, "fat": 3.6, "benefits": "High protein for muscle repair"},
{"name": "Broccoli", "calories": 55, "protein": 3.7, "carbs": 11, "fat": 0.6, "benefits": "Rich in fiber and vitamins"},
{"name": "Quinoa", "calories": 120, "protein": 4.4, "carbs": 21, "fat": 1.9, "benefits": "Complete protein, gluten-free"}
]
# Function to fetch workout plan from Salesforce
def fetch_workout_plan(user_id):
try:
url = f"{SALESFORCE_BASE_URL}/WorkoutPlan/{user_id}"
headers = {
'Authorization': f'Bearer {SALESFORCE_TOKEN}',
'Content-Type': 'application/json'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
plans = response.json()
return "\n".join([f"Plan: {plan['Plan_Name__c']}, Exercises: {plan['Exercises__c']}, Duration: {plan['Duration__c']} min" for plan in plans])
return f"Error fetching workout plan: {response.status_code}"
except Exception as e:
logger.error(f"Error fetching workout plan: {str(e)}")
return f"Error: {str(e)}"
# Function to generate diet plan using Hugging Face AI
def generate_diet_plan(height, weight, goal):
try:
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."
diet_plan = generator(prompt, max_length=200, num_return_sequences=1)[0]['generated_text']
return diet_plan
except Exception as e:
logger.error(f"Error generating diet plan: {str(e)}")
return f"Error generating diet plan: {str(e)}"
# Function to search food database
def search_food(query):
try:
results = [food for food in FOOD_DATABASE if query.lower() in food['name'].lower()]
if not results:
return "No foods found."
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])
except Exception as e:
logger.error(f"Error searching food: {str(e)}")
return f"Error: {str(e)}"
# Function to save height/weight to Salesforce
def save_metrics(user_id, height, weight):
try:
url = f"{SALESFORCE_BASE_URL}/UserMetrics"
headers = {
'Authorization': f'Bearer {SALESFORCE_TOKEN}',
'Content-Type': 'application/json'
}
data = {
"User__c": user_id,
"Height__c": height,
"Weight__c": weight,
"Date__c": datetime.now().strftime("%Y-%m-%d")
}
response = requests.post(url, headers=headers, json=data)
return "Metrics saved successfully" if response.status_code == 201 else f"Error saving metrics: {response.status_code}"
except Exception as e:
logger.error(f"Error saving metrics: {str(e)}")
return f"Error: {str(e)}"
# Function to fetch and plot height/weight progress
def plot_progress(user_id):
try:
# Mock data (replace with Salesforce User_Metrics__c query)
metrics = [
{"Date__c": "2025-05-01", "Height__c": 180, "Weight__c": 80},
{"Date__c": "2025-05-08", "Height__c": 180, "Weight__c": 79},
{"Date__c": "2025-05-15", "Height__c": 180, "Weight__c": 78}
]
dates = [m["Date__c"] for m in metrics]
weights = [m["Weight__c"] for m in metrics]
plt.figure(figsize=(8, 4))
plt.plot(dates, weights, 'b-', label='Weight (kg)')
plt.title('Weight Progress')
plt.xlabel('Date')
plt.ylabel('Weight (kg)')
plt.grid(True)
plt.legend()
plt.savefig('progress.png')
plt.close()
return 'progress.png'
except Exception as e:
logger.error(f"Error plotting progress: {str(e)}")
return None
# Function to generate a simple calendar
def generate_calendar():
try:
today = datetime.now()
calendar = []
for i in range(7):
day = today + timedelta(days=i)
calendar.append(f"{day.strftime('%Y-%m-%d')}: Schedule workout/meal")
return "\n".join(calendar)
except Exception as e:
logger.error(f"Error generating calendar: {str(e)}")
return f"Error: {str(e)}"
# Main Gradio interface
def gym_work_updates_app(user_id, height, weight, goal, food_query):
try:
# Fetch workout plan
workout_plan = fetch_workout_plan(user_id)
# Generate diet plan
diet_plan = generate_diet_plan(height, weight, goal)
# Search food
food_results = search_food(food_query)
# Save metrics
metrics_result = save_metrics(user_id, height, weight)
# Generate calendar
calendar = generate_calendar()
# Plot progress
progress_chart = plot_progress(user_id)
return (
f"**Workout Plan**\n{workout_plan}\n\n"
f"**Diet Plan**\n{diet_plan}\n\n"
f"**Food Search Results**\n{food_results}\n\n"
f"**Metrics Status**\n{metrics_result}\n\n"
f"**Weekly Calendar**\n{calendar}",
progress_chart
)
except Exception as e:
logger.error(f"Error in app: {str(e)}")
return f"Error: {str(e)}", None
# Create Gradio UI
with gr.Blocks(css="body {font-family: Arial; max-width: 800px; margin: auto; padding: 20px;}") as iface:
gr.Markdown("# Gym Work Updates")
user_id = gr.Textbox(label="User ID")
height = gr.Number(label="Height (cm)")
weight = gr.Number(label="Weight (kg)")
goal = gr.Dropdown(label="Goal", choices=["Weight Loss", "Muscle Gain", "Maintenance"])
food_query = gr.Textbox(label="Search Food")
submit = gr.Button("Get Plans and Metrics")
output_text = gr.Textbox(label="Results")
output_chart = gr.Image(label="Progress Chart")
submit.click(
fn=gym_work_updates_app,
inputs=[user_id, height, weight, goal, food_query],
outputs=[output_text, output_chart]
)
# Launch the app
if __name__ == "__main__":
logger.info("Launching Gradio app...")
iface.launch() |