munch-ease-backend/units.py

46 lines
2.2 KiB
Python
Raw Normal View History

2024-01-13 05:40:10 +00:00
from typing import Union
class Unit:
def __init__(self, name: str, symbols: list, unit_type: str, conversion_to_base: float = 1.0):
self.name = name
self.symbols = symbols
self.unit_type = unit_type
self.conversion_to_base = conversion_to_base
def convert_to_base(self, quantity: float) -> float:
"""Converts a quantity to the base unit."""
return quantity * self.conversion_to_base
def convert_from_base(self, quantity: float) -> float:
"""Converts a quantity from the base unit to this unit."""
return quantity / self.conversion_to_base
# Define common base units in SI units
ITEMS = Unit("Items", ["item", "items"], "count", 1)
LITRE = Unit("Litre", ["litre", "liter", "l"], "volume", 1)
2024-01-13 23:41:15 +00:00
GRAM = Unit("Gram", ["gram", "grams", "g", "gm"], "weight", 1)
2024-01-13 05:40:10 +00:00
# Add conversion factors for common cooking measurements
CUP = Unit("Cup", ["cup", "cups", "c"], "volume", 240)
TABLESPOON = Unit("Tablespoon", ["tablespoon", "tablespoons", "tbsp", "tbsps"], "volume", 15)
TEASPOON = Unit("Teaspoon", ["teaspoon", "teaspoons", "tsp", "tsps"], "volume", 5)
2024-01-13 05:40:10 +00:00
OUNCE = Unit("Ounce", ["ounce", "ounces", "oz"], "weight", 28.3495)
POUND = Unit("Pound", ["pound", "pounds", "lb", "lbs"], "weight", 453.592)
2024-01-13 05:40:10 +00:00
FLUID_OUNCE = Unit("Fluid Ounce", ["fluid ounce", "fl oz"], "volume", 29.5735)
PINT = Unit("Pint", ["pint", "pt"], "volume", 473.176)
QUART = Unit("Quart", ["quart", "qt"], "volume", 946.353)
GALLON = Unit("Gallon", ["gallon", "gal"], "volume", 3785.41)
MILLILITRE = Unit("Millilitre", ["millilitre", "millilitres", "ml"], "volume", 1)
MILLIGRAM = Unit("Milligram", ["milligram", "milligrams", "mg"], "weight", 1)
KILOGRAM = Unit("Kilogram", ["kilogram", "kilograms", "kg"], "weight", 1000)
# Big list of units
ALL_UNITS = [ITEMS, LITRE, GRAM, CUP, TABLESPOON, TEASPOON, OUNCE, POUND, FLUID_OUNCE, PINT, QUART, GALLON, MILLILITRE, MILLIGRAM, KILOGRAM]
def get_unit(alias: str) -> Union[Unit, None]:
"""Returns the corresponding unit based on alias or abbreviation."""
alias_lower = alias.lower()
for unit in ALL_UNITS:
if alias_lower in unit.symbols or alias_lower == unit.name.lower():
return unit
return None