# Project export: WorkFit

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 11.0
- Tagline: WorkFot: Your personalized fitness companion that adapts workout schedules based on your energy levels and work commitments. "Smart scheduling for a healthier you."
- Devpost: https://devpost.com/software/workfit-168vcb
- GitHub: https://github.com/Zak-Dev21/Physical-Health-App
- Team: 1 GitHub contributor(s) — Zak (1 commits)

## Devpost submission (written by the team)

### Inspiration

WorkFit was inspired by the desire to help individuals with varying job types and lifestyles improve their activity levels. I believe that everyone deserves the opportunity to lead longer, more enjoyable, and productive lives. This project aims to tailor fitness solutions that fit seamlessly into users' schedules, considering their unique energy levels and work commitments. What I Learned Throughout this project, I learned about integrating user feedback into fitness applications and the importance of personalized approaches to health. I also gained hands-on experience with Fetch.ai agents, scheduling algorithms, and user interface design. How I Built the Project I developed WorkFit using HTML, CSS, and JavaScript within VS Code. I utilized Fetch.ai for implementing agents that help track user schedules and provide personalized workout recommendations based on energy levels and job types. The project involved defining clear user requirements and designing an intuitive interface for a better user experience. Challenges Faced One of the primary challenges was ensuring that the agent accurately assessed user energy levels and job demands. I had to experiment with different algorithms to optimize the scheduling process. Additionally, integrating the various components of the app and ensuring a seamless user experience required significant testing and iteration. Built With Languages: HTML, CSS, JavaScript Frameworks: Fetch.ai Tools: VS Code

## README (from the GitHub repository)

# WorkFit: Personalized Fitness Platform for Every Lifestyle

**WorkFit** is a health and fitness platform designed to create customized workout schedules that fit seamlessly into users' daily routines. Whether you're working a desk job or an active physical role, WorkFit tailors workout plans based on your job type, activity levels, and personal fitness goals. 

The platform helps users stay active and healthy by providing personalized exercise routines that can be integrated into their busy schedules. It also uses advanced AI technologies, such as Fetch.AI’s uAgents, to optimize workout plans and track performance.

## Key Features

- **Personalized Workout Schedule**: Automatically adjusts workout plans to fit into your daily routine, based on your job type (sedentary or physical) and preferred time slots.
- **Tailored Exercises**: Offers workouts suited to your lifestyle, whether you're looking to build strength, improve endurance, or maintain overall fitness.
- **AI-Powered Automation**: Utilizes Fetch.AI’s uAgents to automatically optimize workout schedules and exercise routines for better performance.
- **Fitness Goal Tracking**: Tracks progress toward your fitness goals, adjusting plans to ensure continuous improvement.

## Future Goals

- **Location-Based Fitness**: Integration with location services to suggest nearby parks and gyms for convenient exercise options.
- **Cost-Effective Plans**: Personalization based on user budget, providing customized, affordable workout plans and resources.

## Technology Stack

- **Backend**: Node.js, Express
- **AI Integration**: Fetch.AI uAgents
- **Frontend**: React
- **Database**: MongoDB
- **Deployment**: Heroku

## Installation & Setup

1. Clone the repository:  
   `git clone https://github.com/Zak-Dev21/Physical-Health-App
   
2. Navigate to the project directory:  
   `cd Physical-Health-App`
   
3. Install dependencies:  
   `npm install`
   
4. Start the development server:  
   `npm start`
   
5. Open your browser and go to:  
   `http://localhost:3000`

## Contributing

We welcome contributions! If you'd like 


## Detected evidence (automated analysis)

Indexed codebase: 9 recognized source files, 14 KB.
- CSS (language) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code

## Codebase structure (from repository index)

### Files (25 of 25)

