Preprocess#

class ingredient_parser.en.preprocess.PreProcessor(input_sentence: str, custom_units: dict[str, str] | None = None)[source]#

Recipe ingredient sentence PreProcessor class.

Performs the necessary preprocessing on a sentence to generate the features required for the ingredient parser model.

Each input sentence goes through a cleaning process to tidy up the input into a standardised form.

Parameters:
input_sentencestr

Input ingredient sentence.

custom_unitsdict[str, str] | None, optional

Dict of plural-singular pairs of custom units.

Attributes:
inputstr

Input ingredient sentence.

sentencestr

Input ingredient sentence, cleaned to standardised form.

singularised_indiceslist[int]

Indices of tokens in tokenized sentence that have been converted from plural to singular

tokenized_sentencelist[Token]

Tokenised ingredient sentence.

Methods

sentence_features()

Return dict of features for each token in sentence.

Notes

The cleaning steps are as follows:
  1. Unescape HTML

  2. Remove price annotations

  3. Replace en and em dashes with hyphens

  4. Replace unicode fractions with ASCII versions

  5. Combine quantities split by ‘and’ (e.g. 1 and 1/2)

  6. Identify fractions and convert to intermediate format

  7. Split joined quantity and units

  8. Remove trailing period from units

  9. Replace string ranges

  10. Replace ranges involved duplicated units

  11. Merge quantity with following ‘x’

  12. Collapse ranges into single token

  13. Expand hyphen split names into full names

Following the cleaning of the input sentence, it is tokenized into a list of tokens.

Each token is one of the following

  • A word, including most punctuation marks

  • Opening or closing parentheses, braces, brackets; comma; speech marks

The features for each token are computed on demand using the sentence_features method, which returns a list of dictionaries. Each dictionary is the feature set for each token.

The sentence features can then be passed to the CRF model which will generate the parsed output.

sentence_features() → list[dict[str, str | bool]][source]#

Return dict of features for each token in sentence.

This is done in two stages: 1. Calculate the common features that every token has. 2. Calculate the features for the context of each token by looking up the

features from the common features for the context tokens.

This two stage approach avoids calculating each feature for every token and every time each token is a context token, which improves performance.

Returns:
list[FeatureDict]

List of feature dicts for each token in sentence.