# unite -> mL/g ; densites ; items comptes -> grammes.
UNIT = {"cup": (236.588, False), "cups": (236.588, False),
"tablespoon": (14.7868, False), "tablespoons": (14.7868, False), "tbsp": (14.7868, False), "tbs": (14.7868, False),
"teaspoon": (4.92892, False), "teaspoons": (4.92892, False), "tsp": (4.92892, False),
"ounce": (28.3495, True), "ounces": (28.3495, True), "oz": (28.3495, True),
"pound": (453.592, True), "pounds": (453.592, True), "lb": (453.592, True), "lbs": (453.592, True),
"gram": (1, True), "grams": (1, True), "g": (1, True), "kg": (1000, True), "kilogram": (1000, True),
"ml": (1, False), "milliliter": (1, False), "millilitre": (1, False),
"l": (1000, False), "liter": (1000, False), "litre": (1000, False),
"pint": (473.176, False), "pt": (473.176, False), "quart": (946.353, False), "qt": (946.353, False),
"gallon": (3785.41, False), "gal": (3785.41, False),
"pinch": (0.36, True), "dash": (0.6, False), "stick": (113.0, True), "sticks": (113.0, True)}
DENS = [("flour", 0.53), ("sugar", 0.85), ("oil", 0.92), ("butter", 0.911), ("honey", 1.42),
("syrup", 1.33), ("milk", 1.03), ("cream", 1.01), ("water", 1.0), ("salt", 1.22),
("rice", 0.85), ("cocoa", 0.52), ("cornstarch", 0.54), ("oats", 0.41)]
COUNT = [("egg", 50), ("banana", 120), ("apple", 180), ("onion", 110), ("clove", 5),
("carrot", 60), ("potato", 150), ("tomato", 120), ("lemon", 60), ("lime", 45),
("orange", 130), ("garlic", 5), ("shallot", 30), ("scallion", 15), ("pepper", 120)]
def density(item_lower):
for kw, d in DENS:
if kw in item_lower: return d
return 1.0
def count_weight(item_lower):
for kw, g in COUNT:
if kw in item_lower: return g
return 0.0
def to_grams(qty, unit, item_lower):
if qty <= 0: return 0.0
if not unit:
cw = count_weight(item_lower)
return qty * cw if cw > 0 else 0.0
u = UNIT.get(unit)
if u is None: return 0.0
factor, is_mass = u
return qty * factor if is_mass else qty * factor * density(item_lower)
for q, u, it in [(2.0, "cups", "white sugar"), (2.0, "cups", "flour"), (1.0, "teaspoon", "vanilla"),
(4.0, "ounces", "butter"), (2.0, "", "eggs"), (1.0, "can", "crushed pineapple")]:
g = to_grams(q, u, it)
print(f" {q} {(u or '(compte)'):10} {it:18} -> {g:.1f} g" + (" (non convertible)" if g == 0 else ""))