```
.vs/Physical Health App/CopilotIndices/0.2.1634.3922/CodeChunks.db
.vs/Physical Health App/CopilotIndices/0.2.1634.3922/SemanticSymbols.db
.vs/Physical Health App/CopilotIndices/0.2.1634.3922/SemanticSymbols.db-shm
.vs/Physical Health App/CopilotIndices/0.2.1634.3922/SemanticSymbols.db-wal
.vs/Physical Health App/CopilotIndices/0.2.1657.32929/CodeChunks.db
.vs/Physical Health App/CopilotIndices/0.2.1657.32929/SemanticSymbols.db
.vs/Physical Health App/CopilotIndices/0.2.1657.32929/SemanticSymbols.db-shm
.vs/Physical Health App/CopilotIndices/0.2.1657.32929/SemanticSymbols.db-wal
.vs/Physical Health App/FileContentIndex/488667fa-a4f4-443f-bcf0-1ff4daf8f40e.vsidx
.vs/Physical Health App/v17/.wsuo
.vs/Physical Health App/v17/DocumentLayout.backup.json
.vs/Physical Health App/v17/DocumentLayout.json
.vs/ProjectSettings.json
.vs/slnx.sqlite
.vs/VSWorkspaceState.json
.vscode/settings.json
api_server.py
index.html
lifestyle_agent.py
output_agent.py
README.md
schedule_agent.py
script.js
style.css
workoutiming_agent.py
```

### Dependencies

No dependency index available.

### Recent commits (newest first)

- Create README.md
- first commit

## Key source files (fetched from GitHub, selected and truncated for size)

### output_agent.py

```python
ECHO is on.

```

### style.css

```css
body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}
.container {
    max-width: 600px;
    margin: 50px auto;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0px 4px 8px rgba(0,0,0,0.1);
}
h1 {
    text-align: center;
}
.task {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}
button {
    display: block;
    margin: 10px auto;
    padding: 10px 20px;
    background-color: #007BFF;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
button:hover {
    background-color: #0056b3;
}
#freeSlots {
    margin-top: 20px;
    text-align: center;
}

```

### workoutiming_agent.py

```python
from uagents import Agent, Context
from datetime import datetime, timedelta

class TimingAgent(Agent):
    def __init__(self, address: str):
        super().__init__(name="timing_agent", seed=address)

    async def suggest_best_time(self, ctx: Context, schedule: list, energy_level: str):
        """
        Suggests the best time for workouts based on user schedule and energy level.
        """
        best_time = None
        # Assuming energy levels can be 'low', 'moderate', 'high'
        if energy_level == "high":
            best_time = schedule[0] if schedule else "No available time today"
        elif energy_level == "moderate":
            # Pick the mid-point of free time slots
            best_time = schedule[len(schedule) // 2] if schedule else "No available time today"
        else:  # low energy
            # Suggest rest or light workout
            best_time = "Consider rest or light stretching today"

        ctx.logger.info(f"Suggested best time for workout: {best_time}")
        return best_time

```

### lifestyle_agent.py

```python
from uagents import Agent, Context

class LifestyleAgent(Agent):
    def __init__(self, address: str):
        super().__init__(name="lifestyle_agent", seed=address)
        self.user_data = {}

    async def store_user_data(self, ctx: Context, user_data: dict):
        """
        Stores user information: job type, activity level, and goals.
        """
        self.user_data = {
            "job_type": user_data["job_type"],
            "activity_level": user_data["activity_level"],
            "goals": user_data["goals"]
        }
        ctx.logger.info(f"User data stored: {self.user_data}")

# Example usage
async def run_lifestyle_agent():
    # Create an instance of LifestyleAgent
    lifestyle_agent = LifestyleAgent(address="some_seed_or_address")

    # Example user data
    user_data = {
        "job_type": "sedentary",  # Can be 'sedentary' or 'physical'
        "activity_level": "low",  # Can be 'low', 'moderate', 'high'
        "goals": "increase strength"  # User goal
    }

    # Store user data
    await lifestyle_agent.store_user_data(Context(lifestyle_agent), user_data)

```

