0% found this document useful (0 votes)
5 views44 pages

Campus Health Monitoring System in Python

Pythons assignment

Uploaded by

rohithlingam25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

Campus Health Monitoring System in Python

Pythons assignment

Uploaded by

rohithlingam25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON ASSIGNMENT

Q1. Design a Campus Health & Fitness Monitoring System (CHFMS) that automates:
- daily health check
- fitness scoring
- appointment scheduling
Develop full Python workflow using algorithm, decisions, loops, control statements.

ALGORITHM:

1. Start the program.

2. Create an empty health record and an empty appointment list.

3. Display menu with 4 options:

- Daily health check

- Fitness score

- Appointment scheduling

- View appointments

4. Ask the user to enter a choice.

5. If choice is Daily Health Check:

- Read temperature, symptoms, sleep, exercise.

- Store these values in health_record.

- If temperature > 37.5 or symptoms = yes:

Show “Need medical attention”.

Else:

Show “Healthy”.

6. If choice is Fitness Score:

- Check if health_record exists.

- Calculate score using simple rules.

- Display the fitness score.

7. If choice is Schedule Appointment:

- Read date, time, purpose.

- Save these details in the appointment list.

8. If choice is View Appointments:

- Display all appointments in the list.

9. If choice is Exit:

- End the program.

10. Stop.
PYTHON PROGRAM:
health_record = {}

appointments = []

while True:

print("\n--- Campus Health & Fitness Monitoring System ---")

print("1. Daily Health Check")

print("2. Fitness Score")

print("3. Schedule Appointment")

print("4. View Appointments")

print("0. Exit")

choice = input("Enter choice: ")

# 1. DAILY HEALTH CHECK

if choice == "1":

temp = float(input("Enter body temperature (°C): "))

symptoms = input("Any symptoms? (yes/no): ")

sleep = float(input("Hours of sleep: "))

exercise = int(input("Minutes of exercise: "))

