QoL and metric value inverter
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
@@ -53,10 +54,54 @@ def close_db(exc: BaseException | None = None) -> None:
|
||||
repo.conn.close()
|
||||
|
||||
|
||||
_SI_PREFIXES = [
|
||||
(1e12, "T"),
|
||||
(1e9, "G"),
|
||||
(1e6, "M"),
|
||||
(1e3, "k"),
|
||||
]
|
||||
|
||||
|
||||
def _si_format(value: object) -> str:
|
||||
"""Format a number with SI prefixes for readability.
|
||||
|
||||
Handles string inputs (like dep.value) by trying float conversion first.
|
||||
Non-numeric values are returned as-is.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
num = float(value)
|
||||
except (ValueError, TypeError):
|
||||
return value
|
||||
elif isinstance(value, (int, float)):
|
||||
num = float(value)
|
||||
else:
|
||||
return str(value)
|
||||
|
||||
if math.isnan(num) or math.isinf(num):
|
||||
return str(value)
|
||||
|
||||
abs_num = abs(num)
|
||||
if abs_num < 1000:
|
||||
# Small numbers: drop trailing zeros, cap at 4 significant figures
|
||||
if num == int(num) and abs_num < 100:
|
||||
return str(int(num))
|
||||
return f"{num:.4g}"
|
||||
|
||||
for threshold, prefix in _SI_PREFIXES:
|
||||
if abs_num >= threshold:
|
||||
scaled = num / threshold
|
||||
return f"{scaled:.4g}{prefix}"
|
||||
|
||||
return f"{num:.4g}"
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.secret_key = _load_or_generate_secret_key()
|
||||
|
||||
app.jinja_env.filters["si"] = _si_format
|
||||
|
||||
app.teardown_appcontext(close_db)
|
||||
|
||||
# Register blueprints
|
||||
|
||||
Reference in New Issue
Block a user