forked from eric-wieser/engineering-calendar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
objects.py
272 lines (199 loc) · 7.24 KB
/
objects.py
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
from __future__ import unicode_literals
from datetime import datetime, time
import re
import os
import xlrd
def _strify(c):
if isinstance(c, float):
return str(int(c))
return str(c)
def _dateify(value, wb):
return datetime(*xlrd.xldate_as_tuple(value, wb.datemode))
class Slot(object):
def __init__(self, name, times=None):
self.times = times or {}
self.name = name
def on(self, date):
day = '{:%a}'.format(date) # 3-letter day names (Mon, Tue, etc)
try:
start, end = self.times.get(day) or self.times['']
except KeyError:
raise ValueError("No times for {} associated with {}, and no default found".format(day, self.name))
return datetime.combine(date, start), datetime.combine(date, end)
def __repr__(self):
return "Slot({s.name!r}, {s.times!r})".format(s=self)
class Lab(object):
def __init__(self, code, group, name, location, slots, link):
self.group = group
self.code = code
self.name = name
self.location = location
self.slots = slots
self.link = link
def __repr__(self):
return "Lab({s.code!r}, {s.group!r}, {s.name!r}, {s.location!r}, slot=<{sl}>)".format(
s=self, sl=', '.join(s.name for s in self.slots))
def times_on(self, day):
return [slot.on(day) for slot in self.slots]
class Timetable(object):
def __init__(self, table, dates, groups, course, term):
self.dates = dates
self.groups = groups
self.table = table
self.course = course
self.term = term
def labs_for(self, lab_code):
return self.table[lab_code]
class ExamplePaper(object):
def __init__(self, name, sheet_no, paper_no, issue_date, class_date, class_location, class_lecturer):
self.name = name
self.sheet_no = sheet_no
self.paper_no = paper_no
self.issue_date = issue_date
# TODO: remove hard-coded times
self.class_start = datetime.combine(class_date, time(hour=11))
self.class_end = datetime.combine(class_date, time(hour=12))
self.class_location = class_location
self.class_lecturer = class_lecturer
class NoTermData(LookupError): pass
class CourseYear(object):
def __init__(self, part, year, xls_fname):
self.part = part
self.year = year
self.xls_fname = xls_fname
self._wb = xlrd.open_workbook(xls_fname, formatting_info=True)
self.slots = self._get_slots()
self.labs = self._get_labs()
self.last_mod = datetime.fromtimestamp(os.path.getmtime(xls_fname))
self._timetable = {}
@classmethod
def iter(cls):
import os
for fname in os.listdir():
m = re.match(r'(\w+)-(\d+).xls', fname)
if m:
yield cls.get(m.group(1), int(m.group(2)))
@classmethod
def get(cls, part, year):
return cls(part, year, '{}-{}.xls'.format(part, year))
def _get_slots(self):
sh = self._wb.sheet_by_name('slots')
headers = [c.value for c in sh.row(0)]
assert headers == ['Slot', 'Day', 'Start', 'End']
slots = {}
for i in range(1, sh.nrows):
name, day, start, end = [c.value for c in sh.row(i)[:4]]
start = time(*xlrd.xldate_as_tuple(start, self._wb.datemode)[3:])
end = time(*xlrd.xldate_as_tuple(end, self._wb.datemode)[3:])
if name not in slots:
slots[name] = Slot(name)
slot = slots[name]
slot.times[day] = start, end
return slots
def _get_labs(self):
sh = self._wb.sheet_by_name('labs')
headers = [c.value for c in sh.row(0)]
assert headers[:6] == ['Group', 'Code', 'Name', 'Location', 'Slot', 'Link']
current_group = None
labs = {}
for i in range(1, sh.nrows):
group, code, name, location, slots, link = [c.value for c in sh.row(i)[:6]]
code = _strify(code)
if group:
current_group = group
continue
if slots:
slots = [self.slots[slot] for slot in slots.split(',')]
else:
slots = []
if code in labs:
raise ValueError("Lab code {} refers to both {} and {}".format(code, labs[code].name, name))
labs[code] = Lab(code, current_group, name, location, slots, link)
return labs
def examples(self, name='lent'):
try:
sh = self._wb.sheet_by_name('examples-{}'.format(name))
except xlrd.XLRDError as e:
raise NoTermData("No data for example papers in term {!r}".format(name)) from e
issue_date = None
def gen():
for i in range(1, sh.nrows):
week, n_issue_date, title, sheet_no, class_date, class_lecturer, class_location = [c.value for c in sh.row(i)[:7]]
if n_issue_date:
try:
issue_date = _dateify(n_issue_date, self._wb)
except ValueError:
issue_date = None
class_date = _dateify(class_date, self._wb)
sheet_no = int(sheet_no)
paper_no, name = re.match(r'^P(\d): (.*)$', title).groups()
paper_no = int(paper_no)
yield ExamplePaper(
name=name,
sheet_no=sheet_no,
paper_no=paper_no,
issue_date=issue_date,
class_date=class_date,
class_location=class_location,
class_lecturer=class_lecturer
)
return gen()
def term(self, name='lent'):
try:
sh = self._wb.sheet_by_name(name)
except xlrd.XLRDError as e:
raise NoTermData("No data for term {!r}".format(name)) from e
col_area = range(1, sh.ncols)
row_area = range(4, sh.nrows)
def get_dates():
# read start month
assert sh.cell_value(0, 0) == 'Start month', "A1 should contain 'Start month:'"
start_month = _dateify(sh.cell_value(0, 1), self._wb)
# parse column headers, check dates
last_date_no = 0
for i in range(1, sh.ncols):
day_name, date_no = [c.value for c in sh.col(i)[1:3]]
date_no = int(date_no)
# increment the month if we roll over
if date_no < last_date_no:
month = start_month.month + 1
start_month = datetime(
year=start_month.year + (month - 1)//12,
month=(month - 1)%12 + 1, day=1)
# build and check the new date
date = start_month.replace(day=date_no)
if not '{:%a}'.format(date).startswith(day_name):
raise ValueError("Day in column {}, {:%a %d %b} is not a {!r}".format(i, date, day_name))
yield date.date()
last_date_no = date_no
def get_groups():
assert sh.cell_value(3, 0) == 'Groups', "A4 should contain 'Groups'"
for i in range(4, sh.nrows):
group = sh.cell_value(i, 0)
yield group
def get_merges():
for rlo, rhi, clo, chi in sh.merged_cells:
if rlo not in row_area or rhi-1 not in row_area:
raise ValueError('Merged cell overflows range horizontally')
elif clo not in col_area or chi-1 not in col_area:
raise ValueError('Merged cell overflows range vertically')
else:
rrange = range(rlo, rhi)
crange = range(clo, chi)
yield rrange, crange, sh.cell_value(rlo, clo)
dates = list(get_dates())
groups = list(get_groups())
merges = list(get_merges())
results = {}
def get_code(r, c):
for merge_r, merge_c, code in merges:
if r in merge_r and c in merge_c:
return _strify(code)
return _strify(sh.cell_value(r, c))
# convert timetable to lab objects
for group, r in zip(groups, row_area):
results[group] = {}
for date, c in zip(dates, col_area):
codes = get_code(r, c).split(',')
results[group][date] = [self.labs[code] for code in codes if code]
return Timetable(dates=dates, groups=groups, table=results, course=self, term=name)