### index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>WorkFit</title>
</head>
<body>
    <div class="container">
        <h1>WorkFit Scheduler</h1>
        
        <form id="scheduleForm">
            <h2>User Data</h2>
            <label for="jobType">Job Type:</label>
            <input type="text" id="jobType" name="job_type" required>
            <label for="activityLevel">Activity Level:</label>
            <input type="text" id="activityLevel" name="activity_level" required>
            <label for="goals">Workout Goals:</label>
            <input type="text" id="goals" name="goals" required>
            
            <h2>Schedule Tasks</h2>
            <div id="tasks"></div>
            <button type="button" id="addTask">Add Task</button>
            
            <button type="submit">Submit Schedule</button>
        </form>

        <div id="freeSlots"></div>
        <div id="workoutSuggestions"></div> <!-- Moved this inside the container -->
    </div>

    <script src="script.js"></script>
</body>
</html>

```

### api_server.py

```python
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List

from schedule_agent import SchedulerAgent, Context
from lifestyle_agent import LifestyleAgent
from workoutiming_agent import TimingAgent

app = FastAPI()

scheduler_agent = SchedulerAgent(address="some_seed_or_address")
lifestyle_agent = LifestyleAgent(address="some_seed_or_address")
timing_agent = TimingAgent(address="some_seed_or_address")

class Task(BaseModel):
    start_time: str
    end_time: str

class ScheduleData(BaseModel):
    tasks: List[Task]

class UserData(BaseModel):
    job_type: str
    activity_level: str
    goals: str

@app.post("/api/schedule")
async def receive_schedule(schedule_data: ScheduleData):
    task_list = [{"start_time": task.start_time, "end_time": task.end_time} for task in schedule_data.tasks]
    schedule_payload = {"tasks": task_list}
    await scheduler_agent.add_schedule(Context(scheduler_agent), schedule_payload)
    free_slots = await scheduler_agent.find_free_slots(Context(scheduler_agent))
    return {"free_slots": free_slots}

@app.post("/api/user_data")
async def receive_user_data(user_data: UserData):
    await lifestyle_agent.store_user_data(Context(lifestyle_agent), user_data.dict())
    return {"message": "User data stored"}

@app.get("/api/suggest_workout_time")
async def suggest_workout_time():
    # Assuming you already have free slots and energy level
    free_slots = await scheduler_agent.find_free_slots(Context(scheduler_agent))
    user_data = lifestyle_agent.user_data
    energy_level = "moderate"  # This could be dynamic based on more user info
    best_time = await timing_agent.suggest_best_time(Context(timing_agent), free_slots, energy_level)
    return {"best_workout_time": best_time}

```

### schedule_agent.py

```python
from uagents import Agent, Context
from datetime import datetime, timedelta

class SchedulerAgent(Agent):
    def __init__(self, address: str):
        super().__init__(name="scheduler_agent", seed=address)
        self.schedule = []

    @staticmethod
    def str_to_time(time_str: str) -> datetime:
        return datetime.strptime(time_str, "%H:%M")

    @staticmethod
    def time_to_str(time_obj: datetime) -> str:
        return time_obj.strftime("%H:%M")

    async def add_schedule(self, ctx: Context, schedule_data: dict):
        """
        Receives a schedule and stores it for the user.
        Example schedule: [{'start_time': '09:00', 'end_time': '10:30'}, ...]
        """
        self.schedule = [(self.str_to_time(task['start_time']), self.str_to_time(task['end_time'])) for task in schedule_data['tasks']]
        ctx.logger.info(f"Schedule received: {self.schedule}")

    async def find_free_slots(self, ctx: Context):
        """
        Find free time slots in the user's schedule for workouts.
        Returns a list of free time slots.
        """
        day_start = self.str_to_time("08:00")  # Start of the day
        day_end = self.str_to_time("22:00")    # End of the day
        free_slots = []
        current_time = day_start

        self.schedule.sort(key=lambda x: x[0])

        for task_start, task_end in self.schedule:
            if current_time < task_start:
                free_slots.append((self.time_to_str(current_time), self.time_to_str(task_start)))
            current_time = max(current_time, task_end)

        if current_time < day_end:
            free_slots.append((self.time_to_str(current_time), self.time_to_str(day_end)))

        ctx.logger.info(f"Free slots: {free_slots}")
        return free_slots

