Files
mealie/dev/code-generation/gen_ts_unit_systems.py
T

108 lines
3.5 KiB
Python

from jinja2 import Template
from unit_systems import UnitDimension, UnitSystem, build_table
from utils import CodeDest, log
UNIT_SYSTEMS_TEMPLATE = """// This Code is auto generated by gen_ts_unit_systems.py
export type UnitDimension = {{ dimension_union }};
export type UnitSystem = {{ system_union }};
export interface StandardizedUnit {
dimension: UnitDimension;
/** How many base units (grams for mass, millilitres for volume) are in one of this unit. */
base: number;
/** Customary rather than metric, so a recipe using it is already in a customary system. */
customary: boolean;
}
export interface UnitRung {
/** The pint unit name. */
unit: string;
/** Key into the seeded unit names merged into i18n messages under `unit-names`. */
seedKey: string;
base: number;
/** Whole units needed before this rung takes over from the one below it. */
takeover: number;
fraction: boolean;
}
export const STANDARDIZED_UNITS: Record<string, StandardizedUnit> = {
{%- for name, unit in units.items() %}
{{ name }}: { dimension: "{{ unit.dimension }}", base: {{ unit.base }}, customary: {{ unit.customary }} },
{%- endfor %}
};
/** Systems made of customary units. An ingredient already in the reader's system is left alone. */
export const CUSTOMARY_SYSTEMS: UnitSystem[] = [{{ customary_systems }}];
export const UNIT_SYSTEMS: Record<UnitSystem, Record<UnitDimension, UnitRung[]>> = {
{%- for system, dimensions in systems.items() %}
{{ system }}: {
{%- for dimension, rungs in dimensions.items() %}
{{ dimension }}: [
{%- for rung in rungs %}
{{ rung }},
{%- endfor %}
],
{%- endfor %}
},
{%- endfor %}
};
"""
def number(value: float) -> str:
"""Render a float without the noise pint's arithmetic leaves behind.
Pint computes `pound` as 453.5923700000001 and `cup` as 236.58823649999994; the trailing
digits are artifacts of operation order rather than precision. 14 significant digits sits
well inside a double and recovers the exact defined values.
"""
return repr(float(f"{value:.14g}"))
def rung_literal(rung: dict) -> str:
"""Render one rung as a single-line object literal, so the template stays readable."""
return (
f'{{ unit: "{rung["unit"]}", seedKey: "{rung["seed_key"]}", base: {number(rung["base"])}, '
f"takeover: {number(rung['takeover'])}, fraction: {'true' if rung['fraction'] else 'false'} }}"
)
def generate_unit_systems_ts_file():
table = build_table()
tmpl = Template(UNIT_SYSTEMS_TEMPLATE)
rendered = tmpl.render(
dimension_union=" | ".join(f'"{dimension.value}"' for dimension in UnitDimension),
system_union=" | ".join(f'"{system.value}"' for system in UnitSystem),
units={
name: {
"dimension": unit["dimension"],
"base": number(unit["base"]),
"customary": "true" if unit["customary"] else "false",
}
for name, unit in table["units"].items()
},
customary_systems=", ".join(f'"{system}"' for system in table["customary_systems"]),
systems={
system: {dimension: [rung_literal(rung) for rung in rungs] for dimension, rungs in dimensions.items()}
for system, dimensions in table["systems"].items()
},
)
log.debug(f"generating unit systems ts file -> {CodeDest.unit_systems}")
with open(CodeDest.unit_systems, "w") as f:
f.write(rendered)
def main():
generate_unit_systems_ts_file()
if __name__ == "__main__":
main()