-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.py
255 lines (212 loc) · 8.6 KB
/
process.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
import csv
import json
import os
import shutil
import tomllib
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import booklet
from api_types import APIResponse, Config, Event
eastern_tz = ZoneInfo("America/New_York")
with open("config.toml", "rb") as c:
config: Config = tomllib.load(c) # type: ignore
def get_main_dorm(dorm: str) -> str:
if dorm in config["dorms"]["subdorms"]:
return config["dorms"]["subdorms"][dorm]
return dorm
def process_dt_from_csv(time_string: str) -> str:
"""
Uses the config setting `date_format` to convert a time string into ISO format
"""
event_dt = datetime.strptime(time_string, config["csv"]["date_format"]).replace(
tzinfo=eastern_tz
)
return event_dt.isoformat()
def get_dorm_group(dorms: list[str]) -> str:
return ", ".join(dorms)
def event_with_same_name_exists(event: Event, events: list[Event]) -> bool:
for e in events:
if (
e["name"] == event["name"]
and e["start"] != event["start"]
and e["end"] != event["end"]
):
return True
return False
def check_if_events_conflict(
event_one_start: datetime,
event_one_end: datetime,
event_two_start: datetime,
event_two_end: datetime,
) -> bool:
return (
(event_two_start <= event_one_start < event_two_end)
or (event_two_start < event_one_end <= event_two_end)
or (event_one_start <= event_two_start < event_one_end)
or (event_one_start < event_two_end <= event_one_end)
)
def get_invalid_events(orientation_events: list[Event], api_response: APIResponse):
"""
Get list of error messages for invalid events.
Formatted as a dict, with dorms as the key and a tuple of the contact emails and list of events as the value.
"""
errors: dict[str, tuple[list[str], list[str]]] = dict()
# Check for conflicts with mandatory events and invalid events
all_events = orientation_events + api_response["events"]
mandatory_events = list(
event_to_check
for event_to_check in all_events
if config["orientation"]["mandatory_tag"].strip().lower()
in event_to_check["tags"]
)
def create_error_dorm_entry(dorms: list[str], error_string: str) -> None:
dorms_list = [get_main_dorm(dorm) for dorm in dorms]
error_key = get_dorm_group(dorms_list)
if errors.get(error_key) is None:
errors[error_key] = (
[
config["dorms"]["rex_contact"][
dorm if dorm != config["rename_dormcon_to"] else "DormCon"
]
+ "@mit.edu"
for dorm in dorms_list
],
[],
)
errors[error_key][1].append(error_string)
for event in api_response["events"]:
event_start = datetime.fromisoformat(event["start"])
event_end = datetime.fromisoformat(event["end"])
if event_end < event_start:
event_date = (
" on "
+ booklet.get_date_bucket(
event, config["dates"]["hour_cutoff"]
).strftime("%x")
if event_with_same_name_exists(event, api_response["events"])
else ""
)
create_error_dorm_entry(
event["dorm"],
f"{event['name']}{event_date} has an end time before its start time.",
)
continue
for mandatory_event in mandatory_events:
mandatory_event_start = datetime.fromisoformat(mandatory_event["start"])
mandatory_event_end = datetime.fromisoformat(mandatory_event["end"])
if check_if_events_conflict(
event_start, event_end, mandatory_event_start, mandatory_event_end
):
event_date = " on " + booklet.get_date_bucket(
event, config["dates"]["hour_cutoff"]
).strftime("%x")
subdorms_if_needed = (
" ("
+ ", ".join(
[dorm for dorm in event["dorm"] if dorm != get_main_dorm(dorm)]
)
+ ") "
if [dorm for dorm in event["dorm"] if dorm != get_main_dorm(dorm)]
else " "
)
create_error_dorm_entry(
event["dorm"],
f"{event['name']}{subdorms_if_needed}conflicts with {mandatory_event['name']}{event_date}.",
)
continue
if errors.get(config["rename_dormcon_to"]) is not None:
errors["DormCon"] = errors.pop(config["rename_dormcon_to"])
return errors
def process_csv(filename: str):
events: list[Event] = []
# NOTE: If you saved this with Excel as a CSV file with UTF-8 encoding, you might
# need to open it with encoding="utf-8-sig" instead of "utf-8".
with open(filename, encoding="utf-8") as f:
reader = [row for row in csv.DictReader(f)]
events_list: list[dict[str, str]] = []
for index, row in enumerate(reader):
events_list.append(dict())
for key, val in row.items():
events_list[index][key.strip()] = val.strip() if val else ""
for event in events_list:
if event["Published"] != "TRUE":
continue
events.append(
{
"name": event["Event Name"],
"dorm": [
(
dorm.strip()
if dorm.strip().lower() != "dormcon"
else config["rename_dormcon_to"].strip()
)
for dorm in event["Dorm"].split(",")
if dorm
],
"location": event["Event Location"],
"start": process_dt_from_csv(event["Start Date and Time"]),
"end": process_dt_from_csv(event["End Date and Time"]),
"description": event["Event Description"],
"tags": [
tag.strip().lower() for tag in event["Tags"].split(",") if tag
],
"group": event["Group"] or None,
}
)
return events
if __name__ == "__main__":
api_response: APIResponse = {
"name": config["name"],
"published": datetime.now(timezone.utc).isoformat(),
"events": [],
"dorms": [],
"tags": [],
"colors": config["colors"],
"start": config["dates"]["start"],
"end": config["dates"]["end"],
}
orientation_events: list[Event] = []
for filename in os.listdir("events"):
if not filename.endswith(".csv"):
continue
print(f"Processing {filename}...")
if filename == config["orientation"]["filename"]:
orientation_events = process_csv("events/" + filename)
else:
api_response["events"].extend(process_csv("events/" + filename))
# Order events by start time, then by end time.
api_response["events"].sort(key=lambda e: e["end"])
api_response["events"].sort(key=lambda e: e["start"])
# Add extra data from events and config file
api_response["dorms"] = sorted(
list(set(dorm for e in api_response["events"] for dorm in e["dorm"])),
key=str.lower,
)
api_response["tags"] = sorted(
list(set(t for e in api_response["events"] for t in e["tags"]))
)
booklet_only_events = (
orientation_events if config["orientation"]["include_in_booklet"] else []
)
errors = get_invalid_events(orientation_events, api_response)
print("Processing complete!")
print("Generating the booklet...")
booklet_html = booklet.generate_booklet(api_response, config, booklet_only_events)
print("Processing index.md...")
index_html = booklet.generate_index()
print("Processing errors...")
errors_html = booklet.generate_errors(errors, api_response["name"])
print("Outputting booklet and JSON...")
if os.path.exists("output"):
shutil.rmtree("output")
os.mkdir("output")
shutil.copytree("static", "output", dirs_exist_ok=True)
with open("output/api.json", "w", encoding="utf-8") as w:
json.dump(api_response, w)
with open("output/booklet.html", "w", encoding="utf-8") as b:
b.write(booklet_html)
with open("output/index.html", "w", encoding="utf-8") as i:
i.write(index_html)
with open("output/errors.html", "w", encoding="utf-8") as e:
e.write(errors_html)
print("Complete!")