# Example usage
async def run_scheduler():
    # Create an instance of SchedulerAgent
    scheduler_agent = SchedulerAgent(address="some_seed_or_address_here")

    # Example schedule data
    schedule_data = {
        "tasks": [
            {"start_time": "09:00", "end_time": "10:30"},
            {"start_time": "12:00", "end_time": "13:00"},
            {"start_time": "15:30", "end_time": "17:00"}
        ]
    }

    # Add schedule
    await scheduler_agent.add_schedule(Context(scheduler_agent), schedule_data)

    # Find free slots
    free_slots = await scheduler_agent.find_free_slots(Context(scheduler_agent))
    print("Free slots for workouts:", free_slots)

# You would call run_scheduler() as part of your agent's lifecycle.

```

### script.js

```javascript
document.getElementById('addTask').addEventListener('click', function() {
    const taskInput = document.createElement('input');
    taskInput.type = 'text';
    taskInput.placeholder = 'Task Description';
    document.getElementById('tasks').appendChild(taskInput);
});

document.getElementById('scheduleForm').addEventListener('submit', function(e) {
    e.preventDefault();

    // Collect user data
    const jobType = document.getElementById('jobType').value;
    const activityLevel = document.getElementById('activityLevel').value.toLowerCase();
    const goals = document.getElementById('goals').value.toLowerCase();

    // Generate workout suggestions based on user input
    const workoutSuggestions = generateWorkoutSuggestions(jobType, activityLevel, goals);
    // Generate timing suggestions based on user input
    const timingSuggestions = generateTimingSuggestions(activityLevel, goals);

    // Display the workout suggestions
    const workoutSuggestionsDiv = document.getElementById('workoutSuggestions');
    workoutSuggestionsDiv.innerHTML = "<h3>Workout Suggestions</h3>";
    
    workoutSuggestions.forEach(suggestion => {
        const suggestionElement = document.createElement('p');
        suggestionElement.textContent = suggestion;
        workoutSuggestionsDiv.appendChild(suggestionElement);
    });

    // Display timing suggestions
    workoutSuggestionsDiv.innerHTML += "<h3>Suggested Timing</h3>";
    timingSuggestions.forEach(timing => {
        const timingElement = document.createElement('p');
        timingElement.textContent = timing;
        workoutSuggestionsDiv.appendChild(timingElement);
    });

    // Clear the input fields
    document.getElementById('scheduleForm').reset();
});

// Function to generate workout suggestions based on user input
function generateWorkoutSuggestions(jobType, activityLevel, goals) {
    const suggestions = [];

    // Example logic for generating suggestions
    if (activityLevel === "high") {
        suggestions.push("Try interval training to maximize your efficiency.");
        suggestions.push("Incorporate strength training twice a week.");
    } else if (activityLevel === "medium") {
        suggestions.push("Consider a balanced mix of cardio and strength training.");
        suggestions.push("Aim for at least 150 minutes of moderate activity each week.");
    } else {
        suggestions.push("Start with light exercises, such as walking or yoga.");
        suggestions.push("Gradually increase your activity level over time.");
    }

    // Add suggestions based on goals as needed
    if (goals.includes("weight loss")) {
        suggestions.push("Focus on high-intensity interval training (HIIT) for weight loss.");
    }

    return suggestions;
}

// Function to generate timing suggestions based on user input
function generateTimingSuggestions(activityLevel, goals) {
    const timingSuggestions = [];

    // Add timing suggestions based on activity level
    if (activityLevel === "high") {
        timingSuggestions.push("Schedule workouts in the morning before work for maximum energy.");
        timingSuggestions.push("Try short sessions during lunch breaks.");
    } else if (activityLevel === "medium") {
        timingSuggestions.push("Consider evening workouts after work when your energy levels are higher.");
    } else {
        timingSuggestions.push("Short sessions in the evening or weekends are best to ease into exercise.");
    }

    // Additional timing suggestions based on goals
    if (goals.includes("weight loss")) {
        timingSuggestions.push("Aim for workouts in the evening to help boost metabolism.");
    } else if (goals.includes("muscle gain")) {
        timingSuggestions.push("Morning workouts can maximize energy for strength training.");
    } else if (goals.includes("flexibility")) {
        timingSuggestions.push("Evening or morning yoga sessions can be beneficial.");
    }

    return timingSuggestions;
}


```