System Habit Tracker With Python

Health Tracker Program

Health Tracker Program

This program tracks the time spent on web browsers and saves the data to Google Sheets. Below are the steps to set it up and the complete code.

Prerequisites

  1. Install Required Libraries:
    pip install psutil gspread oauth2client
  2. Set Up Google Sheets API:
    • Go to the Google Cloud Console.
    • Create a new project.
    • Enable the Google Sheets API for your project.
    • Create credentials (Service Account) and download the JSON file.
    • Share your Google Sheet with the email address of the service account (found in the JSON file).
  3. Create a Google Sheet:

    Create a new Google Sheet where you want to save the data. Note the name of the sheet, as you will need it in the code.

Health Tracker Program


import psutil
import threading
import time
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from collections import defaultdict

class HealthTracker:
    def __init__(self):
        self.visited_sites = defaultdict(int)
        self.running = True
        self.total_time = 0
        self.start_time = time.time()
        self.sheet_name = "Your Google Sheet Name"  # Replace with your Google Sheet name
        self.gc = self.authenticate_google_sheets()

    def authenticate_google_sheets(self):
        # Authenticate with Google Sheets API
        scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"]
        creds = ServiceAccountCredentials.from_json_keyfile_name('path/to/your/credentials.json', scope)  # Replace with your JSON file path
        client = gspread.authorize(creds)
        return client

    def track_time(self):
        while self.running:
            # Get the list of all running processes
            for proc in psutil.process_iter(['pid', 'name']):
                try:
                    # Check if the process is a web browser
                    if 'chrome' in proc.info['name'].lower() or 'firefox' in proc.info['name'].lower():
                        # Simulate tracking time spent on the browser
                        self.visited_sites[proc.info['name']] += 1
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue
            
            time.sleep(60)  # Check every minute

    def warn_after_three_hours(self):
        while self.running:
            time.sleep(60)  # Check every minute
            self.total_time += 1
            if self.total_time >= 180:  # 3 hours
                print("Warning: You have been using the application for 3 hours!")
                self.total_time = 0  # Reset the timer after warning

    def save_to_google_sheets(self):
        sheet = self.gc.open(self.sheet_name).sheet1  # Open the first sheet
        while self.running:
            time.sleep(300)  # Save every 5 minutes
            data = list(self.visited_sites.items())
            # Clear existing data
            sheet.clear()
            # Write header
            sheet.append_row(['Site', 'Time Spent (minutes)'])
            # Write data
            for site, time_spent in data:
                sheet.append_row([site, time_spent])

    def start(self):
        # Start the tracking, warning, and saving threads
        tracking_thread = threading.Thread(target=self.track_time)
        warning_thread = threading.Thread(target=self.warn_after_three_hours)
        saving_thread = threading.Thread(target=self.save_to_google_sheets)

        tracking_thread.start()
        warning_thread.start()
        saving_thread.start()

        tracking_thread.join()
        warning_thread.join()
        saving_thread.join()

    def stop(self):
        self.running = False
        print("Tracking stopped.")
        print("Visited sites and their time spent (in minutes):")
        for site, time_spent in self.visited_sites.items():
            print(f"{site}: {time_spent} minutes")

if __name__ == "__main__":
    tracker = HealthTracker()
    try:
        tracker.start()
    except KeyboardInterrupt:
        tracker.stop()

Key Changes

  • Google Sheets Authentication: The authenticate_google_sheets method handles authentication using the service account credentials.
  • Saving to Google Sheets: The save_to_google_sheets method saves the visited sites and their time spent to the specified Google Sheet every 5 minutes. It clears the existing data before writing new data.
  • Sheet Name: Replace "Your Google Sheet Name" with the actual name of your Google Sheet.

Note

  • Ensure that the path to your credentials JSON file is correct in the authenticate_google_sheets method.
  • The program will run in the background and can be stopped with a keyboard interrupt (Ctrl+C), at which point it will print the visited sites and their time spent.
  • This implementation still simulates tracking time spent on browsers. For accurate tracking of specific websites visited, you would need to implement a more sophisticated method, possibly using browser extensions or APIs.

Comments

Popular posts from this blog

Tech Duos For Web Development

CIFAR-10 Dataset Classification Using Convolutional Neural Networks (CNNs) With PyTorch

Long-short-term-memory (LSTM) Word Prediction With PyTorch