-
-
Notifications
You must be signed in to change notification settings - Fork 69
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: add add_ingredient_in_taxonomy_field function from Robotoff
- Loading branch information
1 parent
d0aa579
commit 64ee295
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
from openfoodfacts.taxonomy import Taxonomy | ||
from openfoodfacts.types import JSONType | ||
|
||
|
||
def add_ingredient_in_taxonomy_field( | ||
parsed_ingredients: list[JSONType], ingredient_taxonomy: Taxonomy | ||
) -> tuple[int, int]: | ||
"""Add the `in_taxonomy` field to each ingredient in `parsed_ingredients`. | ||
This function is called recursively to add the `in_taxonomy` field to each | ||
sub-ingredient. It returns the total number of ingredients and the number | ||
of known ingredients (including sub-ingredients). | ||
:param parsed_ingredients: a list of parsed ingredients, in Product Opener | ||
format | ||
:param ingredient_taxonomy: the ingredient taxonomy | ||
:return: a (total_ingredients_n, known_ingredients_n) tuple | ||
""" | ||
ingredients_n = 0 | ||
known_ingredients_n = 0 | ||
for ingredient_data in parsed_ingredients: | ||
ingredient_id = ingredient_data["id"] | ||
in_taxonomy = ingredient_id in ingredient_taxonomy | ||
ingredient_data["in_taxonomy"] = in_taxonomy | ||
known_ingredients_n += int(in_taxonomy) | ||
ingredients_n += 1 | ||
|
||
if "ingredients" in ingredient_data: | ||
( | ||
sub_ingredients_n, | ||
known_sub_ingredients_n, | ||
) = add_ingredient_in_taxonomy_field( | ||
ingredient_data["ingredients"], ingredient_taxonomy | ||
) | ||
ingredients_n += sub_ingredients_n | ||
known_ingredients_n += known_sub_ingredients_n | ||
|
||
return ingredients_n, known_ingredients_n |