-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__main__.py
More file actions
252 lines (187 loc) · 9.7 KB
/
__main__.py
File metadata and controls
252 lines (187 loc) · 9.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import customtkinter as ctk
import sqlite3
import pandas as pd
import matplotlib.pyplot as plt
import os
class App(ctk.CTk):
def __init__(self):
super().__init__()
self.db = Database()
self.calculator = Calculator()
self.history_options = self.db.get_saved_selections()
self.xcl = None
self.main_directory_handler()
# window
self.title("")
self.iconbitmap('icons/empty.ico')
self.resizable(False, False)
self.geometry("700x700")
# widgets
self.grid_rowconfigure((0,1,2,3), weight=1)
self.grid_columnconfigure((0,1,2,3,4,5), weight=1)
self.label = ctk.CTkLabel(self, text="Workout Manager", font=("Arial", 30), text_color="#DDDDDD", justify='center')
self.label.grid( column=0, columnspan=6)
# XCL LINK ENTRY
self.entry = ctk.CTkEntry(self, width=300, height=50, font=("Arial", 20), placeholder_text="Entry your Excel link", text_color="#DDDDDD", placeholder_text_color= "#AAAAAA")
self.entry.grid(row=1, column=0, columnspan=6, sticky='ew', padx='10')
self.excel_btn = ctk.CTkButton(self,text="Choose Excel link", command=lambda:self.activate_day_choice(self.entry.get()))
self.excel_btn.grid(row=1, column=3, pady=(150,0))
# HISTORY
self.history_combo = ctk.CTkComboBox(self, values=self.history_options, dropdown_font=("Arial", 20), dropdown_text_color="#DDDDDD", justify='center',state="readonly", command=lambda value: self.change_entry_value(value))
self.history_combo.grid(row=1, column=0,columnspan=3, pady=(150,0))
self.save_to_history_btn = ctk.CTkButton(self, text="save link", command=lambda: self.redirect_history_saver(self.entry.get()))
self.save_to_history_btn.grid(row=1, column=4, pady=(150,0))
self.delete_histoty_btn = ctk.CTkButton(self, text="delete link", command=lambda: self.redirect_history_deleter(self.history_combo.get()))
self.delete_histoty_btn.grid(row=1, column=5, pady=(150,0))
# DAY CHOICE
self.day_combo = ctk.CTkComboBox(self, dropdown_font=("Arial", 20), dropdown_text_color="#DDDDDD", justify='center',values=[], state="disabled")
self.day_combo.grid(row = 2, column=1, columnspan=3)
self.day_btn = ctk.CTkButton(self,text="Chose this day", state="disabled", command=lambda: self.read_day_combobox(self.day_combo.get()))
self.day_btn.grid(row=2, column=3, columnspan=3)
self.day_message = []
self.day_label = ctk.CTkLabel(self, text="Chose your Excel link\nFor the day choosing option to activate", font=("Arial", 30), fg_color='transparent', text_color='#555')
self.day_label.grid(row=2, column=0, columnspan=6,padx=75)
# Changes entry text variable after choosing an excel link from history
def change_entry_value(self, new_value: str) -> None:
self.entry.delete(0, 'end')
self.entry.insert(0, new_value)
def redirect_history_saver(self, link: str)-> None:
if link == "" or link in self.history_options: return
self.db.save_selection(link)
self.refresh_history_combo()
def redirect_history_deleter(self, link: str) -> None:
if link == "" or link not in self.history_options: return
self.db.delete_history_row(link)
self.refresh_history_combo()
def main_directory_handler(self) -> None:
folder_name = 'figures'
main_dir = os.path.join(os.path.dirname(__file__), folder_name)
if not os.path.isdir(folder_name): os.mkdir(main_dir)
def subdirectory_handler(self,wo_type: str) -> None:
sub_dir = os.path.join(os.path.dirname(__file__), 'figures', wo_type)
if not os.path.isdir(sub_dir): os.mkdir(sub_dir)
def read_day_combobox(self,choice: str) -> None:
choices = self.day_combo.cget("values")
choices.remove(choice)
self.day_combo.configure(values=choices)
self.day_combo.set("")
day = int(choice[0])
self.day_choice(day)
def day_choice(self,day) -> None:
wo_types = self.xcl.sheet_names if day == 0 else [self.xcl.sheet_names[day-1]]
for wo_type in wo_types:
self.subdirectory_handler(wo_type)
workout_data = pd.read_excel(self.xcl, sheet_name=wo_type)
self.calculator.update_workout(workout_data, wo_type)
self.day_message.append(f"{wo_type} updated")
self.day_label.configure(text=("\n".join(self.day_message)), font=("Arial", 15))
self.day_label.grid(row=2, column=0, columnspan=6, padx=75, pady=(150,0))
def activate_day_choice(self,url: str) -> None:
self.day_label.configure(text="Please wait till conection is established")
try:
self.xcl = pd.ExcelFile(url, engine='openpyxl')
except:
self.day_label.configure(text="There was an error while connecting\nCheck your link or internet connection", padx=75)
return None
choices = []
choices.append("0.Update all days")
for num, wo_type in enumerate(self.xcl.sheet_names):
choices.append(f"{num + 1}.Update {num + 1} day ({wo_type})")
self.day_combo.configure(values=choices,state="readonly")
self.day_btn.configure(state="normal")
self.day_label.configure(text="")
def refresh_history_combo(self):
self.history_combo.configure(values=[])
self.history_options = self.db.get_saved_selections()
self.history_combo.configure(values=self.history_options)
self.history_combo.set("")
class Database:
def __init__(self):
pass
def delete_history_row(self, link: str) -> None:
with sqlite3.connect('history/history.db') as conn:
c = conn.cursor()
c.execute("DELETE FROM links WHERE link = ?", (link,))
conn.commit()
def save_selection(self,link):
with sqlite3.connect('history/history.db') as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS links (id INTEGER PRIMARY KEY, link TEXT)")
conn.commit()
c.execute("INSERT INTO links (link) VALUES (?)", (link,))
conn.commit()
def get_saved_selections(self):
with sqlite3.connect('history/history.db') as conn:
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS links (id INTEGER PRIMARY KEY, link TEXT)")
c.execute("SELECT * FROM links")
rows = c.fetchall()
options = []
for row in rows:
options.append(row[1])
return options
class Calculator:
def __init__(self):
pass
def update_workout(self,day, wo_type: str)-> None:
height = {}
height.update(self.redirection(day, height))
save = Saving()
save.saving_figure(day, height, wo_type)
def redirection(self, wo_type: pd.DataFrame, height: dict) -> dict:
for start, column_name in enumerate(wo_type.columns):
if "Unnamed" not in column_name and column_name != "weight":
height.update({column_name: {}})
final = self.find_final(start, wo_type)
for rows in range(len(wo_type.index)):
height[column_name].update({wo_type.values[rows][0]: self.one_rep_max(wo_type, rows, start, final)})
return height
def find_final(self,start: int, wo_type: pd.DataFrame)-> int:
for final, column_name in enumerate(wo_type.columns):
if final > start and "Unnamed" not in column_name:
return final
def one_rep_max(self,wo_type: pd.DataFrame, row: int, start_cell: int, end_cell:int) -> list:
array_of_equations = []
array = []
for x in range(start_cell, end_cell):
array_of_equations.append(wo_type.values[row][x])
for equation in array_of_equations:
parts = equation.split('*')
numbers = [float(part) for part in parts]
RM = numbers[0]/( 1.0278-0.0278 * numbers[1] )
if(RM%1 <= 0.4):
array.append(int(RM))
elif(RM%1 <= 0.75):
array.append(int(RM)+.5)
else: array.append(int(RM)+1)
return array
class Saving:
def __init__(self):
pass
def saving_figure(self,day, height: dict, wo_type: str) -> None:
folder_name = 'figures'
main_dir = os.path.join(os.path.dirname(__file__), folder_name)
sub_dir = os.path.join(main_dir, wo_type)
width = 0.8
colors = [f'C{i}' for i in range(len(day.index))]
for exercise_name, date_and_reps in height.items():
num_sets = len(next(iter(date_and_reps.values())))
fig, axs = plt.subplots(1, num_sets, figsize=(5 * num_sets, 10))
if num_sets == 1:
axs = [axs]
keys_list = list(date_and_reps.keys())
for i, reps in enumerate(date_and_reps.values()):
for j in range(num_sets):
bar_data = [reps[j]]
axs[j].bar(i, bar_data, color=colors[i], edgecolor='white', width=width)
for v in bar_data:
axs[j].text(i, v, str(v), ha='center', va='bottom', fontdict={'family': 'sans-serif', 'weight': 'bold', 'size': 7})
axs[j].set_title(f'set: {j + 1}') # add 1 to set number for 1-based indexing
plt.tight_layout()
plt.subplots_adjust(bottom=0.2, left=0.1, right=0.9, top=0.9)
fig.legend(labels=keys_list, loc='upper left', fontsize='medium', ncols=1)
plt.savefig(os.path.join(sub_dir, f'{exercise_name}.png'))
plt.close()
if __name__ == "__main__":
app = App()
app.mainloop()