recept / recept.py
amcoff's picture
please
fdd3e65 unverified
raw
history blame
4.36 kB
import json
import datasets
_DESCRIPTION = "Recipes scraped from ICA.se"
_TRAIN_DOWNLOAD_URL = "./ica.json"
difficulty_translations = {
"Enkel": "easy",
"Medel": "medium",
"Avancerad": "hard",
}
difficulties = ["easy", "medium", "hard"]
class Recept(datasets.GeneratorBasedBuilder):
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("int32"),
"title": datasets.Value("string"),
"preamble": datasets.Value("string"),
"url": datasets.Value("string"),
"cooking_time": datasets.Value("string"),
"difficulty": datasets.ClassLabel(names=difficulties),
"categories": datasets.Sequence(datasets.Value("string")),
"rating": datasets.Value("float32"),
"reviews": datasets.Value("int32"),
"instructions": datasets.Sequence(datasets.Value("string")),
"ingredients": datasets.Sequence(
{
"heading": datasets.Value("string"),
"list": datasets.Sequence(
{
"name": datasets.Value("string"),
"amount": datasets.Value("string"),
}
),
}
),
"nutrition": {
"energy": datasets.Value("string"),
"fat": datasets.Value("string"),
"salt": datasets.Value("string"),
"carbohydrates": datasets.Value("string"),
"protein": datasets.Value("string"),
},
}
),
)
def _split_generators(self, dl_manager):
train_path = dl_manager.download_and_extract(_TRAIN_DOWNLOAD_URL)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN, gen_kwargs={"filepath": train_path}
),
]
def _generate_examples(self, filepath):
with open(filepath, encoding="utf8") as file:
for row in file:
recipe = json.loads(row)
difficulty = recipe.get("difficulty")
if difficulty is not None:
difficulty = difficulties.index(difficulty_translations[difficulty])
ingredient_sections = []
for section in recipe["ingredients"]:
ingredients = []
for ingredient in section["list"]:
ingredients.append(
{
"name": ingredient["ingr"],
"amount": ingredient["qty"],
}
)
ingredient_sections.append(
{
"heading": section["heading"],
"list": ingredients,
}
)
nutrition = recipe["nutrition"]
yield recipe["id"], {
"id": recipe["id"],
"title": recipe["title"],
"preamble": recipe["preamble"],
"url": recipe["absoluteUrl"],
"cooking_time": recipe.get("cookingTime"),
"difficulty": difficulty,
"categories": recipe["categories"],
"rating": recipe["rating"]["averageRating"],
"reviews": recipe["rating"]["numberOfVotes"],
"instructions": recipe["instructions"],
"ingredients": ingredient_sections,
"nutrition": {
"energy": nutrition.get("energy"),
"fat": nutrition.get("fat"),
"salt": nutrition.get("salt"),
"carbohydrates": nutrition.get("carbohydrates"),
"protein": nutrition.get("protein"),
},
}