-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
208 lines (173 loc) · 6.97 KB
/
main.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
import click
import requests
import uuid
import sys
from urllib.parse import urlparse
# TODO error handling...
def get_kptn_recipe(uid, language):
""" Get the recipe JSON from KptnCook """
# Mby parameter store is important, but until now, it worked fine...
url = f"https://mobile.kptncook.com:443/recipes/search?lang={language}&store=de"
headers = {
"hasIngredients": "YES",
"kptnkey": "6q7QNKy-oIgk-IMuWisJ-jfN7s6",
"Accept": "application/vnd.kptncook.mobile-v8+json",
"User-Agent": "Platform/Android/5.0.1 App/7.2.7",
}
res = requests.post(url, headers=headers, json=[{"uid": uid}])
if res.status_code != 200 or "title" not in res.json()[0]:
print(res.text)
sys.exit(1)
return res.json()
def import_recipe(host, auth, data, with_time=False, units="metric"):
""" Take the KptnCook JSON and translate it to Tandoor """
headers = {"Authorization": "Bearer " + auth}
# d is the final JSON
d = {}
d["name"] = data["title"]
d["description"] = data["authorComment"]
d["keywords"] = [] # add your own keywords
d["internal"] = True
d["nutrition"] = {
"calories": data["recipeNutrition"]["calories"],
"proteins": data["recipeNutrition"]["protein"],
"fats": data["recipeNutrition"]["fat"],
"carbohydrates": data["recipeNutrition"]["carbohydrate"],
}
d["working_time"] = data.get("preparationTime", 0)
d["waiting_time"] = data.get("cookingTime", 0)
d["servings"] = 1
d["file_path"] = "" # Is added below
# Parse all steps
steps = []
for step_idx, s in enumerate(data["steps"]):
# Init data
step = {}
step["instruction"] = s["title"]
step["step_recipe"] = None
step["order"] = step_idx
step["show_as_header"] = True
# Load the step image and upload it to Tandoor
img_url = s["image"]["url"]
res = requests.get(img_url , params={"kptnkey": "6q7QNKy-oIgk-IMuWisJ-jfN7s6"}, stream=True)
bin_data = res.content
img_name = str(uuid.uuid4())
files = {'file': (img_name + '.png', bin_data)}
res = requests.post(host.strip("/") + "/api/user-file/", headers=headers, files=files, data={"name": img_name})
if res.status_code != 201:
print(res.text)
sys.exit(1)
step["file"] = res.json()
# Parse the time per step
step["time"] = 0
timers = s["timers"]
for timer in timers:
t = timer["minOrExact"]
if with_time:
step["time"] += t
if "max" in timer:
t_str = f"{ t } - { timer['max'] } min."
else:
t_str = f"{ t } min."
step["instruction"] = step["instruction"].replace("<timer>", t_str, 1)
# Parse all ingredients
ingredients = []
ings = s.get("ingredients", [])
for ing_idx, ing in enumerate(ings):
# Init ingredient
ingredient = {}
ingredient["note"] = ""
ingredient["order"] = ing_idx
ingredient["is_header"] = False
ingredient["no_amount"] = False
# Add the food. If name already exists, Tandoor will merge it.
ingredient["food"] = {
"full_name": ing["title"],
"name": ing["title"],
"food_onhand": False,
"supermarket_category": None,
"inherit_fields": [],
"ignore_shopping": False
}
# Init measures and units
ingredient["amount"] = 0
ingredient["unit"] = None
ingredient["no_amount"] = True
# Parse measures and units
q = "metricQuantity" if units=="metric" else "imperialQuantity"
m = "metricMeasure" if units=="metric" else "imperialMeasure"
if "unit" in ing:
ingredient["amount"] = ing["unit"][q]
ingredient["no_amount"] = False
if "measure" in ing["unit"]:
ingredient["unit"] = {"name": ing["unit"][m]}
elif "quantity" in ing:
ingredient["amount"] = ing[q]
ingredient["no_amount"] = False
# Add ingredient
ingredients.append(ingredient)
# Add step
step["ingredients"] = ingredients
steps.append(step)
# Add steps
d["steps"] = steps
# Upload recipe to Tandoor
recipe_api_url = host.strip("/") + "/api/recipe/"
res = requests.post(recipe_api_url, headers=headers, json=d)
if res.status_code != 201:
print(res.text)
sys.exit(1)
# Get recipe id to upload the cover image
tandoor_recipe_json = res.json()
rid = tandoor_recipe_json["id"]
img_api_url = host.strip("/") + f"/api/recipe/{rid}/image/"
# Loading the cover image from KptnCook
for img in data["imageList"]:
if img["type"] == "cover":
img_url = img["url"]
break
res = requests.get(img_url , params={"kptnkey": "6q7QNKy-oIgk-IMuWisJ-jfN7s6"}, stream=True)
bin_data = res.content
# Upload cover image to Tandoor
files = {'image': ('img.png', bin_data)}
res = requests.put(img_api_url, headers=headers, files=files)
if res.status_code != 200:
print(res.text)
sys.exit(1)
# Link cover image with recipe
tandoor_recipe_json["image"] = host.strip("/") + res.json()["image"]
res = requests.put(recipe_api_url + str(rid) + "/", headers=headers, json=tandoor_recipe_json)
if res.status_code != 200:
print(res.text)
sys.exit(1)
@click.command()
@click.argument('host')
@click.argument('api_key')
@click.argument('src')
@click.option('--language', default="de", help='choose the language',
type=click.Choice(['de', 'en']))
@click.option('--units', default="metric", help='choose the untis',
type=click.Choice(['metric', 'imperial']))
@click.option('--with_time', default=False, help='import time into recipes')
def main(host, api_key, src, language, units, with_time):
"""Request a recipe (<SRC>) from KptnCook and
import it into the Tandoor cookbook on <HOST>
using the Tandoor <API_KEY>.
<SRC> can either be the recipe id or the shared recipe url."""
# Get UID
uid = src
if src.startswith("http"):
print("Try to parse URL")
res = requests.get(src, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0"})
u = urlparse(res.url)
uid = u.path.split("/")[-1]
print(f"Loading recipe from {res.url}")
# Get recipe
print(f"UID: {uid}")
data = get_kptn_recipe(uid, language)
# Parse recipe
print(f"Start parsing and uploading")
import_recipe(host, api_key, data[0], with_time=with_time, units=units)
print(f"Done!")
if __name__ == '__main__':
main()