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) GRAM = Unit("Gram", ["gram", "grams", "g", "gm"], "weight", 1) # 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) OUNCE = Unit("Ounce", ["ounce", "ounces", "oz"], "weight", 28.3495) POUND = Unit("Pound", ["pound", "pounds", "lb", "lbs"], "weight", 453.592) 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