sadpandajoe commented on code in PR #41028: URL: https://github.com/apache/superset/pull/41028#discussion_r3685936880
########## superset/utils/number_format.py: ########## @@ -0,0 +1,375 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. + +Only d3-format specifiers (and the ``SMART_NUMBER`` pseudo-formats) are ported. +Non-d3 presets such as ``DURATION``, ``DURATION_SUB`` and the ``MEMORY_*`` +formatters are not supported: they do not parse as a d3 specifier and fall back +to the raw value, so a column using one of those renders unformatted in reports. +The fill/align/zero/width specifier flags (absent from every preset, reachable +only by hand-typed formats) are parsed but not rendered: the numeric content +(precision, grouping, sign) is still formatted correctly, only the padding is +omitted. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from functools import lru_cache +from typing import Any + +from babel.numbers import format_currency, get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" Review Comment: Hard-coding `en_US` makes reports disagree with Explore on non-English deployments when `symbolPosition` is unset: for example the frontend uses the configured `fr_FR` locale and places EUR after the value, while this always resolves it with English rules. Can this use the configured/request locale instead? ########## superset/charts/client_processing.py: ########## @@ -278,6 +300,44 @@ def pivot_table_v2( show_columns_total=bool(form_data.get("colTotals")), apply_metrics_on_rows=form_data.get("metricsLayout") == "ROWS", ) + if apply_number_format: + return apply_pivot_number_formats(pivoted, form_data, detected_currency) + return pivoted + + +def apply_pivot_number_formats( + df: pd.DataFrame, + form_data: dict[str, Any], + detected_currency: Optional[str] = None, +) -> pd.DataFrame: + """ + Apply `valueFormat`/`columnFormats` and currency config to pivot values. + + The metric name is the first column level, or the last when `combineMetric` + moves it there; in the ROWS metrics layout it is on the index instead. + Per-metric overrides fall back to the global value format. + """ + value_format = form_data.get("valueFormat") + column_formats = form_data.get("columnFormats") or {} Review Comment: Saved metric formats still disappear from report text because both frontend plugins read per-metric formats from `datasource.columnFormats`, while this reads `columnFormats` from form data (and `table()` ignores `datasource` entirely). Could this merge `datasource.data["column_formats"]` with chart overrides and cover a saved metric format with no chart-level override? ########## superset/utils/number_format.py: ########## @@ -0,0 +1,375 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. + +Only d3-format specifiers (and the ``SMART_NUMBER`` pseudo-formats) are ported. +Non-d3 presets such as ``DURATION``, ``DURATION_SUB`` and the ``MEMORY_*`` +formatters are not supported: they do not parse as a d3 specifier and fall back +to the raw value, so a column using one of those renders unformatted in reports. +The fill/align/zero/width specifier flags (absent from every preset, reachable +only by hand-typed formats) are parsed but not rendered: the numeric content +(precision, grouping, sign) is still formatted correctly, only the padding is +omitted. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from functools import lru_cache +from typing import Any + +from babel.numbers import format_currency, get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def resolve_auto_currency( + currency: dict[str, Any], detected_currency: str | None +) -> dict[str, Any]: + """ + Resolve an ``AUTO`` currency to the code detected from the data. + + Mirrors the frontend's ``resolveAutoCurrency``: without a detected currency + (mixed-currency data) the config stays ``AUTO``, which renders the bare + number. + """ + if currency.get("symbol") == AUTO_CURRENCY and detected_currency: + return {**currency, "symbol": detected_currency} + return currency + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)): + return value + if isinstance(value, Decimal): + value = float(value) + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + try: + return apply_currency(formatted, currency) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + return formatted + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: + """ + Format ``value`` according to a d3 number format. + + Delegates to the smart-number formatter for the ``SMART_NUMBER`` and + ``SMART_NUMBER_SIGNED`` pseudo-formats, and to the d3 specifier parser for + every other format string. + """ + if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED): + return format_smart_number(value, signed=d3_format == SMART_NUMBER_SIGNED) + return format_d3(d3_format, value) + + +def format_d3(d3_format: str, value: float) -> str: + """ + Format ``value`` with a d3-format specifier. + + Supports the subset of the specifier grammar the Table/Pivot plugins emit: + the ``+ - ( space`` sign modes, the ``$`` currency prefix, the ``,`` group + separator, ``.precision``, the ``~`` trim flag, and the ``s`` (SI), ``r`` + (significant), ``d`` (integer), ``f``/``e``/``g``/``%`` numeric types. + Returns the formatted string and raises ``ValueError`` for an unparseable + specifier. + """ + match = D3_FORMAT_RE.match(d3_format) + if not match: + raise ValueError(d3_format) + + sign_mode = match.group(3) or "-" + currency_symbol = match.group(4) == "$" + comma = "," if match.group(7) else "" + precision = int(match.group(8)) if match.group(8) is not None else None + trim = bool(match.group(9)) + type_ = (match.group(10) or "").lower() + + magnitude = abs(value) + if type_ == "s": + formatted = format_si( + magnitude, precision if precision is not None else 6, trim + ) + elif type_ == "r": + formatted = format_significant( + magnitude, precision if precision is not None else 6, trim, comma + ) + elif type_ == "" and precision is None: + formatted = format_default(magnitude, comma) + else: + if type_ == "d": + formatted = format(int(quantize_half_up(magnitude, 0)), f"{comma}d") + elif type_ in ("f", "%") and precision is not None: + scaled = magnitude * 100 if type_ == "%" else magnitude + suffix = "%" if type_ == "%" else "" + rounded = quantize_half_up(scaled, precision) + formatted = format(rounded, f"{comma}.{precision}f") + suffix + else: + decimals = f".{precision}" if precision is not None else "" + formatted = format(magnitude, f"{comma}{decimals}{type_}") + formatted = normalize_exponent(formatted) + formatted = trim_trailing_zeros(formatted) if trim else formatted + + if currency_symbol: + formatted = f"${formatted}" + return apply_sign(formatted, value, sign_mode) + + +def apply_sign(formatted: str, value: float, sign_mode: str) -> str: + """ + Decorate a formatted magnitude with the d3 sign mode. + + Negative values get a leading ``-`` (or wrapping parentheses for the ``(`` + accounting mode); positive values get a ``+`` or a leading space only for the + ``+`` and space modes respectively. + """ + if value < 0: + return f"({formatted})" if sign_mode == "(" else f"-{formatted}" + if sign_mode == "+": + return f"+{formatted}" + if sign_mode == " ": + return f" {formatted}" + return formatted + + +def format_default(value: float, comma: str) -> str: + """ + Format ``value`` the way d3's default (no-type) specifier does. + + Mirrors JavaScript's ``Number.toString``: the shortest decimal representation + with optional grouping and no trailing zeros, so whole-valued floats render + without a spurious ``.0`` (``4725.0`` -> ``4,725``) and small values stay in + fixed-point notation (``0.00005`` rather than ``5e-5``). + """ + formatted = format(Decimal(repr(value)), f"{comma}f") Review Comment: The `,` preset diverges from d3 at its scientific-notation thresholds: for example d3 renders `5e-7` and `1e+21`, but this fixed-point conversion produces `0.0000005` and `1,000,000,000,000,000,000,000`. Can this preserve d3's exponent behavior for very small and large values? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
