/
_utils.py
189 lines (153 loc) · 5.73 KB
/
_utils.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
# mypy: disallow_untyped_defs=False
import html
import isodate
import math
import re
from ._exceptions import ElementNotFoundInHtml
FRACTIONS = {
"¼": 0.25,
"½": 0.50,
"¾": 0.75,
"⅓": 0.33,
"⅔": 0.66,
"⅕": 0.20,
"⅖": 0.40,
"⅗": 0.60,
}
TIME_REGEX = re.compile(
r"(\D*(?P<hours>[\d.\s/?¼½¾⅓⅔⅕⅖⅗]+)\s*(hours|hrs|hr|h|óra))?(\D*(?P<minutes>\d+)\s*(minutes|mins|min|m|perc))?",
re.IGNORECASE,
)
SERVE_REGEX_NUMBER = re.compile(r"(\D*(?P<items>\d+)?\D*)")
SERVE_REGEX_ITEMS = re.compile(
r"\bsandwiches\b |\btacquitos\b | \bmakes\b | \bcups\b | \bappetizer\b | \bporzioni\b | \bcookies\b | \b(large |small )?buns\b",
flags=re.I | re.X,
)
SERVE_REGEX_TO = re.compile(r"\d+(\s+to\s+|-)\d+", flags=re.I | re.X)
def get_minutes(element, return_zero_on_not_found=False): # noqa: C901: TODO
if element is None:
# to be removed
if return_zero_on_not_found:
return 0
raise ElementNotFoundInHtml(element)
# handle integer in string literal
try:
return int(element)
except Exception:
pass
if isinstance(element, str):
time_text = element
else:
time_text = element.get_text()
# attempt iso8601 duration parsing
if time_text.startswith("PT"):
try:
duration = isodate.parse_duration(time_text)
return math.ceil(duration.total_seconds() / 60)
except Exception:
pass
if time_text.startswith("P") and "T" in time_text:
time_text = time_text.split("T", 2)[1]
if "-" in time_text:
time_text = time_text.split("-", 2)[
1
] # sometimes formats are like this: '12-15 minutes'
if " to " in time_text:
time_text = time_text.split("to", 2)[
1
] # sometimes formats are like this: '12 to 15 minutes'
if "h" in time_text:
time_text = time_text.replace("h", "hours")
matched = TIME_REGEX.search(time_text)
minutes = int(matched.groupdict().get("minutes") or 0)
hours_matched = matched.groupdict().get("hours")
if hours_matched:
hours_matched = hours_matched.strip()
if any([symbol in FRACTIONS.keys() for symbol in hours_matched]):
hours = 0
for fraction, value in FRACTIONS.items():
if fraction in hours_matched:
hours += value
hours_matched = hours_matched.replace(fraction, "")
hours += int(hours_matched) if hours_matched else 0
elif "/" in hours_matched:
# for example "1 1/2" is matched
hours_matched_split = hours_matched.split(" ")
hours = 0
if len(hours_matched_split) == 2:
hours += int(hours_matched_split[0])
fraction = hours_matched_split[-1:][0].split("/")
hours += float(int(fraction[0]) / int(fraction[1]))
else:
hours = float(hours_matched)
minutes += round(60 * hours, 0)
return minutes
def get_yields(element):
"""
Will return a string of servings or items, if the receipt is for number of items and not servings
the method will return the string "x item(s)" where x is the quantity.
:param element: Should be BeautifulSoup.TAG, in some cases not feasible and will then be text.
:return: The number of servings or items.
"""
if element is None:
raise ElementNotFoundInHtml(element)
if isinstance(element, str):
serve_text = element
else:
serve_text = element.get_text()
if SERVE_REGEX_TO.search(serve_text):
serve_text = serve_text.split(SERVE_REGEX_TO.split(serve_text, 2)[1], 2)[1]
matched = SERVE_REGEX_NUMBER.search(serve_text).groupdict().get("items") or 0
servings = "{} serving{}".format(matched, "" if int(matched) == 1 else "s")
if SERVE_REGEX_ITEMS.search(serve_text) is not None:
# This assumes if object(s), like sandwiches, it is 1 person.
# Issue: "Makes one 9-inch pie, (realsimple-testcase, gives "9 items")
servings = "{} item{}".format(matched, "" if int(matched) == 1 else "s")
return servings
def normalize_string(string):
# Convert all named and numeric character references (e.g. >, >)
unescaped_string = html.unescape(string)
return re.sub(
r"\s+",
" ",
unescaped_string.replace("\xa0", " ")
.replace("\n", " ") #
.replace("\t", " ")
.strip(),
)
def url_path_to_dict(path):
pattern = (
r"^"
r"((?P<schema>.+?)://)?"
r"((?P<user>.+?)(:(?P<password>.*?))?@)?"
r"(?P<host>.*?)"
r"(:(?P<port>\d+?))?"
r"(?P<path>/.*?)?"
r"(?P<query>[?].*?)?"
r"$"
)
regex = re.compile(pattern)
matches = regex.match(path)
url_dict = matches.groupdict() if matches is not None else None
return url_dict
def get_host_name(url):
return url_path_to_dict(url.replace("://www.", "://"))["host"]
def change_keys(obj, convert):
"""
Recursively goes through the dictionary obj and replaces keys with the convert function
Useful for fixing incorrect property keys, e.g. in JSON-LD dictionaries
Credit: StackOverflow user 'baldr'
(https://web.archive.org/web/20201022163147/https://stackoverflow.com/questions/11700705/python-recursively-replace
-character-in-keys-of-nested-dictionary/33668421)
"""
if isinstance(obj, (str, int, float)):
return obj
if isinstance(obj, dict):
new = obj.__class__()
for k, v in obj.items():
new[convert(k)] = change_keys(v, convert)
elif isinstance(obj, (list, set, tuple)):
new = obj.__class__(change_keys(v, convert) for v in obj)
else:
return obj
return new