Utils API

The utils module provides utility functions for unit conversion and measurement handling.

Unit Conversion

usda_fdc.utils.parse_unit_and_value(measurement_str)[source]

Parse a measurement string into a value and unit.

Parameters:

measurement_str (str) – A string containing a measurement (e.g., “100 g”, “1 cup”).

Returns:

A tuple of (value, unit).

Return type:

Tuple[float, str]

usda_fdc.utils.convert_to_grams(amount, unit)[source]

Convert a measurement to grams.

Parameters:
  • amount (float) – The amount to convert.

  • unit (str) – The unit to convert from.

Returns:

The equivalent amount in grams.

Raises:

ValueError – If the unit cannot be converted to grams.

Return type:

float

usda_fdc.utils.convert_to_milliliters(amount, unit)[source]

Convert a measurement to milliliters.

Parameters:
  • amount (float) – The amount to convert.

  • unit (str) – The unit to convert from.

Returns:

The equivalent amount in milliliters.

Raises:

ValueError – If the unit cannot be converted to milliliters.

Return type:

float

usda_fdc.utils.convert_measurement(amount, from_unit, to_unit)[source]

Convert a measurement from one unit to another.

Parameters:
  • amount (float) – The amount to convert.

  • from_unit (str) – The unit to convert from.

  • to_unit (str) – The unit to convert to.

Returns:

The converted amount.

Raises:

ValueError – If the conversion is not possible.

Return type:

float

usda_fdc.utils.normalize_nutrient_value(value, unit, target_unit='g')[source]

Normalize a nutrient value to a standard unit.

Parameters:
  • value (float) – The nutrient value.

  • unit (str) – The unit of the nutrient value.

  • target_unit (str) – The target unit to normalize to.

Returns:

A tuple of (normalized_value, normalized_unit).

Return type:

Tuple[float, str]