health_record = {

"temp": temp,

"symptoms": symptoms,

"sleep": sleep,

"exercise": exercise

if temp > 37.5 or symptoms == "yes":

print("⚠ You may need medical attention.")

else:

print("✔ You look healthy today.")


# 2. FITNESS SCORE

elif choice == "2":

if not health_record:

print("No record found. Do Daily Health Check first.")

else:

score = 100

if health_record["temp"] > 37.5:

score -= 20

if health_record["symptoms"] == "yes":

score -= 20

if health_record["sleep"] < 7:

score -= 10

if health_record["exercise"] < 30:

score -= 10

print("Your Fitness Score:", score)

# 3. SCHEDULE APPOINTMENT

elif choice == "3":

date = input("Enter date (DD-MM-YYYY): ")

time = input("Enter time: ")

purpose = input("Reason for appointment: ")

[Link]({

"date": date,

"time": time,

"purpose": purpose

})

print("✔ Appointment Scheduled.")

# 4. VIEW APPOINTMENTS

elif choice == "4":

if not appointments:
print("No appointments scheduled.")

else:

print("\nAppointments:")

for a in appointments:

print(a['date'], "-", a['time'], "-", a['purpose'])

# EXIT

elif choice == "0":

print("Thank you! Stay Healthy.")

break

else:

print("Invalid option. Try again.")

OUTPUT:
Q2. Develop a customized function suite for CHFMS:
- fitness score function
- health ID generator
- medical notes text-processing function
Integrate into one workflow.

PYTHON PROGRAM:

FUNCTION SUITE:

import random

import string

# -------------------------------

# 1. FITNESS SCORE FUNCTION

# -------------------------------

def fitness_score(temp, symptoms, sleep, exercise):

score = 100

if temp > 37.5:

score -= 20

if symptoms == "yes":

score -= 20

if sleep < 7:

score -= 10

if exercise < 30:

score -= 10

return score

# -------------------------------

# 2. HEALTH ID GENERATOR

# -------------------------------

def generate_health_id(name):
prefix = name[:2].upper()

number = "".join([Link]([Link]) for _ in range(4))

return prefix + number # Example: KI4821

# -------------------------------

# 3. MEDICAL NOTES TEXT-PROCESSING FUNCTION

# -------------------------------

def process_notes(text):

text = [Link]() # remove space

text = [Link]() # first letter capital

text = [Link](" ", " ") # remove double spaces

return text

INTEGRATED WORKFLOW:

# Simple workflow using all custom functions

health_data = {}

appointments = []

print("\n--- Campus Health & Fitness System Workflow ---")

# Step 1: Register student

name = input("Enter student name: ")

health_id = generate_health_id(name)

print("Generated Health ID:", health_id)

# Step 2: Daily health check

temp = float(input("Temperature: "))


symptoms = input("Any symptoms? (yes/no): ")
sleep = float(input("Sleep hours: "))
exercise = int(input("Exercise minutes: "))

# Step 3: Calculate fitness score

score = fitness_score(temp, symptoms, sleep, exercise)


print("Fitness Score:", score)

# Step 4: Add medical notes

notes = input("Enter doctor's medical notes: ")

clean_notes = process_notes(notes)

print("Processed Notes:", clean_notes)

# Save all data


health_data[health_id] = {

"name": name,

"temperature": temp,

"symptoms": symptoms,

"sleep": sleep,

"exercise": exercise,

"fitness_score": score,
"notes": clean_notes

# Step 5: Show summary

print("\n--- Summary ---")

for key, value in health_data[health_id].items():

print(key, ":", value)


OUTPUT:
Q3. Create an integrated health-data framework using lists, tuples, dictionaries, sets to manage:
- health readings
- appointment slots
- unique symptoms
- workout logs.

ALGORITHM:

Step 1: Start
Step 2: Create a list to store daily health readings
Step 3: Create a tuple to store fixed appointment time slots
Step 4: Create a set to store unique symptoms reported
Step 5: Create a dictionary to store workout logs (date → workout)
Step 6: Ask user to enter today’s health reading and add it to list
Step 7: Ask user to enter any symptom and add to set
Step 8: Ask user to pick an appointment slot from tuple
Step 9: Ask user to enter today’s workout and store in dictionary
Step 10: Display all stored health data
Step 11: Stop

FLOWCHART:
┌──────────┐

│ Start │

└─────┬────┘

┌──────────▼──────────┐

│ Create health list │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Create slots tuple │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Create symptom set │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Create workout dict │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Enter health reading │


│ Add to list │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Enter symptom │

│ Add to set │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Select appointment │

│ from tuple │

└──────────┬──────────┘

┌──────────▼──────────┐

│ Enter workout log │

│ Store in dictionary │

└──────────┬──────────┘

┌─────▼─────┐

│ Display │

└─────┬─────┘

┌─────▼─────┐

│ End │

└────────────┘

PYTHON PROGRAM:

# ---------------------------------------------
# CAMPUS HEALTH DATA FRAMEWORK (BEGINNER LEVEL)

# ---------------------------------------------

# 1) HEALTH READINGS (List of Tuples)

# Each tuple = (temperature, sleep hours, exercise minutes)

health_readings = []

# 2) APPOINTMENT SLOTS (Dictionary)


# key = date, value = list of time slots

appointments = {
"25-11-2025": ["10:00 AM", "2:00 PM"],

"26-11-2025": ["11:00 AM"]

# 3) UNIQUE SYMPTOMS (Set)

# Set automatically removes duplicates

symptoms_set = set()

# 4) WORKOUT LOG (List of Dictionaries)

# Each dict = 1 day workout record

workout_logs = []

# ---------------------------------------------

# ADD HEALTH READING

# ---------------------------------------------

def add_health_reading(temp, sleep, exercise, symptoms):

# store reading as a tuple

reading = (temp, sleep, exercise)


health_readings.append(reading)

# store symptoms in set

for s in symptoms:

symptoms_set.add(s)

# ---------------------------------------------

# ADD WORKOUT ENTRY

# ---------------------------------------------
def log_workout(date, minutes, workout_type):

log = {

"date": date,
"minutes": minutes,

"type": workout_type

workout_logs.append(log)

# ---------------------------------------------

# CHECK APPOINTMENTS

# ---------------------------------------------

def view_appointments():

for date, slots in [Link]():

print(date, ":", slots)

# ---------------------------------------------

# SIMPLE WORKFLOW

# ---------------------------------------------

print("\n--- CAMPUS HEALTH FRAMEWORK ---")

# Step 1: Add Health Reading

add_health_reading(

temp = 36.8,

sleep = 7,

exercise = 30,

symptoms = ["cold", "headache"]

# Step 2: Add Workout Log

log_workout("25-11-2025", 45, "Running")

# Step 3: Display All Data

print("\nHealth Readings (List of Tuples):")


print(health_readings)

print("\nUnique Symptoms (Set):")

print(symptoms_set)

print("\nWorkout Logs (List of Dictionaries):")

print(workout_logs)

print("\nAppointment Slots (Dictionary):")

view_appointments()

OUTPUT:
Q4. Develop backend data-processing for CHFMS:
- file handling
- custom modules & package
- Pandas analytics dashboard.
PROJECT LAYOUT:

chfms_backend/

├─ chfms_pkg/

│ ├─ __init__.py

│ ├─ file_io.py # file handling (CSV / JSON helpers)

│ ├─ health_utils.py # core helpers: id generator, fitness score, notes


│ └─ [Link] # pandas analytics & charts

├─ data/

│ └─ sample_health.csv # optional - auto-created if missing

├─ outputs/

│ └─ (charts & reports will be saved here)

└─ run_main.py # simple script to demo the backend

1) chfms_pkg/[Link]

# chfms_pkg/__init__.py

# package init - keep small

__all__ = ["file_io", "health_utils", "analytics"]

2)chfms_pkg/file_io.py

# chfms_pkg/file_io.py

import os

import csv

import json

def ensure_dir(path):

[Link](path, exist_ok=True)

def write_csv(path, fieldnames, rows):

"""

path: full filepath


fieldnames: list of columns

rows: iterable of dicts

"""

ensure_dir([Link](path) or ".")

with open(path, mode="w", newline="", encoding="utf-8") as f:

writer = [Link](f, fieldnames=fieldnames)

[Link]()

for row in rows:

[Link](row)

def append_csv(path, row, fieldnames=None):

"""

Append a single dict row. If file not exists and fieldnames provided, create header.

"""

ensure_dir([Link](path) or ".")

exists = [Link](path)

with open(path, mode="a", newline="", encoding="utf-8") as f:

writer = [Link](f, fieldnames=fieldnames or [Link]())

if not exists:

[Link]()

[Link](row)

def read_csv(path):

"""

Return list of dicts (strings). If file missing, return [].

"""

if not [Link](path):

return []

with open(path, mode="r", encoding="utf-8") as f:

reader = [Link](f)

return [row for row in reader]


def write_json(path, data):

ensure_dir([Link](path) or ".")

with open(path, "w", encoding="utf-8") as f:

[Link](data, f, indent=2)

def read_json(path):

if not [Link](path):

return None

with open(path, "r", encoding="utf-8") as f:

return [Link](f)

3) chfms_pkg/health_utils.py

# chfms_pkg/health_utils.py

import random, string

def generate_health_id(name, prefix="H"):

"""

Create short unique-looking id: prefix + first2letters + 4 digits

Example: H-KI4821

"""

letters = (name[:2].upper() if name else "XX")

digits = "".join([Link]([Link]) for _ in range(4))

return f"{prefix}-{letters}{digits}"

def fitness_score_numeric(temp, symptoms_flag, sleep_hours, exercise_mins):

"""

Simple, explainable scoring (0-100).

symptoms_flag: bool (True if any symptoms)

"""

score = 100

# temp penalties
try:

temp = float(temp)

if temp >= 38.0:

score -= 30

elif temp >= 37.5:

score -= 20

elif temp >= 37.0:

score -= 10

except Exception:

pass

if symptoms_flag:

score -= 20

# sleep

try:

sleep = float(sleep_hours)

if sleep < 5:

score -= 20

elif sleep < 7:

score -= 10

elif sleep > 9:

score -= 5

except Exception:

pass

# exercise

try:

ex = int(exercise_mins)

if ex >= 60:

score += 5
elif ex >= 30:

score += 3

elif ex < 10:

score -= 10

except Exception:

pass

return max(0, min(100, int(score)))

def process_medical_notes(text):

"""

Very small cleaning: strip, normalize spaces, capitalize first letter.

"""

if not text:

return ""

txt = " ".join([Link]().split())

return [Link]()

4) chfms_pkg/[Link]

# chfms_pkg/[Link]

import os

import pandas as pd

import [Link] as plt

def load_health_dataframe(csv_path):

"""

Read csv into a pandas DataFrame and convert some columns.

Expect columns: health_id, name, date, temp, symptoms, sleep, exercise, notes, score

"""

if not [Link](csv_path):

return [Link]() # empty

df = pd.read_csv(csv_path)
# convert types if columns exist

for col in ("temp", "sleep", "exercise", "score"):

if col in [Link]:

df[col] = pd.to_numeric(df[col], errors="coerce")

if "date" in [Link]:

df["date"] = pd.to_datetime(df["date"], errors="coerce")

return df

def summary_stats(df):

"""

Return a small dict summary suitable for console display.

"""

if [Link]:

return {"rows": 0}

stats = {

"rows": len(df),

"avg_temp": float(df["temp"].mean()) if "temp" in [Link] else None,

"avg_sleep": float(df["sleep"].mean()) if "sleep" in [Link] else None,

"avg_exercise": float(df["exercise"].mean()) if "exercise" in [Link] else None,

"avg_score": float(df["score"].mean()) if "score" in [Link] else None,

return stats

def plot_score_trend(df, out_folder="outputs", out_name="score_trend.png"):

"""

Plot mean score per day and save PNG.

"""

[Link](out_folder, exist_ok=True)

if [Link] or "date" not in [Link] or "score" not in [Link]:

return None

daily = [Link](subset=["date", "score"]).groupby(df["date"].[Link])["score"].mean()


[Link](figsize=(6,3))

[Link](marker="o")

[Link]("Average Fitness Score per Day")

[Link]("Date")

[Link]("Score")

plt.tight_layout()

out_path = [Link](out_folder, out_name)

[Link](out_path)

[Link]()

return out_path

def top_symptoms(df, top_n=5):

"""

Return top reported symptoms from 'symptoms' column (comma-separated strings)

"""

if [Link] or "symptoms" not in [Link]:

return []

all_sym = df["symptoms"].dropna().astype(str)

# split and count

from collections import Counter

cnt = Counter()

for s in all_sym:

parts = [[Link]().lower() for p in [Link](",") if [Link]()]

[Link](parts)

return cnt.most_common(top_n)

5)run_main.py

# run_main.py

import os

from datetime import datetime

from chfms_pkg import file_io, health_utils, analytics


DATA_PATH = "data/sample_health.csv"

OUT_DIR = "outputs"

# Create sample data if missing

if not [Link](DATA_PATH):

sample_rows = [

"health_id": "H-KI0001",

"name": "Kishor",

"date": "2025-11-20",

"temp": "36.8",

"symptoms": "none",

"sleep": "7",

"exercise": "30",

"notes": "feeling good",

"score": str(health_utils.fitness_score_numeric(36.8, False, 7, 30))

},

"health_id": "H-RU0002",

"name": "Raju",

"date": "2025-11-20",

"temp": "38.2",

"symptoms": "fever,cough",

"sleep": "5",

"exercise": "5",

"notes": "high fever",

"score": str(health_utils.fitness_score_numeric(38.2, True, 5, 5))

file_io.write_csv(DATA_PATH, fieldnames=list(sample_rows[0].keys()), rows=sample_rows)

print("Created sample data at", DATA_PATH)


# Demo: add a new record (simulate daily check)

name = "New Student"

hid = health_utils.generate_health_id(name)

today = [Link]().date().isoformat()

temp = 36.9

symptoms = "none"

sleep = 8

exercise = 40

score = health_utils.fitness_score_numeric(temp, False, sleep, exercise)

notes = health_utils.process_medical_notes("stable")

new_row = {

"health_id": hid,

"name": name,

"date": today,

"temp": str(temp),

"symptoms": symptoms,

"sleep": str(sleep),

"exercise": str(exercise),

"notes": notes,

"score": str(score)

file_io.append_csv(DATA_PATH, new_row, fieldnames=new_row.keys())

print("Appended new record for", name)

# Run analytics

df = analytics.load_health_dataframe(DATA_PATH)

print("\n--- Analytics Summary ---")

print(analytics.summary_stats(df))
# Create chart

chart_path = analytics.plot_score_trend(df, out_folder=OUT_DIR)

if chart_path:

print("Saved chart to:", chart_path)

# Top symptoms

print("Top symptoms:", analytics.top_symptoms(df))

Q5. Create a functional CHFMS application with Tkinter GUI, DB connectivity, CRUD operations and your
own layout.

PYTHON PROGRAM:

"""
CHFMS - Simple Campus Health & Fitness Monitoring System (Tkinter + SQLite)

Save as: chfms_tk.py

Run: python chfms_tk.py

Features:

- SQLite DB stored in file '[Link]'


- Tables: students, health_records, appointments

- CRUD operations for students, health records (daily check), appointments

- Simple fitness scoring and a small analytics area

- Beginner-friendly code with comments


"""

import sqlite3

from datetime import datetime


import random

import string
import tkinter as tk

from tkinter import ttk, messagebox, simpledialog


DB_FILE = "[Link]"

# -------------------------
# Database helper functions

# -------------------------

def init_db():

con = [Link](DB_FILE)

cur = [Link]()

[Link]("""

CREATE TABLE IF NOT EXISTS students (

id INTEGER PRIMARY KEY AUTOINCREMENT,


health_id TEXT UNIQUE,

name TEXT,

age INTEGER,

gender TEXT

""")

[Link]("""
CREATE TABLE IF NOT EXISTS health_records (

id INTEGER PRIMARY KEY AUTOINCREMENT,

student_id INTEGER,

date TEXT,

temp REAL,

symptoms TEXT,

sleep REAL,
exercise INTEGER,

notes TEXT,

score INTEGER,
FOREIGN KEY(student_id) REFERENCES students(id)

""")
[Link]("""

CREATE TABLE IF NOT EXISTS appointments (

id INTEGER PRIMARY KEY AUTOINCREMENT,

student_id INTEGER,
date TEXT,

time TEXT,

purpose TEXT,

created_at TEXT,

FOREIGN KEY(student_id) REFERENCES students(id)

""")

[Link]()
[Link]()

def get_connection():

return [Link](DB_FILE)

# -------------------------

# Utility functions

# -------------------------

def generate_health_id(name, prefix="H"):

letters = (name[:2].upper() if name else "XX")

digits = "".join([Link]([Link]) for _ in range(4))

return f"{prefix}-{letters}{digits}"

def fitness_score_numeric(temp, symptoms_flag, sleep_hours, exercise_mins):


score = 100

try:

temp = float(temp)
if temp >= 38.0:

score -= 30

elif temp >= 37.5:

score -= 20
elif temp >= 37.0:

score -= 10

except Exception:

pass

if symptoms_flag:

score -= 20

try:

sleep = float(sleep_hours)

if sleep < 5:

score -= 20

elif sleep < 7:

score -= 10

elif sleep > 9:


score -= 5

except Exception:

pass

try:

ex = int(exercise_mins)

if ex >= 60:
score += 5

elif ex >= 30:

score += 3
elif ex < 10:

score -= 10

except Exception:
pass

return max(0, min(100, int(score)))

# -------------------------

# App GUI

# -------------------------

class CHFMSApp([Link]):

def __init__(self):

super().__init__()

[Link]("CHFMS - Campus Health & Fitness Monitoring System")


[Link]("900x520")

[Link](False, False)

# Initialize DB

init_db()

# Left frame: student list and student actions


left = [Link](self, padding=8)

[Link](side=[Link], fill=tk.Y)

[Link](left, text="Students", font=("Arial", 12, "bold")).pack(anchor=tk.W)

self.student_list = [Link](left, width=24, height=25)

self.student_list.pack(pady=6)
self.student_list.bind("<<ListboxSelect>>", self.on_student_select)

btn_frame = [Link](left)
btn_frame.pack(pady=8, fill=tk.X)

[Link](btn_frame, text="Add", command=self.add_student).pack(side=[Link],


expand=True, fill=tk.X)
[Link](btn_frame, text="Edit", command=self.edit_student).pack(side=[Link],
expand=True, fill=tk.X)

[Link](btn_frame, text="Delete", command=self.delete_student).pack(side=[Link],


expand=True, fill=tk.X)

# Right frame: notebook with tabs

right = [Link](self, padding=8)

[Link](side=[Link], fill=[Link], expand=True)

[Link] = [Link](right)

[Link](fill=[Link], expand=True)

# Tab 1: Health Check / Records

self.tab_records = [Link]([Link], padding=8)

[Link](self.tab_records, text="Health Records")

self._build_records_tab(self.tab_records)

# Tab 2: Appointments

self.tab_appt = [Link]([Link], padding=8)

[Link](self.tab_appt, text="Appointments")

self._build_appointments_tab(self.tab_appt)

# Tab 3: Analytics / Summary

self.tab_analytics = [Link]([Link], padding=8)

[Link](self.tab_analytics, text="Analytics")

self._build_analytics_tab(self.tab_analytics)

# Load students into listbox


self.load_students()
# -------------------------

# Student CRUD

# -------------------------

def load_students(self):
self.student_list.delete(0, [Link])

con = get_connection()

cur = [Link]()

[Link]("SELECT id, health_id, name FROM students ORDER BY name")

rows = [Link]()

self.students_cache = {} # id -> (health_id, name)

for r in rows:

sid, hid, name = r


self.students_cache[sid] = (hid, name)

self.student_list.insert([Link], f"{name} ({hid})")

[Link]()

# Clear selection details

self.selected_student_id = None

self.clear_record_fields()

self.clear_appointments_view()
self.update_analytics()

def add_student(self):

# small dialog sequence

name = [Link]("Add Student", "Enter student name:", parent=self)

if not name:

return
try:

age = int([Link]("Add Student", "Enter age:", parent=self) or "0")

except ValueError:
age = 0

gender = [Link]("Add Student", "Enter gender (M/F/Other):", parent=self) or


""
hid = generate_health_id(name)

con = get_connection()

cur = [Link]()
try:

[Link]("INSERT INTO students (health_id, name, age, gender) VALUES (?, ?, ?, ?)",

(hid, name, age, gender))

[Link]()

[Link]("Success", f"Student added with Health ID {hid}")

except [Link]:

[Link]("Error", "Health ID conflict. Try again.")

finally:
[Link]()

self.load_students()

def edit_student(self):

sid = self.get_selected_student_dbid()

if not sid:

[Link]("No selection", "Select a student first.")


return

con = get_connection()

cur = [Link]()

[Link]("SELECT name, age, gender FROM students WHERE id=?", (sid,))

row = [Link]()

[Link]()

if not row:
[Link]("Error", "Student not found.")

return

cur_name, cur_age, cur_gender = row


name = [Link]("Edit Student", "Name:", initialvalue=cur_name, parent=self)

if not name:

return
try:

age = int([Link]("Edit Student", "Age:", initialvalue=str(cur_age),


parent=self) or cur_age)

except ValueError:

age = cur_age

gender = [Link]("Edit Student", "Gender:", initialvalue=cur_gender,


parent=self) or cur_gender

con = get_connection()

cur = [Link]()
[Link]("UPDATE students SET name=?, age=?, gender=? WHERE id=?", (name, age,
gender, sid))

[Link]()
[Link]()
[Link]("Updated", "Student updated.")

self.load_students()

def delete_student(self):

sid = self.get_selected_student_dbid()

if not sid:
[Link]("No selection", "Select a student first.")

return

if not [Link]("Confirm", "Delete student and all related records?"):

return

con = get_connection()

cur = [Link]()

[Link]("DELETE FROM health_records WHERE student_id=?", (sid,))


[Link]("DELETE FROM appointments WHERE student_id=?", (sid,))

[Link]("DELETE FROM students WHERE id=?", (sid,))

[Link]()

[Link]()
[Link]("Deleted", "Student and related data removed.")

self.load_students()
def get_selected_student_dbid(self):

sel = self.student_list.curselection()

if not sel:

return None
# we stored students_cache ordered by query; map index to db id

idx = sel[0]

# rebuild mapping: index -> id

con = get_connection()

cur = [Link]()

[Link]("SELECT id FROM students ORDER BY name")

ids = [r[0] for r in [Link]()]

[Link]()
if idx < len(ids):

return ids[idx]

return None

def on_student_select(self, event):

sid = self.get_selected_student_dbid()

self.selected_student_id = sid
self.load_records_for_student()

self.load_appointments_for_student()

self.update_analytics()

# -------------------------

# Records tab

# -------------------------
def _build_records_tab(self, parent):

left = [Link](parent)

[Link](side=[Link], fill=tk.Y, padx=6, pady=6)

[Link](left, text="Daily Health Check", font=("Arial", 11, "bold")).pack(anchor=tk.W)


lbl_temp = [Link](left, text="Temperature (°C)")

lbl_temp.pack(anchor=tk.W, pady=(6, 0))

self.entry_temp = [Link](left, width=18)

self.entry_temp.pack()

lbl_sym = [Link](left, text="Symptoms (comma-separated or 'none')")

lbl_sym.pack(anchor=tk.W, pady=(6, 0))

self.entry_sym = [Link](left, width=18)

self.entry_sym.pack()

lbl_sleep = [Link](left, text="Sleep hours")

lbl_sleep.pack(anchor=tk.W, pady=(6, 0))


self.entry_sleep = [Link](left, width=18)

self.entry_sleep.pack()

lbl_ex = [Link](left, text="Exercise minutes")

lbl_ex.pack(anchor=tk.W, pady=(6, 0))

self.entry_ex = [Link](left, width=18)

self.entry_ex.pack()

lbl_notes = [Link](left, text="Notes")

lbl_notes.pack(anchor=tk.W, pady=(6, 0))

self.entry_notes = [Link](left, width=18)

self.entry_notes.pack()

[Link](left, text="Save Record", command=self.save_health_record).pack(pady=10,


fill=tk.X)

[Link](left, text="Delete Selected Record",


command=self.delete_selected_record).pack(fill=tk.X)

# Right side: records treeview


right = [Link](parent)

[Link](side=[Link], fill=[Link], expand=True, padx=6, pady=6)


[Link](right, text="Health Records", font=("Arial", 11, "bold")).pack(anchor=tk.W)

cols = ("id", "date", "temp", "symptoms", "sleep", "exercise", "score")

self.records_tree = [Link](right, columns=cols, show="headings", height=14)


for c in cols:

self.records_tree.heading(c, text=[Link]())

self.records_tree.column(c, width=90 if c != "symptoms" else 180, anchor=[Link])

self.records_tree.pack(fill=[Link], expand=True)

self.records_tree.bind("<<TreeviewSelect>>", self.on_record_select)

def clear_record_fields(self):

self.entry_temp.delete(0, [Link])
self.entry_sym.delete(0, [Link])

self.entry_sleep.delete(0, [Link])

self.entry_ex.delete(0, [Link])

self.entry_notes.delete(0, [Link])

for i in self.records_tree.get_children():

self.records_tree.delete(i)

def save_health_record(self):

sid = getattr(self, "selected_student_id", None)

if not sid:

[Link]("No student", "Please select a student first.")

return

temp = self.entry_temp.get().strip()

symptoms = self.entry_sym.get().strip() or "none"


sleep = self.entry_sleep.get().strip() or "0"

exercise = self.entry_ex.get().strip() or "0"

notes = self.entry_notes.get().strip()
symptoms_flag = ([Link]() != "none" and symptoms != "")

score = fitness_score_numeric(temp or 0, symptoms_flag, sleep, exercise)

date = [Link]().date().isoformat()
con = get_connection()

cur = [Link]()

[Link]("""INSERT INTO health_records


(student_id, date, temp, symptoms, sleep, exercise, notes, score)

VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",

(sid, date, temp, symptoms, sleep, exercise, notes, score))

[Link]()

[Link]()

[Link]("Saved", f"Record saved (Score: {score}).")

self.load_records_for_student()

self.update_analytics()

def load_records_for_student(self):

self.clear_record_fields()

sid = getattr(self, "selected_student_id", None)

if not sid:

return

con = get_connection()
cur = [Link]()

[Link]("""SELECT id, date, temp, symptoms, sleep, exercise, score

FROM health_records WHERE student_id=? ORDER BY date DESC""", (sid,))

rows = [Link]()

[Link]()

for r in rows:

self.records_tree.insert("", [Link], values=r)

def on_record_select(self, event):

sel = self.records_tree.selection()
if not sel:

return

vals = self.records_tree.item(sel[0], "values")


# id, date, temp, symptoms, sleep, exercise, score

_, date, temp, symptoms, sleep, exercise, score = vals

# fill left form so user can edit and re-save if desired (simple approach: delete+recreate)

self.entry_temp.delete(0, [Link])
self.entry_temp.insert(0, temp)

self.entry_sym.delete(0, [Link])

self.entry_sym.insert(0, symptoms)

self.entry_sleep.delete(0, [Link])

self.entry_sleep.insert(0, sleep)

self.entry_ex.delete(0, [Link])

self.entry_ex.insert(0, exercise)

# notes not shown in tree - leave blank

def delete_selected_record(self):

sel = self.records_tree.selection()

if not sel:

[Link]("No selection", "Select a record first.")

return

vals = self.records_tree.item(sel[0], "values")


rid = vals[0]

if not [Link]("Confirm", "Delete selected health record?"):

return

con = get_connection()

cur = [Link]()

[Link]("DELETE FROM health_records WHERE id=?", (rid,))

[Link]()
[Link]()

self.load_records_for_student()

self.update_analytics()
[Link]("Deleted", "Record deleted.")

# -------------------------
# Appointments Tab

# -------------------------

def _build_appointments_tab(self, parent):

top = [Link](parent)
[Link](side=[Link], fill=tk.X, padx=6, pady=6)

[Link](top, text="Date (YYYY-MM-DD)").grid(row=0, column=0, padx=4, pady=2)

self.appt_date = [Link](top, width=12)

self.appt_date.grid(row=0, column=1, padx=4)

[Link](top, text="Time (HH:MM)").grid(row=0, column=2, padx=4, pady=2)

self.appt_time = [Link](top, width=10)


self.appt_time.grid(row=0, column=3, padx=4)

[Link](top, text="Purpose").grid(row=0, column=4, padx=4, pady=2)

self.appt_purpose = [Link](top, width=20)

self.appt_purpose.grid(row=0, column=5, padx=4)

[Link](top, text="Schedule", command=self.schedule_appointment).grid(row=0,


column=6, padx=6)

# list of appointments (treeview)

cols = ("id", "date", "time", "purpose", "created_at")


self.appt_tree = [Link](parent, columns=cols, show="headings", height=18)

for c in cols:

self.appt_tree.heading(c, text=[Link]())

self.appt_tree.column(c, width=110, anchor=[Link])

self.appt_tree.pack(fill=[Link], expand=True, padx=6, pady=(4,6))

self.appt_tree.bind("<Delete>", lambda e: self.delete_selected_appointment())

btns = [Link](parent)

[Link](fill=tk.X, padx=6, pady=4)


[Link](btns, text="Delete Appointment",
command=self.delete_selected_appointment).pack(side=[Link])

[Link](btns, text="Refresh",
command=self.load_appointments_for_student).pack(side=[Link], padx=6)

def schedule_appointment(self):

sid = getattr(self, "selected_student_id", None)

if not sid:

[Link]("No student", "Select a student first.")


return

date = self.appt_date.get().strip()

time = self.appt_time.get().strip()

purpose = self.appt_purpose.get().strip() or "General"

created_at = [Link]().isoformat(timespec="seconds")

con = get_connection()

cur = [Link]()
[Link]("INSERT INTO appointments (student_id, date, time, purpose, created_at)
VALUES (?, ?, ?, ?, ?)",

(sid, date, time, purpose, created_at))


[Link]()

[Link]()

[Link]("Scheduled", "Appointment added.")

self.load_appointments_for_student()

def load_appointments_for_student(self):

# clear
for i in self.appt_tree.get_children():

self.appt_tree.delete(i)

sid = getattr(self, "selected_student_id", None)

if not sid:
return

con = get_connection()

cur = [Link]()
[Link]("SELECT id, date, time, purpose, created_at FROM appointments WHERE
student_id=? ORDER BY date DESC",

(sid,))

rows = [Link]()

[Link]()

for r in rows:

self.appt_tree.insert("", [Link], values=r)

def clear_appointments_view(self):

for i in self.appt_tree.get_children():

self.appt_tree.delete(i)

def delete_selected_appointment(self):

sel = self.appt_tree.selection()
if not sel:

[Link]("No selection", "Select an appointment first.")

return

vals = self.appt_tree.item(sel[0], "values")

aid = vals[0]

if not [Link]("Confirm", "Delete selected appointment?"):

return
con = get_connection()

cur = [Link]()
[Link]("DELETE FROM appointments WHERE id=?", (aid,))

[Link]()

[Link]()

self.load_appointments_for_student()

[Link]("Deleted", "Appointment deleted.")

# -------------------------
# Analytics Tab

# -------------------------
def _build_analytics_tab(self, parent):

[Link](parent, text="Analytics Summary", font=("Arial", 12, "bold")).pack(anchor=tk.W,


padx=6, pady=6)

self.analytics_text = [Link](parent, height=18, wrap=[Link])

self.analytics_text.pack(fill=[Link], expand=True, padx=6, pady=(0,6))

[Link](parent, text="Refresh Analytics", command=self.update_analytics).pack(padx=6,


pady=(0,6))

def update_analytics(self):
# simple analytics: average score, last record, top symptoms (simple)

con = get_connection()

cur = [Link]()

[Link]("SELECT COUNT(*) FROM students")

total_students = [Link]()[0]

[Link]("SELECT AVG(score) FROM health_records")

avg_score = [Link]()[0]
[Link]("SELECT date, score FROM health_records ORDER BY date DESC LIMIT 1")

last = [Link]()

[Link]("SELECT symptoms FROM health_records WHERE symptoms IS NOT NULL")

all_sym = [r[0] for r in [Link]() if r[0]]

[Link]()

# compute simple symptom counts

from collections import Counter


cnt = Counter()

for s in all_sym:

parts = [[Link]().lower() for p in [Link](",") if [Link]()]

[Link](parts)

top_symptoms = ", ".join(f"{k}({v})" for k, v in cnt.most_common(5))

self.analytics_text.delete(1.0, [Link])
self.analytics_text.insert([Link], f"Total students: {total_students}\n")
self.analytics_text.insert([Link], f"Average fitness score (all records): {avg_score:.1f}\n" if
avg_score else "Average fitness score (all records): N/A\n")

if last:

self.analytics_text.insert([Link], f"Last record: Date: {last[0]}, Score: {last[1]}\n")

else:

self.analytics_text.insert([Link], "Last record: N/A\n")

self.analytics_text.insert([Link], f"Top symptoms: {top_symptoms or 'None'}\n\n")


self.analytics_text.insert([Link], "Tip: Select a student on the left to see individual records &
appointments.\n")

# -------------------------

# Application close

# -------------------------

def on_close(self):

if [Link]("Quit", "Do you want to quit?"):

[Link]()

# -------------------------

# Run the app

# -------------------------

if __name__ == "__main__":

app = CHFMSApp()

[Link]("WM_DELETE_WINDOW", app.on_close)
[Link]()

OUTPUT:

Common questions

Powered by AI

The Campus Health & Fitness Monitoring System provides functionalities for student registration, daily health checks, fitness score calculation, medical notes processing, health data storage and management, and the scheduling of appointments. The system generates unique health IDs, calculates fitness scores based on temperature, symptoms, sleep, and exercise, processes medical notes, and stores information in a structured health data framework. Additionally, it integrates a file-handling and data-processing backend, analytics dashboard using Pandas, and allows for CRUD operations on student records and health-related events.

The system ensures data integrity and proper functionality through its modular backend design comprising file handling, utilities, and analytics. By employing files for storing health records in CSV and JSON formats, with checks to create directories if missing, the system maintains data organization and accessibility. It uses custom modules for health ID generation and fitness score calculations and defines clear processes for writing to and reading from files, thereby reducing errors. It employs Pandas for analytics operations, allowing robust data manipulation and visualization, and follows a structured project layout for scalability and maintenance.

The fitness score is calculated starting from a base of 100. The score is decreased by 20 if the temperature is over 37.5 degrees, by 20 if symptoms are present, by 10 if sleep is less than 7 hours, and by 10 if exercise is less than 30 minutes. Modifications are made based on conditions, such as increasing the score for more exercise and reducing it under various sleep conditions. This framework helps assess an individual's health status.

The health ID generation function combines a prefix, the first two letters of the student's name in uppercase, and a random sequence of four digits to create a unique and identifiable health ID (e.g., H-KI4821). This design leverages randomness and a standardized format, reducing the likelihood of duplications and ensuring ease of use for identification and data indexing.

The system uses an organized GUI design with components like notebooks and tabs to separate functionalities (records, appointments, and analytics), and entry widgets to ease input processes. Interaction feedback, such as warnings and confirmations for data transactions (e.g., saving or deleting records), enhance user acknowledgment and prevent errors. Dropdown selections and auto-filled entry fields streamline user interactions, and comprehensive layout designs visually guide users through operations, ensuring a seamless and intuitive interface.

The system incorporates error-handling measures such as data validation during input (e.g., ensuring correct data types for health metrics), exception handling within scoring functions, and using default values to manage missing inputs (like setting symptoms to 'none'). Additionally, it checks file existence before operations to prevent access errors and employs Pandas coercion methods for type conversion, avoiding processing disruptions.

The application uses a Tkinter-based GUI interface for managing student health records. It allows CRUD operations—adding, editing, and deleting student records through a series of prompts and command widgets. The interface organizes data using frames and tree views, enabling users to easily navigate and select records. Health data entries, such as temperature, symptoms, and exercise, are inputted via entry widgets, and records are saved to a database for retrieval and analysis. This interface design ensures an intuitive user experience and comprehensive data management.

Custom modules play a pivotal role in the architecture of the Campus Health & Fitness Monitoring System by compartmentalizing different functionalities into reusable components. This approach enhances maintainability, scalability, and clarity. Modules such as 'file_io' manage file operations, 'health_utils' provide core functionalities like ID generation and scoring, and 'analytics' handle data analysis and visualization. These modules enable the decoupling of components, facilitating independent updates and testing, while maintaining coherent integration within the system's workflow.

The system utilizes Pandas in its analytics module to load CSV health data into DataFrames, enabling efficient data manipulation, summary statistics calculation (like average temperature, sleep, exercise, and score), and trend visualization (e.g., plotting average fitness scores over time). The use of Pandas facilitates handling large datasets, ensuring computations are fast, reliable, and can be extended to various analytical functions and visualizations, which enhances insights into health trends for timely interventions.

The health data framework employs various data structures: a list is used to store daily health readings as tuples, which include temperature, sleep hours, and exercise minutes. A dictionary is used for appointment slots, where each key (date) maps to a list of time slots. A set is utilized for storing unique symptoms to automatically eliminate duplicates, and workout logs are managed by a list of dictionaries, each containing a day's workout record with details such as date, minutes, and type.

You might also like