-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml_parse.py
More file actions
214 lines (179 loc) · 7.04 KB
/
Copy pathhtml_parse.py
File metadata and controls
214 lines (179 loc) · 7.04 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
import sys
import os
import re
from pathlib import Path
import uuid
import shutil
# navigate to https://sdb.admin.uw.edu/sisStudents/uwnetid/schedule.aspx and
# use that html page as input. unfortunately quarter start and end dates
# are currently hard-coded, can probably change that later by having this
# refer to academic calendar and look at local date or something
# "3/30/2025", for some reason all the events will display on the starting date
# on google calendar and i have absolutely no idea why it does that
QUARTER_START = "20250330"
# "6/7/2025", ensure events show up on 6th as the end date seems to be exclusive
QUARTER_END = "20250607"
# class containing all data for calendar event
class Event:
def __init__(self, start_time: str, end_time: str, name: str,
location: str, days: list[str], ):
self.start_time = start_time
self.end_time = end_time
self.name = name
self.location = location
self.days = days
# takes in file path and if the file exists and is an html file,
# it will read out the html into a string
def read_html_file(file_name: str) -> str:
# Check if file has .html extension
if not file_name.lower().endswith('.html'):
print("Error: File is not an HTML file.")
return None
# Check if the file exists
if not os.path.isfile(file_name):
print("Error: File does not exist.")
return None
# Read the file contents into a string
try:
with open(file_name, 'r', encoding='utf-8') as file:
html_content = file.read()
return html_content
except Exception as e:
print(f"Error reading file: {e}")
return None
# perform regex on the entire html string to pick out the useful pieces
# for building each calendar event
def regex(html_string: str) -> None:
pattern = r'<td class=[\"|\']mono nowrap[\"|\']>[A-Z ]+ [0-9]+.*</td>\n.*\n.*\n.*\n\t<td class=[\"|\']mono nowrap[\"|\']>[MWThF]*</td>\n.*\n.*'
res = re.findall(pattern, html_string)
for course in res:
# split html by newline to extract needed information
split = course.splitlines()
# extract class name
start = 24
end = 24
while (split[0][end] != '<'):
end+=1
name = split[0][start:end]
name = name.replace(" ", " ")
# extract days
start = 25
end = 25
while (split[4][end] != '<'):
end+=1
days = split[4][start:end]
# need to convert these days into a list format for easier ICS file creation
day_list = []
for i in range(len(days)):
if (days[i] == 'T' and i < len(days)-1 and days[i+1] == 'h'):
day_list.append("TH")
elif (days[i] == 'T'):
day_list.append("TU")
elif (days[i] == 'M'):
day_list.append("MO")
elif (days[i] == 'W'):
day_list.append("WE")
elif (days[i] == 'F'):
day_list.append("FR")
# extract times
start = 25
end = 25
while (split[5][end] != '<'):
end+=1
times = split[5][start:end]
# strip out non-breaking space, replace with zero for easier integer parsing
times = times.replace(" ", "0")
# need to convert times to military time
replace_start = times[:4]
replace_end = times[-4:]
# NOTE this does not work for PMP classes that run from 6pm to 9pm
if (int(times[0:2]) < 8):
replace_start = str(int(times[0:2]) + 12) + times[2:4]
if (int(times[5:7]) < 8):
replace_end = str(int(times[-4:-2]) + 12) + times[-2:]
# extract location
location_pattern = r'>[A-Z0-9 ]+</a> [A-Z0-9]+<'
location = ""
curr = re.findall(location_pattern, split[6])
if (len(curr) == 0):
location = "TBA"
else:
start = 1
end = 1
while (curr[0][end] != '<'):
end+=1
location = curr[0][start:end] + " "
start = end + 5
end = start
while (curr[0][end] != '<'):
end+=1
location += curr[0][start:end]
event = Event(replace_start, replace_end, name, location, day_list)
create_ics(event)
# create actual ICS file given the event details
def create_ics(event: Event) -> None:
# this code is terrible and seems to use 2 different ways to check
# if a file exists (compared to in read_html) as well as write to a file
file_path = Path(event.name + ".ics")
if file_path.exists():
print(f"{file_path} already exists. Not overwriting.")
return
else:
# copy starter ics data (which should be the same for all events)
try:
shutil.copyfile("starter_ics.txt", file_path)
except Exception as e:
print(f"shutil.copyfile error occured {e}")
return
uid = uuid.uuid4()
# DTSTART;TZID=America/Los_Angeles:20250331T093000
remaining_content = "DTSTART;TZID=America/Los_Angeles:" + QUARTER_START + "T" \
+ event.start_time + "00\n"
# DTEND;TZID=America/Los_Angeles:20250331T103000
remaining_content += "DTEND;TZID=America/Los_Angeles:" + QUARTER_START + "T" \
+ event.end_time + "00\n"
day_str = ""
for index, day in enumerate(event.days):
day_str = day_str + day
if (index != len(event.days)-1):
day_str = day_str + ","
# RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20250607T065959Z;BYDAY=MO,TU,WE,FR
remaining_content += "RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=" + QUARTER_END + "T" \
"065959Z;BYDAY=" + day_str + "\n"
# DTSTAMP:20250506T183209Z
remaining_content += "DTSTAMP:20250506T183209Z\n"
# UID:insert_some_uid_here
remaining_content += "UID:" + str(uid) + "\n"
# LOCATION:THO 125
remaining_content += "LOCATION:" + event.location + "\n"
# STATUS:CONFIRMED
remaining_content += "STATUE:CONFIRMED\n"
# SUMMARY:EE 331 A
remaining_content += "SUMMARY:" + event.name + "\n"
# remainder
remaining_content += "TRANSP:OPAQUE\nEND:VEVENT\nEND:VCALENDAR"
#file_path.write_text(remaining_content)
with file_path.open("a") as f:
f.write(remaining_content)
'''
DTSTART;TZID=America/Los_Angeles:20250331T093000
DTEND;TZID=America/Los_Angeles:20250331T103000
RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20250607T065959Z;BYDAY=MO,TU,WE,FR
DTSTAMP:20250506T183209Z
UID:insert_some_uid_here
LOCATION:THO 125
STATUS:CONFIRMED
SUMMARY:EE 331 A
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR
'''
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python html_parse.py <filename.html>")
sys.exit(1)
filename = sys.argv[1]
html_string = read_html_file(filename)
if html_string is not None:
print("HTML content successfully read.")
regex(html_string)