Source code for ingredient_parser._common

#!/usr/bin/env python3

import collections
import logging
import os
import platform
import re
import subprocess
from collections.abc import Generator, Iterator
from fractions import Fraction
from importlib.resources import as_file, files
from itertools import groupby, islice
from operator import itemgetter
from typing import Any, TypeVar

import pint

UREG = pint.UnitRegistry()
with as_file(files(__package__) / "pint_extensions.txt") as p:
    # Load pint context that defines transformations between mass and volume
    UREG.load_definitions(p)

SUPPORTED_LANGUAGES = ["en"]

# Logging
logger = logging.getLogger("ingredient-parser")
logger.addHandler(logging.NullHandler())

# Regex pattern for matching a numeric range e.g. 1-2, 2-3, #1$2-1#3$4, 1.5-2.5
RANGE_PATTERN = re.compile(r"^[\d\#\$\.]+\s*[\-][\d\#\$\.]+$")

# Prefixes at the start of the string that indicate the string may be a float.
FLOAT_CANDIDATE_PREFIXES = frozenset(["-", "."])


[docs] def consume(iterator: Iterator[Any], n: int | None) -> None: """Advance the `iterator` n-steps ahead. If `n` is none, consume entirely. See consume from https://docs.python.org/3/library/itertools.html#itertools-recipes Parameters ---------- iterator : Iterator[Any] Iterator to advance. n : int | None Number of iterations to advance by. If None, consume entire iterator. Examples -------- >>> it = iter(range(10)) >>> consume(it, 3) >>> next(it) 3 >>> it = iter(range(10)) >>> consume(it, None) >>> next(it) StopIteration """ if n is None: # Feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # Advance to the empty slice starting at position n next(islice(iterator, n, n), None)
[docs] def group_consecutive_idx(idx: list[int]) -> Generator[Iterator[int], None, None]: """Yield groups of consecutive indices. Given a list of integers, yield groups of integers where the value of each in a group is adjacent to the previous element's value. Parameters ---------- idx : list[int] List of indices. Yields ------ Generator[Iterator[int], None, None] List of lists, where each sub-list contains consecutive indices. Examples -------- >>> groups = group_consecutive_idx([0, 1, 2, 4, 5, 6, 8, 9]) >>> [list(g) for g in groups] [[0, 1, 2], [4, 5, 6], [8, 9]] """ for _, g in groupby(enumerate(idx), key=lambda x: x[0] - x[1]): yield map(itemgetter(1), g)
T = TypeVar("T")
[docs] def incremental_sublists(sequence: list[T], reverse: bool = False) -> list[list[T]]: """Return sublists of sequence, retaining the same order, where each sublist contains incrementally more of sequence. Parameters ---------- sequence : list[T] Sequence of elements. reverse : bool, optional If True, generate incremental sublists starting at end of sequence Returns ------- list[list[T]] Incremental sublists of sequence Examples -------- >>> incremental_sublists([0, 1, 2, 3]) [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] >>> incremental_sublists(["this", "is", "a", "sequence"]) [["this"], ["this", "is"], ["this", "is", "a"], ["this", "is", "a", "sequence"]] >>> incremental_sublists([0, 1, 2, 3], reverse=True) [[3], [3, 2], [3, 2, 1], [3, 2, 1, 0]] """ if reverse: r_sequence = list(reversed(sequence.copy())) return [r_sequence[: i + 1] for i in range(len(sequence))] else: return [sequence[: i + 1] for i in range(len(sequence))]
[docs] def show_model_card(lang: str = "en") -> None: """Open model card for specified language in default application. Parameters ---------- lang : str, optional Selected language to open model card for. Raises ------ FileNotFoundError Raised if model card not found at expected path. ValueError Raised if unsupported language provided in lang argument. """ if lang not in SUPPORTED_LANGUAGES: raise ValueError(f'Unsupported language "{lang}"') with as_file(files(__package__) / lang / f"data/ModelCard.{lang}.md") as p: if not p.exists(): raise FileNotFoundError(f"Could not find Model Card at {p}") if platform.system() == "Darwin": # macOS subprocess.call(("open", p)) elif platform.system() == "Windows": # Windows os.startfile(p) # type: ignore else: # linux variants subprocess.call(("xdg-open", p))
[docs] def is_float(value: str) -> bool: """Check if `value` can be converted to a float. Parameters ---------- value : str Value to check. Returns ------- bool True if the value can be converted to float, else False. Examples -------- >>> is_float("3") True >>> is_float("2.5") True >>> is_float("1-2") False >>> if_float("-5") True """ if ( not value or value == "nan" or value.endswith("inf") or not (value[0].isdecimal() or value[0] in FLOAT_CANDIDATE_PREFIXES) ): # Quick checks for things that definitely aren't floats. return False try: _ = float(value) return True except ValueError: return False
[docs] def is_range(value: str) -> bool: """Check if `value` is a range e.g. 100-200. Parameters ---------- value : str Value to check. Returns ------- bool True if the value is a range, else False. Examples -------- >>> is_range("1-2") True >>> is_range("100-500") True >>> is_range("1") False """ return RANGE_PATTERN.match(value) is not None
# Define the regex pattern for a fraction in the intermediate format. # The first capture group captures any leading integer. # The second capture group captures the fraction part, including the leading '#'. INTERMEDIATE_FRACTION_PATTERN = re.compile(r"(\d*)(\#\d+\$\d+)")
[docs] def intermediate_fraction_to_unicode(token: str) -> str: """Convert intermediate format fraction to unicode fraction. The intermediate format uses # to mark the start of the fraction (and separate any leading integer from the fraction) and $ to mark the separation between the numerator and denominator. For example: #1$2 = ½ 2#1$3 = 2⅓ If the fraction part does not correspond to a unicode fraction, it is returned in a plain text form e.g. 1/2. Parameters ---------- token : str Fraction in intermediate format. Returns ------- str Intermediate format fraction converted to unicode fraction. Examples -------- >>> intermediate_fraction_to_unicode("#1$2") ½ >>> intermediate_fraction_to_unicode("1#1$3") 1⅓ >>> intermediate_fraction_to_unicode("2#1$9") 2 1/9 >>> intermediate_fraction_to_unicode("#1$2-#3$4") ½-¾ >>> intermediate_fraction_to_unicode("2#1$2-inch") 2½-inch """ INTERMEDIATE_FRAC_TO_UNICODE = { "#1$8": "\u215b", "#3$8": "\u215c", "#5$8": "\u215d", "#7$8": "\u215e", "#1$6": "\u2159", "#5$6": "\u215a", "#1$5": "\u2155", "#2$5": "\u2156", "#3$5": "\u2157", "#4$5": "\u2158", "#1$4": "\xbc", "#3$4": "\xbe", "#1$3": "\u2153", "#2$3": "\u2154", "#1$2": "\xbd", } def substitute_fraction_string(match: re.Match) -> str: """Function to construct the substitute for a intermediate format fraction. Parameters ---------- match : re.Match Match object for fraction in intermediate format. Returns ------- str Replacement string. """ integer = match.group(1) fraction = match.group(2) if fraction in INTERMEDIATE_FRAC_TO_UNICODE: replacement_fraction = INTERMEDIATE_FRAC_TO_UNICODE[fraction] else: replacement_fraction = fraction.replace("#", " ").replace("$", "/") return integer + replacement_fraction return INTERMEDIATE_FRACTION_PATTERN.sub(substitute_fraction_string, token).strip()
[docs] def is_fraction(value: str) -> bool: """Check if `value` is a fraction given in the intermediate format. Parameters ---------- value : str Value to check. Returns ------- bool True if the value is an fraction, else False. Examples -------- >>> is_fraction("#1$2") True >>> is_fraction("2#1$4") True >>> is_fraction("#1$2-#3$4") False """ return INTERMEDIATE_FRACTION_PATTERN.fullmatch(value) is not None
[docs] def fraction_obj_to_str(frac: Fraction) -> str: """Convert Fraction object to string. If the fractional part of the Fraction object can be converted to a unicode fraction, return as a unicode fraction. Otherwise return as a decimal. Parameters ---------- frac : Fraction Fraction object to convert to string. Returns ------- str Converted string. Examples -------- >>> fraction_obj_to_str(Fraction(1)) '1' >>> fraction_obj_to_str(Fraction(5, 2)) '2½' >>> fraction_obj_to_str(Fraction(0.75)) '¾' >>> fraction_obj_to_str(Fraction(11829411824999997, 25000000000000)) '473.176' >>> fraction_obj_to_str(Fraction(100000000000000009336059, 40000000000000000000000)) '2½' """ TEXT_FRAC_TO_UNICODE = { "1/8": "\u215b", "3/8": "\u215c", "5/8": "\u215d", "7/8": "\u215e", "1/6": "\u2159", "5/6": "\u215a", "1/5": "\u2155", "2/5": "\u2156", "3/5": "\u2157", "4/5": "\u2158", "1/4": "\xbc", "3/4": "\xbe", "1/3": "\u2153", "2/3": "\u2154", "1/2": "\xbd", } # Round fraction to avoid compounding errors during multiple conversions. # Only do this if the fraction is not already in UNICODE_FRACTIONS. if str(frac) not in TEXT_FRAC_TO_UNICODE: frac = round(frac, 12) # Fraction.is_integer() only available from Python 3.12. # Check Fraction.denominator is 1 instead. if frac.denominator == 1: return str(frac) if str(frac - int(frac)) in TEXT_FRAC_TO_UNICODE: # If the fractional part can be converted to unicode, do so. integer = int(frac) integer_text = str(integer) if integer != 0 else "" fraction = frac - int(frac) fraction_text = TEXT_FRAC_TO_UNICODE[str(fraction)] return integer_text + fraction_text else: # If the fractional part cannot be converted to unicode, return as decimal. return f"{float(frac):g}"