|
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 |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
try: |
|
|
|
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 |
|
|
|
|
|
SALESFORCE_BASE_URL = "https://your-org.my.salesforce.com/services/apexrest" |
|
SALESFORCE_TOKEN = "YOUR_SALESFORCE_ACCESS_TOKEN" |
|
|
|
|
|
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"} |
|
] |
|
|
|
|
|
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)}" |
|
|
|
|
|
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)}" |
|
|
|
|
|
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)}" |
|
|
|
|
|
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)}" |
|
|
|
|
|
def plot_progress(user_id): |
|
try: |
|
|
|
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 |
|
|
|
|
|
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)}" |
|
|
|
|
|
def gym_work_updates_app(user_id, height, weight, goal, food_query): |
|
try: |
|
|
|
workout_plan = fetch_workout_plan(user_id) |
|
|
|
diet_plan = generate_diet_plan(height, weight, goal) |
|
|
|
food_results = search_food(food_query) |
|
|
|
metrics_result = save_metrics(user_id, height, weight) |
|
|
|
calendar = generate_calendar() |
|
|
|
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 |
|
|
|
|
|
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] |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
logger.info("Launching Gradio app...") |
|
iface.launch() |