-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmenu.py
86 lines (67 loc) · 2.38 KB
/
menu.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
import datetime
import os
import re
import pdfplumber
import requests
from tempfile import NamedTemporaryFile
from meal import Meal
base_url = 'https://food-rewards.com/wp-content/uploads/'
tmp_file = NamedTemporaryFile(delete=False)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
def get_filepath(date: datetime.date):
year = date.year
month = date.month
day = date.day
ones = day % 10
if ones == 1:
suffix = 'st'
elif ones == 2:
suffix = 'nd'
elif ones == 3:
suffix = 'rd'
else:
suffix = 'th'
weekday = days[date.weekday()]
calmonth = months[month-1]
return f'{year}/{month:02}/{weekday}-{day}{suffix}-{calmonth}-{year}.pdf'
def normalise_whitespace(s):
return ' '.join(s.split())
def process_allergens(allergens):
allergens = normalise_whitespace(allergens).replace('TREE NUTS', 'tree-nuts')
processed = [x.strip().capitalize() for x in re.split(', | ', allergens)]
if not processed or processed == ['']:
return []
return processed
def get_menu(date):
"""Get menu for a given date"""
response = requests.get(os.path.join(base_url, get_filepath(date)))
response.raise_for_status()
with open(tmp_file.name, 'wb') as f:
f.write(response.content)
f = pdfplumber.open(tmp_file)
table = f.pages[0].extract_table()
all_items = []
all_allergens = []
all_may_contains = []
# skip header/footer rows
for row in table[2:-1]:
# whitespace normalisation
item = normalise_whitespace(row[0])
if ' - 1 Serving' not in item:
continue
item = item[:item.index(' - 1 Serving')].strip().capitalize()
allergens = process_allergens(row[2])
may_contains = process_allergens(row[3])
all_items.append(item)
all_allergens.append(allergens)
all_may_contains.append(may_contains)
return all_items, all_allergens, all_may_contains
if __name__ == '__main__':
# for testing
items, allergens, may_contains = get_menu(datetime.date.today())
meals = Meal().from_menu(items, allergens, may_contains)
print(items)
print(allergens)
print(may_contains)
[print(meal, meal.is_gluten_free()) for meal in meals]