Skip to content

Commit

Permalink
refactor: uses split_barcode from openfoodfacts package
Browse files Browse the repository at this point in the history
  • Loading branch information
raphael0202 committed Aug 7, 2023
1 parent eaaeca3 commit 9c2d1c6
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 36 deletions.
36 changes: 1 addition & 35 deletions robotoff/off.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from urllib.parse import urlparse

import requests
from openfoodfacts.images import split_barcode
from requests.exceptions import JSONDecodeError

from robotoff import settings
Expand Down Expand Up @@ -95,41 +96,6 @@ def get_barcode_from_path(path: str) -> Optional[str]:
return barcode or None


BARCODE_PATH_REGEX = re.compile(r"^(...)(...)(...)(.*)$")


def split_barcode(barcode: str) -> list[str]:
"""Split barcode in the same way as done by Product Opener to generate a
product image folder.
:param barcode: The barcode of the product. For the pro platform only,
it must be prefixed with the org ID using the format
`{ORG_ID}/{BARCODE}`
:raises ValueError: raise a ValueError if `barcode` is invalid
:return: a list containing the splitted barcode
"""
org_id = None
if "/" in barcode:
# For the pro platform, `barcode` is expected to be in the format
# `{ORG_ID}/{BARCODE}` (ex: `org-lea-nature/3307130803004`)
org_id, barcode = barcode.split("/", maxsplit=1)

if not barcode.isdigit():
raise ValueError(f"unknown barcode format: {barcode}")

match = BARCODE_PATH_REGEX.fullmatch(barcode)

splits = [x for x in match.groups() if x] if match else [barcode]

if org_id is not None:
# For the pro platform only, images and OCRs belonging to an org
# are stored in a folder named after the org for all its products, ex:
# https://images.pro.openfoodfacts.org/images/products/org-lea-nature/330/713/080/3004/1.jpg
splits.append(org_id)

return splits


def _generate_file_path(product_id: ProductIdentifier, image_id: str, suffix: str):
splitted_barcode = split_barcode(product_id.barcode)
return f"/{'/'.join(splitted_barcode)}/{image_id}{suffix}"
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/insights/test_question.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import Optional

import pytest
from openfoodfacts.images import split_barcode

from robotoff.insights.question import (
CategoryQuestionFormatter,
Expand All @@ -11,7 +12,6 @@
get_display_image,
)
from robotoff.models import ProductInsight
from robotoff.off import split_barcode
from robotoff.settings import TEST_DATA_DIR
from robotoff.types import InsightType, ProductIdentifier, ServerType
from robotoff.utils.i18n import TranslationStore
Expand Down

0 comments on commit 9c2d1c6

Please sign in to comment.