Coding study/python

2024-10-11 파이썬으로 운동일지 만들어보기!(1)

rwg5565 2024. 10. 11. 18:34

!나만의 운동일지 만들어보기!

 

 

  1. 운동 데이터베이스 구축
  2. 운동 루틴 추천
  3. 컴퓨터 비전을 통한 실시간 자세 분석
  4. 자연어 처리 기능

우선 운동일지를 작성 할 수 있는 코드를 python으로 만들었습니다

import csv
from datetime import datetime

# 사용자가 운동을 기록할 수 있는 함수
def record_exercise():
    # 사용자로부터 운동 정보 입력받기
    exercise_name = input("운동 이름을 입력하세요: ")
    muscle_group = input("운동 부위를 입력하세요: ")
    difficulty = input("운동 난이도를 입력하세요 (예: 초급, 중급, 고급): ")
    sets = int(input("세트 수를 입력하세요: "))
    reps = int(input("반복 횟수를 입력하세요: "))
    weight = input("중량을 입력하세요: ")

    # 오늘 날짜 기록
    today = datetime.now().strftime('%Y-%m-%d')

    # CSV 파일에 운동 기록 저장
    with open('user_exercise_records.csv', mode='a', newline='') as file:
        writer = csv.DictWriter(file, fieldnames=["date", "name", "muscle_group", "difficulty", "sets", "reps", "weight", "description"])
        if file.tell() == 0:  # 파일이 비어있으면 헤더 작성
            writer.writeheader()

        writer.writerow({
            "date": today,
            "name": exercise_name,
            "muscle_group": muscle_group,
            "difficulty": difficulty,
            "sets": sets,
            "reps": reps,
            "weight": weight,
            "description": ""  # 설명 필드가 필요할 경우 추가
        })
   
    print(f"{exercise_name} 운동 기록이 저장되었습니다.")

# 기록된 운동 데이터를 조회하는 함수
def view_exercise_records():
    try:
        with open('user_exercise_records.csv', mode='r') as file:
            reader = csv.DictReader(file)
           
            print("기록된 운동 데이터:")
            print(f"{'날짜':<12} {'운동 이름':<15} {'운동 부위':<10} {'난이도':<6} {'세트':<4} {'반복 횟수':<5} {'중량':<6}")
            print("-" * 80)
           
            # CSV 파일을 읽어 운동 기록 출력
            for row in reader:
                print(f"{row['date']:<12} {row['name']:<15} {row['muscle_group']:<10} {row['difficulty']:<6} {row['sets']:<4} {row['reps']:<5} {row['weight']:<6}")
    except FileNotFoundError:
        print("운동 기록 파일을 찾을 수 없습니다. 먼저 운동 기록을 저장해 주세요.")

# 기록된 운동 데이터 조회
view_exercise_records()

# 사용자로부터 운동 기록을 입력받아 저장하는 함수 호출
record_exercise()

결과:

중량을 입력하세요: 60
벤치 운동 기록이 저장되었습니다.
(.venv)
KJI@DESKTOP-I09HHBD MINGW64 C:/Users/KJI/AppData/Local/Programs/Microsoft VS Code
$ python wl.py
기록된 운동 데이터:
날짜           운동 이름           운동 부위      난이도    세트   반복 횟수 중량
--------------------------------------------------------------------------------
2024-10-11   벤치              가슴         초급     3    10    60

이런 느낌으로 완성 되었는데요

이것을 앱으로 사용 할 수 있게 바꿔보고 싶었습니다. 하지만 window 에서 ios 앱 개발은 불가능 하다고 하네요 .. 나중에 돈 모아서 맥북도 하나 사야겠습니다 ㅋㅋㅋ 해보고 싶은게 너무 많아요,,

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.core.window import Window
from kivy.core.text import LabelBase
import csv
from datetime import datetime

# 사용자 정의 폰트 등록 (폰트 파일 경로 수정)
LabelBase.register(name="NotoSans", fn_regular="NotoSansKR-VariableFont_wght.ttf")

