-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
355 lines (258 loc) · 10.5 KB
/
run.py
File metadata and controls
355 lines (258 loc) · 10.5 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
#!/usr/bin/python3
# Standard imports
import glob
import logging
import os
from datetime import datetime, timedelta
# Third party imports (requirements.txt)
from bs4 import BeautifulSoup
import xlsxwriter
# Global variables
total = 0
class Section:
def __init__(self, num='', title='', state='', info=''):
self.num = num
self.title = title
self.state = state
self.info = info
self.sem = ''
self.lab = ''
self.lec = ''
self.dates = {}
def parse_info(self):
for string in self.info.split('\n'):
substring = string.replace(', ', ',').split(" ")
if substring[1] == 'LAB':
start = clock12to24(substring[3])
finish = clock12to24(substring[5].split(',')[0])
self.lab = substring[2] + "||" + start + "-" + finish
if substring[1] == 'SEM':
start = clock12to24(substring[3])
finish = clock12to24(substring[5].split(',')[0])
self.sem = substring[2] + "||" + start + "-" + finish
if substring[1] == 'EXAM':
pass
if substring[1] == 'LEC':
start = clock12to24(substring[3])
finish = clock12to24(substring[5].split(',')[0])
self.lec = substring[2] + "||" + start + "-" + finish
def print(self):
if self.num != '':
print("\t" + self.num + ".\t" + self.title)
def format_section_times(self):
days = {}
if len(self.lec) > 1:
lec = self.lec.split('||')
for day in lec[0].split(','):
if day not in days.keys():
days.setdefault(day, [lec[1]])
else:
days[day].append(lec[1])
if len(self.sem) > 1:
sem = self.sem.split('||')
for day in sem[0].split(','):
if day not in days.keys():
days.setdefault(day, [sem[1]])
else:
days[day].append(sem[1])
if len(self.lab) > 1:
lab = self.lab.split('||')
for day in lab[0].split(','):
if day not in days.keys():
days.setdefault(day, [lab[1]])
else:
days[day].append(lab[1])
return days
def is_valid_html_file(html):
for string in html.find_all("h1"):
if string.text.upper() == "Section Selection Results".upper():
return True
return False
def format_section_times(section):
days = {}
if len(section.lec) > 1:
lec = section.lec.split('||')
for day in lec[0].split(','):
if day not in days.keys():
days.setdefault(day, [lec[1]])
else:
days[day].append(lec[1])
if len(section.sem) > 1:
sem = section.sem.split('||')
for day in sem[0].split(','):
if day not in days.keys():
days.setdefault(day, [sem[1]])
else:
days[day].append(sem[1])
if len(section.lab) > 1:
lab = section.lab.split('||')
for day in lab[0].split(','):
if day not in days.keys():
days.setdefault(lab, [lab[1]])
else:
days[day].append(lab[1])
return days
def can_be_together(section1, section2):
# dates of the sections must be already formatted
if len(section1.dates) <= 0 and len(section2.dates) <= 0:
return False
# print(section1.dates)
# print(section2.dates)
for day in section1.dates.keys():
# if day is in both sections
if day in list(section2.dates.keys()):
# print(day)
# Need to check times
for time_1 in section1.dates[day]:
if time_1 in list(section2.dates[day]):
return False
time_c1 = time_1.replace(':', '').split('-')
for time_2 in section2.dates[day]:
time_c2 = time_2.replace(':', '').split('-')
# print(time_1 + " | " + time_2)
if int(time_c1[1]) < int(time_c2[0]):
continue
if int(time_c2[1]) < int(time_c1[0]):
continue
return False
return True
def clock12to24(time12):
in_time = datetime.strptime(time12.replace(" ", "").strip(), "%I:%M%p")
return datetime.strftime(in_time, "%H:%M")
def get_day_pos(day):
day = day.lower()
if day == 'mon':
return 'B'
if day == 'tues':
return 'C'
if day == 'wed':
return 'D'
if day == 'thur':
return 'E'
if day == 'fri':
return 'F'
return 'A'
def create_option_menu(sections, workbook):
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
day_format = workbook.add_format({'bold': True, 'align': 'center'})
time_format = workbook.add_format({'bold': True, 'align': 'center'})
worksheet = workbook.add_worksheet()
worksheet.set_column('B:H', 20)
for i in range(0, len(days_of_week)):
worksheet.write(0, i + 1, days_of_week[i], day_format)
start = datetime.strptime('7:30', "%H:%M")
stop = datetime.strptime('22:30', "%H:%M")
times = {}
count = 1
while start.time() != stop.time():
start += timedelta(minutes=30)
worksheet.write(count, 0, start.strftime("%I:%M %p"), time_format)
count += 1
times.setdefault(start, count)
colours = ['#27AE60', '#2980B9', '#8E44AD', '#2C3E50', '#FLC40F', '#E74C3C', '#E67E22']
count = 0
for section in sections:
node_format = workbook.add_format({'bold': True, 'align': 'center', 'valign': 'vcenter'})
node_format.set_font_color('white')
node_format.set_fg_color(colours[count])
for key, values in section.dates.items():
row = get_day_pos(key)
if row != 'A':
for value in values:
start = value.split('-')[0]
stop = value.split('-')[1]
loc_start = 0
loc_stop = 0
for ti, loc in times.items():
if ti.strftime("%H:%M") == start:
loc_start = loc
if (ti + timedelta(minutes=-10)).strftime("%H:%M") == stop:
loc_stop = loc - 1
worksheet.merge_range(row + str(loc_start) + ':' + row + str(loc_stop), section.title, node_format)
count += 1
if count == len(colours):
count = 0
def main():
logging.basicConfig(filename=None, level=logging.DEBUG)
global total
workbook = xlsxwriter.Workbook('out/options.xlsx')
sections = {}
lengths = {}
exceptions = input("What exceptions would you like to add? ").split(' ')
print(exceptions)
if not os.path.exists("out"):
os.makedirs("out")
if not os.path.exists("html_courses"):
os.makedirs("html_courses")
for path in glob.glob(".\html_courses\*.html"):
with open(path, 'r') as data:
soup = BeautifulSoup(data.read(), 'html.parser')
if not is_valid_html_file(soup):
logging.error("File: " + path + " is not valid.")
else:
print("Reading file: '" + path + "'")
for row in soup.find('div', {'id': 'GROUP_Grp_WSS_COURSE_SECTIONS'}).find_all('tr'):
section = Section()
for subsection in row.find_all('td'):
subclasses = subsection.get('class')
if 'windowIdx' in subclasses:
if subsection.text == '':
break
else:
section.num = subsection.text.rstrip('\n')
if 'LIST_VAR1' in subclasses or 'LIST_VAR2' in subclasses:
if subsection.text.lower().strip() == 'open' or subsection.text.lower().strip() == 'closed':
section.state = subsection.text.strip()
if 'SEC_SHORT_TITLE' in subclasses:
section.title = subsection.text.strip().split(" ")[0]
if 'SEC_MEETING_INFO' in subclasses:
section.info = subsection.text.strip()
section.parse_info()
if len(section.state) > 0:
title = section.title.split("*")
title = title[0] + "*" + title[1]
if section.state.upper() == 'OPEN' or section.title.upper() in exceptions:
section.dates = section.format_section_times()
if title in sections.keys():
sections.get(title).append(section)
lengths[title] += 1
else:
sections.setdefault(title, [section])
lengths.setdefault(title, 1)
else:
if title not in sections.keys():
sections.setdefault(title, [])
lengths.setdefault(title, 0)
num_courses = len(sections.keys())
print("\nNum of courses: " + str(num_courses))
for key, values in sections.items():
print("===== " + key + " (" + str(len(values)) + ") ======")
for value in values:
value.print()
work(sections, workbook)
print("\nTotal options found: " + str(total))
workbook.close()
def work(sections, workbook, current=0, courses=None, path=[]):
global total
if courses is None:
courses = list(sections.keys())
if current >= len(courses):
if len(path) != 0:
for element1 in path:
for element2 in path:
if can_be_together(element1, element2) or element2 == element1:
continue
else:
return
# print(total)
# for s in path:
# s.print()
total += 1
create_option_menu(path, workbook)
return
for section in sections[courses[current]]:
path.append(section)
work(sections, workbook, current + 1, courses, path)
del path[-1]
if __name__ == '__main__':
main()