Files
44-Scale/web/app.py
T
2026-07-31 14:59:51 +02:00

726 lines
24 KiB
Python

import base64
import math
import pathlib
from collections import namedtuple
from flask import Flask, render_template, request, Response
from html import escape
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
app = Flask(__name__)
VERSION = "1.0"
_LOGO_PATH = pathlib.Path(__file__).parent / "static" / "logo.png"
_LOGO_B64 = base64.b64encode(_LOGO_PATH.read_bytes()).decode()
_FontData = namedtuple(
"_FontData", ["key", "label", "b64", "glyph_set", "cmap", "hmtx", "upm", "glyf"]
)
_FONT_LABELS = {
"GOST_2.30481_type_A": "GOST Type A",
"GOST_2.30481_type_A_Bold": "GOST Type A Bold",
"Gost2.30481TypeB": "GOST Type B",
"ISOCPEUR": "ISOCPEUR",
"SIEMENS_GOST_Type_A": "Siemens GOST Type A",
"TGL_31034-1": "TGL 31 034",
"alte-din-1451-mittelschrift.regular": "Alte DIN 1451 Mittelschrift",
"alte-din-1451-mittelschrift.gepraegt": "Alte DIN 1451 Mittelschrift (Gepraegt)",
}
def _load_fonts():
font_dir = pathlib.Path(__file__).parent / "fonts"
if not font_dir.exists():
font_dir = pathlib.Path(__file__).parent.parent / "fonts"
fonts = {}
for path in sorted(font_dir.glob("*.ttf")):
key = path.stem
obj = TTFont(str(path))
fonts[key] = _FontData(
key=key,
label=_FONT_LABELS.get(key, key.replace("_", " ")),
b64=base64.b64encode(path.read_bytes()).decode(),
glyph_set=obj.getGlyphSet(),
cmap=obj.getBestCmap(),
hmtx=obj["hmtx"].metrics,
upm=obj["head"].unitsPerEm,
glyf=obj["glyf"],
)
return fonts
_FONTS = _load_fonts()
_DEFAULT_FONT = "alte-din-1451-mittelschrift.regular"
# SVG absolute coordinate constants (1 user unit = 1 mm), pre-layer-translate
# local frame — the <g> wrapper applies translate(-60.717741,-107.14126).
PIVOT_X, PIVOT_Y = 107.42845, 162.62819
R0 = 43.842751 # rim / inner-tick radius
ANGLE_MIN, ANGLE_MAX = (
-45.667193,
45.667193,
) # degrees from vertical, clockwise-positive
MAJOR_LEN, MAJOR_W = 4.7839203, 0.79658329
MEDIUM_LEN, MEDIUM_W = 3.1215858, 0.37985462
SMALL_LEN, SMALL_W = 1.8121802, 0.27478597
LABEL_RADIUS = 49.862
UNIT_X, UNIT_Y = 107.03512, 136.64594
LEFT_X, LEFT_Y0 = 73.432251, 145.16051
RIGHT_X, RIGHT_Y0 = 142.4485, 145.32773
CORNER_LINE_SPACING = 4.4586
CORNER_FONT_SIZE = 3.56685
PIVOT_CIRCLE_R = 1.7287594
BODY_D = (
"m 62.162097,107.14126 c -0.800087,0 -1.444356,0.64428 -1.444356,1.44436 v 45.44839 "
"c 0,0.80008 0.644269,1.44436 1.444356,1.44436 h 7.345288 c 0.902634,0 1.233517,1.12706 "
"1.233517,1.12706 l 0.09043,3.03909 21.903573,-0.0904 2.226221,-5.98775 c 8.352594,-2.8884 "
"16.624974,-2.8884 24.817094,0 l 2.22674,5.98775 21.90357,0.0904 0.0904,-3.03909 c 0,0 "
"0.33088,-1.12706 1.23352,-1.12706 h 7.86567 c 0.80009,0 1.44384,-0.64428 1.44384,-1.44436 "
"v -45.44839 c 0,-0.80008 -0.64375,-1.44436 -1.44384,-1.44436 z m 29.619898,45.85354 "
"a 1.3990685,1.3990685 0 0 1 1.398881,1.39939 1.3990685,1.3990685 0 0 1 -1.398881,1.39888 "
"1.3990685,1.3990685 0 0 1 -1.399398,-1.39888 1.3990685,1.3990685 0 0 1 1.399398,-1.39939 "
"z m 31.220835,0 a 1.3990685,1.3990685 0 0 1 1.39888,1.39939 1.3990685,1.3990685 0 0 1 "
"-1.39888,1.39888 1.3990685,1.3990685 0 0 1 -1.3994,-1.39888 1.3990685,1.3990685 0 0 1 "
"1.3994,-1.39939 z"
)
# --- Inline markup for the unit label -------------------------------------
_SUP_SCALE = 0.62
_SUP_RISE = 0.36
_SUB_DROP = 0.14
_FRAC_SCALE = 0.62
_FRAC_AXIS = 0.32
_FRAC_GAP = 0.14
_FRAC_SIDE = 0.12
_SYM_WIDTH = 0.75
_SYM_HEIGHT = 0.50
_SYM_LW = 0.08
_SYM_RISE = 0.25
def _symbol_svg(name: str, x: float, y: float, fs: float, fill: str) -> str:
w = fs * _SYM_WIDTH
h = fs * _SYM_HEIGHT
lw = fs * _SYM_LW
yc = y - _SYM_RISE * fs
stroke = f"fill:none;stroke:{fill};stroke-width:{lw:.5f};stroke-linecap:round"
if name == "ac":
d = (
f"M {x:.5f},{yc:.5f}"
f" C {x + w / 3:.5f},{yc - h / 2:.5f}"
f" {x + 2 * w / 3:.5f},{yc + h / 2:.5f}"
f" {x + w:.5f},{yc:.5f}"
)
return f'<path style="{stroke}" d="{d}"/>'
elif name == "dc":
dash = w / 5
gap = w / 5
y1 = yc - h / 4
y2 = yc + h / 4
p1 = f'<line x1="{x:.5f}" y1="{y1:.5f}" x2="{x + w:.5f}" y2="{y1:.5f}" style="{stroke}" />'
p2 = f'<line x1="{x:.5f}" y1="{y2:.5f}" x2="{x + dash:.5f}" y2="{y2:.5f}" style="{stroke}" />'
p3 = f'<line x1="{x + dash + gap:.5f}" y1="{y2:.5f}" x2="{x + 2 * dash + gap:.5f}" y2="{y2:.5f}" style="{stroke}" />'
p4 = f'<line x1="{x + 2 * dash + 2 * gap:.5f}" y1="{y2:.5f}" x2="{x + w:.5f}" y2="{y2:.5f}" style="{stroke}" />'
return p1 + "\n " + p2 + "\n " + p3 + "\n " + p4
else: # acdc
y_wave = yc - h / 4
y_dash = yc + h / 4
dash = w / 5
gap = w / 5
d = (
f"M {x:.5f},{y_wave:.5f}"
f" C {x + w / 3:.5f},{y_wave - h / 2:.5f}"
f" {x + 2 * w / 3:.5f},{y_wave + h / 2:.5f}"
f" {x + w:.5f},{y_wave:.5f}"
)
p1 = f'<path style="{stroke}" d="{d}"/>'
p2 = f'<line x1="{x:.5f}" y1="{y_dash:.5f}" x2="{x + dash:.5f}" y2="{y_dash:.5f}" style="{stroke}" />'
p3 = f'<line x1="{x + dash + gap:.5f}" y1="{y_dash:.5f}" x2="{x + 2 * dash + gap:.5f}" y2="{y_dash:.5f}" style="{stroke}" />'
p4 = f'<line x1="{x + 2 * dash + 2 * gap:.5f}" y1="{y_dash:.5f}" x2="{x + w:.5f}" y2="{y_dash:.5f}" style="{stroke}" />'
return p1 + "\n " + p2 + "\n " + p3 + "\n " + p4
_UNIT_BOX_X0, _UNIT_BOX_X1 = UNIT_X - 15.0, UNIT_X + 15.0
_UNIT_BOX_Y0, _UNIT_BOX_Y1 = UNIT_Y - 6.0, UNIT_Y + 6.0
_UNIT_MAX_FS = 9.46938021
def _point_at(radius: float, angle_deg: float):
th = math.radians(angle_deg)
return PIVOT_X + radius * math.sin(th), PIVOT_Y - radius * math.cos(th)
def _glyph_svg(ch: str, x: float, y: float, fs: float, fill: str, fd: _FontData):
gn = fd.cmap.get(ord(ch))
if gn is None:
return None, 0.0
s = fs / fd.upm
adv = fd.hmtx.get(gn, (0, 0))[0] * s
pen = SVGPathPen(fd.glyph_set)
fd.glyph_set[gn].draw(pen)
d = pen.getCommands()
if not d:
return None, adv
t = f"translate({x:.5f},{y:.5f}) scale({s:.8f},{-s:.8f})"
return f'<path style="fill:{fill}" transform="{t}" d="{d}"/>', adv
def _glyph_ybounds(ch: str, fd: _FontData):
gn = fd.cmap.get(ord(ch))
if gn is None:
return 0.0, 0.0
g = fd.glyf[gn]
if g.numberOfContours == 0:
return 0.0, 0.0
g.recalcBounds(fd.glyf)
return g.yMin / fd.upm, g.yMax / fd.upm
def _extract_braced(s: str, i: int):
depth, j = 1, i + 1
while j < len(s) and depth:
if s[j] == "{":
depth += 1
elif s[j] == "}":
depth -= 1
if depth == 0:
break
j += 1
return s[i + 1 : j], j + 1
def _parse_braced(inner: str):
depth = 0
for k, ch in enumerate(inner):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
elif ch == "/" and depth == 0:
return ("frac", _parse_markup(inner[:k]), _parse_markup(inner[k + 1 :]))
return ("group", _parse_markup(inner))
def _parse_atom(s: str, i: int):
if i >= len(s):
return [], i
if s[i] == "{":
inner, j = _extract_braced(s, i)
return [_parse_braced(inner)], j
return [("lit", s[i])], i + 1
def _parse_markup(s: str):
nodes, i = [], 0
while i < len(s):
c = s[i]
if c in "^_":
atom, i = _parse_atom(s, i + 1)
nodes.append(("sup" if c == "^" else "sub", atom))
elif c == "{":
inner, j = _extract_braced(s, i)
nodes.append(_parse_braced(inner))
i = j
elif c == "[":
end = s.find("]", i + 1)
if end > i:
name = s[i + 1 : end].lower()
if name in ("ac", "dc", "acdc"):
nodes.append(("sym", name))
i = end + 1
continue
nodes.append(("lit", c))
i += 1
else:
nodes.append(("lit", c))
i += 1
return nodes
def _measure(nodes, fs: float, fd: _FontData) -> float:
w = 0.0
for n in nodes:
if n[0] == "lit":
gn = fd.cmap.get(ord(n[1]))
if gn:
w += fd.hmtx.get(gn, (0, 0))[0] / fd.upm * fs
elif n[0] == "group":
w += _measure(n[1], fs, fd)
elif n[0] in ("sup", "sub"):
w += _measure(n[1], fs * _SUP_SCALE, fd)
elif n[0] == "frac":
fs2 = fs * _FRAC_SCALE
w += (
max(_measure(n[1], fs2, fd), _measure(n[2], fs2, fd))
+ 2 * _FRAC_SIDE * fs2
)
elif n[0] == "sym":
w += fs * _SYM_WIDTH
return w
def _frac_layout(n, fs: float, fd: _FontData):
fs2 = fs * _FRAC_SCALE
axis = -_FRAC_AXIS * fs
_, num_bot = _vbounds(n[1], fs2, fd)
num_base = axis - _FRAC_GAP * fs2 - num_bot
den_top, _ = _vbounds(n[2], fs2, fd)
den_base = axis + _FRAC_GAP * fs2 - den_top
return fs2, axis, num_base, den_base
def _vbounds(nodes, fs: float, fd: _FontData):
lo, hi = math.inf, -math.inf
for n in nodes:
if n[0] == "lit":
ymin, ymax = _glyph_ybounds(n[1], fd)
a, b = -ymax * fs, -ymin * fs
elif n[0] == "group":
a, b = _vbounds(n[1], fs, fd)
elif n[0] == "sup":
a, b = _vbounds(n[1], fs * _SUP_SCALE, fd)
a, b = a - _SUP_RISE * fs, b - _SUP_RISE * fs
elif n[0] == "sub":
a, b = _vbounds(n[1], fs * _SUP_SCALE, fd)
a, b = a + _SUB_DROP * fs, b + _SUB_DROP * fs
elif n[0] == "frac":
fs2, axis, num_base, den_base = _frac_layout(n, fs, fd)
nt, nb = _vbounds(n[1], fs2, fd)
dt, db = _vbounds(n[2], fs2, fd)
a = min(nt + num_base, axis)
b = max(db + den_base, axis)
elif n[0] == "sym":
a, b = -_SYM_HEIGHT / 2 * fs, _SYM_HEIGHT / 2 * fs
else:
continue
lo, hi = min(lo, a), max(hi, b)
return (0.0, 0.0) if lo > hi else (lo, hi)
def _draw_nodes(nodes, x: float, y: float, fs: float, fill: str, fd: _FontData):
parts, cx = [], x
for n in nodes:
if n[0] == "lit":
p, adv = _glyph_svg(n[1], cx, y, fs, fill, fd)
if p:
parts.append(p)
cx += adv
elif n[0] == "group":
p, adv = _draw_nodes(n[1], cx, y, fs, fill, fd)
parts += p
cx += adv
elif n[0] in ("sup", "sub"):
fs2 = fs * _SUP_SCALE
y2 = y - _SUP_RISE * fs if n[0] == "sup" else y + _SUB_DROP * fs
p, adv = _draw_nodes(n[1], cx, y2, fs2, fill, fd)
parts += p
cx += adv
elif n[0] == "frac":
fs2, axis, num_base, den_base = _frac_layout(n, fs, fd)
wn, wd = _measure(n[1], fs2, fd), _measure(n[2], fs2, fd)
bar_w = max(wn, wd) + 2 * _FRAC_SIDE * fs2
pn, _ = _draw_nodes(
n[1], cx + (bar_w - wn) / 2, y + num_base, fs2, fill, fd
)
pd, _ = _draw_nodes(
n[2], cx + (bar_w - wd) / 2, y + den_base, fs2, fill, fd
)
parts += pn + pd
ay = y + axis
parts.append(
f'<line x1="{cx:.5f}" y1="{ay:.5f}" x2="{cx + bar_w:.5f}" y2="{ay:.5f}"'
f' style="stroke:{fill};stroke-width:{fs * 0.055:.5f};stroke-linecap:butt" />'
)
cx += bar_w
elif n[0] == "sym":
parts.append(_symbol_svg(n[1], cx, y, fs, fill))
cx += fs * _SYM_WIDTH
return parts, cx - x
def _markup_unit_svg(unit: str, fd: _FontData, fill="#1a1a1a") -> str:
nodes = _parse_markup(unit)
x0, x1 = _UNIT_BOX_X0, _UNIT_BOX_X1
y0, y1 = _UNIT_BOX_Y0, _UNIT_BOX_Y1
xc = (x0 + x1) / 2
w1 = _measure(nodes, 1.0, fd)
top1, bot1 = _vbounds(nodes, 1.0, fd)
fs = _UNIT_MAX_FS
if w1 > 0:
fs = min(fs, (x1 - x0) / w1)
if bot1 - top1 > 0:
fs = min(fs, (y1 - y0) / (bot1 - top1))
w = _measure(nodes, fs, fd)
parts, _ = _draw_nodes(nodes, xc - w / 2, UNIT_Y, fs, fill, fd)
return "\n".join(parts)
def _markup_corner_svg(
text: str, x: float, y: float, fd: _FontData, fill="#1a1a1a", anchor="start"
) -> str:
nodes = _parse_markup(text)
fs = CORNER_FONT_SIZE
w = _measure(nodes, fs, fd)
if anchor == "end":
x -= w
parts, _ = _draw_nodes(nodes, x, y, fs, fill, fd)
return "\n".join(parts)
def _text_to_paths(
text,
x,
y,
font_size,
fd: _FontData,
anchor="start",
fill="#1a1a1a",
wrap_transform=None,
):
s = font_size / fd.upm
if anchor in ("middle", "end"):
total_w = sum(
fd.hmtx.get(fd.cmap.get(ord(ch)), (0, 0))[0] * s
for ch in text
if fd.cmap.get(ord(ch))
)
x -= total_w / 2 if anchor == "middle" else total_w
parts = []
cx = x
for ch in text:
gn = fd.cmap.get(ord(ch))
if gn is None:
continue
pen = SVGPathPen(fd.glyph_set)
fd.glyph_set[gn].draw(pen)
d = pen.getCommands()
if d:
t = f"translate({cx:.5f},{y:.5f}) scale({s:.8f},{-s:.8f})"
parts.append(f'<path style="fill:{fill}" transform="{t}" d="{d}"/>')
cx += fd.hmtx.get(gn, (0, 0))[0] * s
inner = "\n".join(parts)
if wrap_transform:
return f'<g transform="{wrap_transform}">{inner}</g>'
return inner
def _fmt(v: float) -> str:
if math.isinf(v):
return ""
r = round(v)
if abs(v - r) < 1e-9 * max(1.0, abs(v)):
return str(int(r))
exp = math.floor(math.log10(abs(v)))
decimals = max(0, 4 - 1 - exp)
s = f"{v:.{decimals}f}"
return s.rstrip("0").rstrip(".") if "." in s else s
def generate_svg(
unit,
min_val,
max_val,
left_label,
right_label,
big_ticks,
small_ticks,
label_count,
use_paths=True,
scale_type="linear",
custom_labels=None,
label_size=5.1126,
font_key=None,
major_len=MAJOR_LEN,
major_w=MAJOR_W,
medium_len=MEDIUM_LEN,
medium_w=MEDIUM_W,
small_len=SMALL_LEN,
small_w=SMALL_W,
):
fd = (
_FONTS.get(font_key) or _FONTS.get(_DEFAULT_FONT) or next(iter(_FONTS.values()))
)
if scale_type == "log":
if min_val <= 0 or max_val <= 0:
raise ValueError(
"Logarithmic scale requires min and max values greater than 0."
)
lmin, lmax = math.log(min_val), math.log(max_val)
lspan = lmax - lmin
if lspan == 0:
raise ValueError("Logarithmic scale requires min and max values to differ.")
def value_to_angle(v):
return ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * (math.log(v) - lmin) / lspan
def major_value(i):
return min_val * (max_val / min_val) ** (i / big_ticks)
elif scale_type == "sqrt":
if min_val < 0:
raise ValueError("Square-root scale requires min value ≥ 0.")
span = max_val - min_val
if span <= 0:
raise ValueError("Square-root scale requires max value greater than min.")
def value_to_angle(v):
return ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * math.sqrt((v - min_val) / span)
def major_value(i):
return min_val + span * (i / big_ticks) ** 2
elif scale_type == "reciprocal":
if min_val <= 0:
raise ValueError(
"Reciprocal scale requires min and max values greater than 0."
)
if not math.isinf(max_val) and max_val <= min_val:
raise ValueError("Reciprocal scale requires max value greater than min.")
if math.isinf(max_val):
def value_to_angle(v):
if math.isinf(v):
return ANGLE_MIN
return ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * min_val / v
def major_value(i):
if i == 0:
return math.inf
return min_val * big_ticks / i
else:
k = 1.0 / min_val - 1.0 / max_val
def value_to_angle(v):
return (
ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * (1.0 / v - 1.0 / max_val) / k
)
def major_value(i):
return 1.0 / (1.0 / max_val + i / big_ticks * k)
else:
span = max_val - min_val
if span == 0:
raise ValueError("Linear scale requires min and max values to differ.")
def value_to_angle(v):
return ANGLE_MIN + (ANGLE_MAX - ANGLE_MIN) * (v - min_val) / span
def major_value(i):
return min_val + span * i / big_ticks
big_interval_angle = (ANGLE_MAX - ANGLE_MIN) / big_ticks
big_angles = [ANGLE_MIN + i * big_interval_angle for i in range(big_ticks + 1)]
big_vals = [major_value(i) for i in range(big_ticks + 1)]
if custom_labels:
label_count = max(1, min(len(custom_labels), big_ticks + 1))
custom_labels = custom_labels[:label_count]
else:
label_count = max(2, min(label_count, big_ticks + 1))
if label_count == 1:
label_indices = [0]
else:
label_indices = [
round(k * big_ticks / (label_count - 1)) for k in range(label_count)
]
def _tick_line(angle_deg, length, width):
x = PIVOT_X
y1 = PIVOT_Y - R0
y2 = PIVOT_Y - R0 - length
return (
f' <line x1="{x:.5f}" y1="{y1:.5f}" x2="{x:.5f}" y2="{y2:.5f}"'
f' style="stroke:#1a1a1a;stroke-width:{width:.5f};stroke-linecap:butt"'
f' transform="rotate({angle_deg:.5f},{PIVOT_X:.5f},{PIVOT_Y:.5f})" />'
)
font_face = (
" <defs><style>"
f'@font-face {{font-family:"{fd.label}";'
f'src:url("data:font/truetype;base64,{fd.b64}") format("truetype");}}'
"</style></defs>"
)
parts = [
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>',
'<svg width="93.824249mm" height="57.215687mm"'
' viewBox="0 0 93.824249 57.215687" version="1.1"'
' xmlns="http://www.w3.org/2000/svg">',
]
if use_paths:
parts.append(' <g transform="translate(-60.717741,-107.14126)">')
else:
parts += [font_face, ' <g transform="translate(-60.717741,-107.14126)">']
parts.append(
f' <path style="fill:#f9f9f9;stroke:#1a1a1a;stroke-width:0.184;'
f'stroke-linecap:round;stroke-miterlimit:10" d="{BODY_D}" />'
)
p0 = _point_at(R0, ANGLE_MIN)
pmid = _point_at(R0, 0.0)
p1 = _point_at(R0, ANGLE_MAX)
parts.append(
f' <path style="fill:none;stroke:#000000;stroke-width:0.484;'
f'stroke-linecap:round;stroke-miterlimit:10"'
f' d="M {p0[0]:.5f},{p0[1]:.5f} A {R0:.5f},{R0:.5f} 0 0 1 {pmid[0]:.5f},{pmid[1]:.5f}'
f' A {R0:.5f},{R0:.5f} 0 0 1 {p1[0]:.5f},{p1[1]:.5f}" />'
)
parts.append(
f' <circle style="fill:none;stroke:#b3b3b3;stroke-width:0.184;'
f'stroke-linecap:round;stroke-miterlimit:10"'
f' cx="{PIVOT_X:.5f}" cy="{PIVOT_Y:.5f}" r="{PIVOT_CIRCLE_R:.5f}" />'
)
for angle in big_angles:
parts.append(_tick_line(angle, major_len, major_w))
if small_ticks > 0:
sub = small_ticks + 1
medium_j = sub // 2 if small_ticks % 2 == 1 else None
for i in range(big_ticks):
for j in range(1, small_ticks + 1):
if scale_type == "reciprocal":
angle = big_angles[i] + (j / sub) * (
big_angles[i + 1] - big_angles[i]
)
else:
v = big_vals[i] + j * (big_vals[i + 1] - big_vals[i]) / sub
angle = value_to_angle(v)
length, width = (
(medium_len, medium_w) if j == medium_j else (small_len, small_w)
)
parts.append(_tick_line(angle, length, width))
lx, ly = PIVOT_X, PIVOT_Y - LABEL_RADIUS
for k, idx in enumerate(label_indices):
angle = big_angles[idx]
label = custom_labels[k] if custom_labels else _fmt(big_vals[idx])
wrap = f"rotate({angle:.5f},{PIVOT_X:.5f},{PIVOT_Y:.5f})"
if use_paths:
parts.append(
" "
+ _text_to_paths(
label, lx, ly, label_size, fd, anchor="middle", wrap_transform=wrap
)
)
else:
parts.append(
f" <text style=\"font-size:{label_size:.5f}px;font-family:'{fd.label}',monospace;fill:#1a1a1a\""
f' text-anchor="middle" x="{lx:.5f}" y="{ly:.5f}" transform="{wrap}">{escape(label)}</text>'
)
parts.append(" " + _markup_unit_svg(unit, fd))
left_lines = left_label.splitlines()[:2]
right_lines = right_label.splitlines()[:2]
for i, line in enumerate(left_lines):
if not line:
continue
y = LEFT_Y0 + i * CORNER_LINE_SPACING
parts.append(" " + _markup_corner_svg(line, LEFT_X, y, fd, anchor="start"))
for i, line in enumerate(right_lines):
if not line:
continue
y = RIGHT_Y0 + i * CORNER_LINE_SPACING
parts.append(" " + _markup_corner_svg(line, RIGHT_X, y, fd, anchor="end"))
parts += [" </g>", "</svg>"]
return "\n".join(parts)
@app.route("/")
def index():
fonts = list(_FONTS.values())
return render_template(
"index.html",
logo_b64=_LOGO_B64,
version=VERSION,
fonts=fonts,
default_font=_DEFAULT_FONT,
)
@app.route("/generate", methods=["POST"])
def generate():
unit = request.form.get("unit", "%")
left_label = request.form.get("left_label", "")
right_label = request.form.get("right_label", "")
use_paths = request.form.get("output_mode", "paths") == "paths"
scale_type = request.form.get("scale_type", "linear")
font_key = request.form.get("font", _DEFAULT_FONT)
custom_labels = [
s.strip() for s in request.form.get("labels", "").split(",") if s.strip()
] or None
try:
min_val = float(request.form.get("min", 0))
max_val = float(request.form.get("max", 100))
big_ticks = max(1, min(50, int(request.form.get("big_ticks", 10))))
small_ticks = max(0, min(20, int(request.form.get("small_ticks", 4))))
label_count = max(2, int(request.form.get("label_count", 6)))
label_size = max(0.5, min(25.0, float(request.form.get("label_size", 5.1126))))
major_len = max(0.1, min(25.0, float(request.form.get("major_len", MAJOR_LEN))))
major_w = max(0.01, min(10.0, float(request.form.get("major_w", MAJOR_W))))
medium_len = max(
0.1, min(25.0, float(request.form.get("medium_len", MEDIUM_LEN)))
)
medium_w = max(0.01, min(10.0, float(request.form.get("medium_w", MEDIUM_W))))
small_len = max(0.1, min(25.0, float(request.form.get("small_len", SMALL_LEN))))
small_w = max(0.01, min(10.0, float(request.form.get("small_w", SMALL_W))))
if request.form.get("max_is_inf") == "1":
max_val = math.inf
svg = generate_svg(
unit,
min_val,
max_val,
left_label,
right_label,
big_ticks,
small_ticks,
label_count,
use_paths,
scale_type,
custom_labels,
label_size,
font_key,
major_len,
major_w,
medium_len,
medium_w,
small_len,
small_w,
)
except ValueError as err:
return Response(str(err), status=400, mimetype="text/plain")
return Response(svg, mimetype="image/svg+xml")
if __name__ == "__main__":
app.run(debug=True)