class WorkoutApp(App):
    def build(self):
        # 창 배경색을 흰색으로 설정
        Window.clearcolor = (1, 1, 1, 1)  # 흰색 배경

        # 메인 레이아웃
        self.layout = BoxLayout(orientation='vertical', padding=10, spacing=10)

        # 입력 필드 생성
        self.exercise_input = self.create_text_input("운동 이름:")
        self.muscle_group_input = self.create_text_input("운동 부위:")
        self.difficulty_input = self.create_text_input("난이도 (초급/중급/고급):")
        self.sets_input = self.create_text_input("세트 수:")
        self.reps_input = self.create_text_input("반복 횟수:")
        self.weight_input = self.create_text_input("중량 (예: 20kg):")

        # 운동 기록 저장 버튼
        save_button = Button(text="운동 기록 저장", size_hint_y=None, height=50, background_color=(0.3, 0.6, 1, 1), color=(1, 1, 1, 1), font_name="NotoSans")
        save_button.bind(on_press=self.record_exercise)
        self.layout.add_widget(save_button)

        # 기록된 운동 조회 버튼
        view_button = Button(text="기록된 운동 조회", size_hint_y=None, height=50, background_color=(0.2, 0.8, 0.2, 1), color=(1, 1, 1, 1), font_name="NotoSans")
        view_button.bind(on_press=self.view_exercise_records)
        self.layout.add_widget(view_button)

        return self.layout

    # 텍스트 입력 필드 생성 함수
    def create_text_input(self, label_text):
        box = BoxLayout(orientation='horizontal', size_hint_y=None, height=40)
        label = Label(text=label_text, size_hint_x=0.4, font_name="NotoSans", color=(0, 0, 0, 1))  # 텍스트 색 검정
        text_input = TextInput(multiline=False, size_hint_x=0.6, background_color=(0.9, 0.9, 0.9, 1), foreground_color=(0, 0, 0, 1))  # 입력 필드 색상 조정
        box.add_widget(label)
        box.add_widget(text_input)
        self.layout.add_widget(box)
        return text_input

    # 운동 기록 저장 함수
    def record_exercise(self, instance):
        exercise_name = self.exercise_input.text
        muscle_group = self.muscle_group_input.text
        difficulty = self.difficulty_input.text
        sets = self.sets_input.text
        reps = self.reps_input.text
        weight = self.weight_input.text

        today = datetime.now().strftime('%Y-%m-%d')

        # CSV 파일에 운동 기록 저장
        with open('user_exercise_records.csv', mode='a', newline='') as file:
            writer = csv.DictWriter(file, fieldnames=["date", "name", "muscle_group", "difficulty", "sets", "reps", "weight", "description"])
            if file.tell() == 0:
                writer.writeheader()

            writer.writerow({
                "date": today,
                "name": exercise_name,
                "muscle_group": muscle_group,
                "difficulty": difficulty,
                "sets": sets,
                "reps": reps,
                "weight": weight,
                "description": ""
            })

        self.show_popup("운동 기록", f"{exercise_name} 운동 기록이 저장되었습니다.")

    # 운동 기록 조회 함수
    def view_exercise_records(self, instance):
        try:
            with open('user_exercise_records.csv', mode='r') as file:
                reader = csv.DictReader(file)

                records = "기록된 운동 데이터:\n"
                records += f"{'날짜':<12} {'운동 이름':<15} {'운동 부위':<10} {'난이도':<6} {'세트':<4} {'반복 횟수':<5} {'중량':<6}\n"
                records += "-" * 80 + "\n"

                for row in reader:
                    records += f"{row['date']:<12} {row['name']:<15} {row['muscle_group']:<10} {row['difficulty']:<6} {row['sets']:<4} {row['reps']:<5} {row['weight']:<6}\n"
               
                self.show_popup("운동 기록 조회", records)

        except FileNotFoundError:
            self.show_popup("오류", "운동 기록 파일을 찾을 수 없습니다. 먼저 운동 기록을 저장해 주세요.")

    # 팝업 메시지 표시 함수
    def show_popup(self, title, message):
        popup_layout = BoxLayout(orientation='vertical', padding=10)
        message_label = Label(text=message, font_name="NotoSans", color=(0, 0, 0, 1))  # 텍스트 검정
        close_button = Button(text="닫기", size_hint_y=None, height=50, font_name="NotoSans")  # 팝업 버튼 폰트 적용

        popup_layout.add_widget(message_label)
        popup_layout.add_widget(close_button)

        popup = Popup(title=title, content=popup_layout, size_hint=(0.8, 0.8))
        close_button.bind(on_press=popup.dismiss)
        popup.open()

# 앱 실행
if __name__ == '__main__':
    WorkoutApp().run()

실행 결과

이런식으로 깔끔하게 뜨네요 폰트는 NotoSansKR-VariableFont 사용했습니다