Add font selector; load all fonts from fonts/ directory; bump to 0.85

All .ttf files in fonts/ are loaded at startup. The web form now has a
font selector dropdown. Glyph-rendering helpers that previously used
module-level font globals now accept a _FontData parameter threaded
through from generate_svg().

Dockerfile updated to copy all of fonts/ into the image rather than a
single hardcoded .ttf path.
This commit is contained in:
2026-07-14 23:51:55 +02:00
parent 8d45a6d10f
commit 62d9f02a82
11 changed files with 152 additions and 168 deletions
+1 -1
View File
@@ -5,7 +5,7 @@ WORKDIR /app
COPY web/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt gunicorn
COPY fonts/ГОСТ_тип_А.ttf /usr/local/share/fonts/г/ГОСТ_тип_А.ttf
COPY fonts/ /app/fonts/
COPY web/ .
+3 -4
View File
@@ -40,7 +40,7 @@ source .venv/bin/activate
cd web && python app.py # http://localhost:5000
```
The font must be installed at `/usr/local/share/fonts/г/ГОСТ_тип_А.ttf`.
Fonts are loaded at startup from the `fonts/` directory in the repo root.
### Form parameters
@@ -84,13 +84,12 @@ Constructs nest: `{m/s^2}` is a fraction with a superscript in the denominator,
## Container
```bash
# Copy the font first (not redistributed via the registry)
cp /usr/local/share/fonts/г/ГОСТ_тип_А.ttf fonts/
docker build -t m1730-scale:latest .
docker run -p 5000:5000 m1730-scale:latest
```
Fonts are loaded from `fonts/` in the repo root; they are bundled into the image at build time.
The production image is at `git.baumann.gr/adebaumann/m1730-generator`.
## Kubernetes
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -15,7 +15,7 @@ spec:
spec:
containers:
- name: m1730-generator
image: git.baumann.gr/adebaumann/m1730-generator:0.84
image: git.baumann.gr/adebaumann/m1730-generator:0.85
imagePullPolicy: Always
ports:
- containerPort: 5000
+135 -162
View File
@@ -1,6 +1,7 @@
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
@@ -8,28 +9,46 @@ from fontTools.pens.svgPathPen import SVGPathPen
app = Flask(__name__)
VERSION = "0.84"
VERSION = "0.85"
_LOGO_PATH = pathlib.Path(__file__).parent / 'static' / 'logo.png'
_LOGO_B64 = base64.b64encode(_LOGO_PATH.read_bytes()).decode()
_FONT_PATH = pathlib.Path('/usr/local/share/fonts/г/ГОСТ_тип_А.ttf')
_FONT_B64 = base64.b64encode(_FONT_PATH.read_bytes()).decode()
_FONT_FACE = (
'<defs><style>'
'@font-face {'
'font-family:"ГОСТ тип А";'
f'src:url("data:font/truetype;base64,{_FONT_B64}") format("truetype");'
'}'
'</style></defs>'
)
_FontData = namedtuple('_FontData', ['key', 'label', 'b64', 'glyph_set', 'cmap', 'hmtx', 'upm', 'glyf'])
_FONT_OBJ = TTFont(str(_FONT_PATH))
_GLYPH_SET = _FONT_OBJ.getGlyphSet()
_CMAP = _FONT_OBJ.getBestCmap()
_HMTX = _FONT_OBJ['hmtx'].metrics
_UPM = _FONT_OBJ['head'].unitsPerEm
_GLYF = _FONT_OBJ['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',
}
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 = 'GOST_2.30481_type_A'
# SVG absolute coordinate constants (1 user unit = 1 mm)
ZERO_X = 60.844130
@@ -45,35 +64,26 @@ _UNIT_SCALE_X = 0.96486402
_UNIT_MAX_FS = 18.7981
# --- Inline markup for the unit label -------------------------------------
# Lighter-shorthand notation, rendered with the ГОСТ font (no LaTeX engine):
# ^x / ^{...} superscript _x / _{...} subscript
# {a/b} stacked fraction (vinculum); a bare '/' stays inline
# The `{...}` argument after ^/_ and the two sides of a fraction are parsed
# recursively, so constructs nest (e.g. {m/s^2}, x^{1/2}).
_SUP_SCALE = 0.62 # size of a super/subscript relative to its base
_SUP_RISE = 0.36 # superscript baseline lift, in base ems
_SUB_DROP = 0.14 # subscript baseline drop, in base ems
_FRAC_SCALE = 0.62 # size of numerator/denominator relative to fraction
_FRAC_AXIS = 0.32 # vinculum height above the base baseline, in base ems
_FRAC_GAP = 0.14 # gap between numerator/denominator ink and the vinculum
_FRAC_SIDE = 0.12 # vinculum overhang past the wider side, in sub ems
_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
# Target box for the unit label (absolute panel coords). A marked-up unit is
# scaled to fit and centered inside this box, leaving white space around it.
# The panel spans y 90.55..117.05; the scale bar starts at x 58.44.
_UNIT_BOX_X0, _UNIT_BOX_X1 = 39.6, 57.4
_UNIT_BOX_Y0, _UNIT_BOX_Y1 = 92.8, 114.8
def _glyph_svg(ch: str, x: float, y: float, fs: float, fill: str):
"""Return (svg_path_or_None, advance_width) for one glyph at size `fs`."""
gn = _CMAP.get(ord(ch))
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 / _UPM
adv = _HMTX.get(gn, (0, 0))[0] * s
pen = SVGPathPen(_GLYPH_SET)
_GLYPH_SET[gn].draw(pen)
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
@@ -81,20 +91,18 @@ def _glyph_svg(ch: str, x: float, y: float, fs: float, fill: str):
return f'<path style="fill:{fill}" transform="{t}" d="{d}"/>', adv
def _glyph_ybounds(ch: str):
"""(yMin, yMax) of a glyph's ink in em units, y-up. (0, 0) if it has none."""
gn = _CMAP.get(ord(ch))
def _glyph_ybounds(ch: str, fd: _FontData):
gn = fd.cmap.get(ord(ch))
if gn is None:
return 0.0, 0.0
g = _GLYF[gn]
if g.numberOfContours == 0: # space and other empty glyphs
g = fd.glyf[gn]
if g.numberOfContours == 0:
return 0.0, 0.0
g.recalcBounds(_GLYF)
return g.yMin / _UPM, g.yMax / _UPM
g.recalcBounds(fd.glyf)
return g.yMin / fd.upm, g.yMax / fd.upm
def _extract_braced(s: str, i: int):
"""s[i] == '{'; return (inner_text, index_just_after_matching_'}')."""
depth, j = 1, i + 1
while j < len(s) and depth:
if s[j] == '{':
@@ -108,7 +116,6 @@ def _extract_braced(s: str, i: int):
def _parse_braced(inner: str):
"""A '{...}' group: a top-level '/' makes it a fraction, else a plain run."""
depth = 0
for k, ch in enumerate(inner):
if ch == '{':
@@ -121,7 +128,6 @@ def _parse_braced(inner: str):
def _parse_atom(s: str, i: int):
"""Argument of ^ or _: a braced group or a single character."""
if i >= len(s):
return [], i
if s[i] == '{':
@@ -131,7 +137,6 @@ def _parse_atom(s: str, i: int):
def _parse_markup(s: str):
"""Parse a markup string into a flat list of nodes."""
nodes, i = [], 0
while i < len(s):
c = s[i]
@@ -148,58 +153,51 @@ def _parse_markup(s: str):
return nodes
def _measure(nodes, fs: float) -> float:
def _measure(nodes, fs: float, fd: _FontData) -> float:
w = 0.0
for n in nodes:
if n[0] == 'lit':
gn = _CMAP.get(ord(n[1]))
gn = fd.cmap.get(ord(n[1]))
if gn:
w += _HMTX.get(gn, (0, 0))[0] / _UPM * fs
w += fd.hmtx.get(gn, (0, 0))[0] / fd.upm * fs
elif n[0] == 'group':
w += _measure(n[1], fs)
w += _measure(n[1], fs, fd)
elif n[0] in ('sup', 'sub'):
w += _measure(n[1], fs * _SUP_SCALE)
w += _measure(n[1], fs * _SUP_SCALE, fd)
elif n[0] == 'frac':
fs2 = fs * _FRAC_SCALE
w += max(_measure(n[1], fs2), _measure(n[2], fs2)) + 2 * _FRAC_SIDE * fs2
w += max(_measure(n[1], fs2, fd), _measure(n[2], fs2, fd)) + 2 * _FRAC_SIDE * fs2
return w
def _frac_layout(n, fs: float):
"""Fraction geometry (offsets relative to the base baseline, y-down).
Numerator and denominator are placed so their ink clears the vinculum by
`_FRAC_GAP` on each side — using the parts' real ink extents, so the gaps
hold whatever glyphs (or nested fractions) they contain.
"""
def _frac_layout(n, fs: float, fd: _FontData):
fs2 = fs * _FRAC_SCALE
axis = -_FRAC_AXIS * fs
_, num_bot = _vbounds(n[1], fs2) # numerator ink bottom, baseline-relative
_, num_bot = _vbounds(n[1], fs2, fd)
num_base = axis - _FRAC_GAP * fs2 - num_bot
den_top, _ = _vbounds(n[2], fs2) # denominator ink top, baseline-relative
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):
"""(top, bottom) of the composite ink, baseline-relative, y-down (top < bottom)."""
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])
ymin, ymax = _glyph_ybounds(n[1], fd)
a, b = -ymax * fs, -ymin * fs
elif n[0] == 'group':
a, b = _vbounds(n[1], fs)
a, b = _vbounds(n[1], fs, fd)
elif n[0] == 'sup':
a, b = _vbounds(n[1], fs * _SUP_SCALE)
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)
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)
nt, nb = _vbounds(n[1], fs2)
dt, db = _vbounds(n[2], fs2)
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)
else:
@@ -208,31 +206,30 @@ def _vbounds(nodes, fs: float):
return (0.0, 0.0) if lo > hi else (lo, hi)
def _draw_nodes(nodes, x: float, y: float, fs: float, fill: str):
"""Return (list_of_svg_parts, total_advance_width). y is the base baseline."""
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)
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)
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)
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)
wn, wd = _measure(n[1], fs2), _measure(n[2], fs2)
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)
pd, _ = _draw_nodes(n[2], cx + (bar_w - wd) / 2, y + den_base, fs2, fill)
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(
@@ -247,87 +244,57 @@ def _has_markup(s: str) -> bool:
return any(c in s for c in '^_') or ('{' in s and '}' in s)
def _markup_unit_svg(unit: str, fill='#1a1a1a') -> str:
"""Render a marked-up unit, scaled to fit and centered in the unit box."""
def _markup_unit_svg(unit: str, fd: _FontData, fill='#1a1a1a') -> str:
nodes = _parse_markup(unit)
x0, x1, y0, y1 = _UNIT_BOX_X0, _UNIT_BOX_X1, _UNIT_BOX_Y0, _UNIT_BOX_Y1
xc, yc = (x0 + x1) / 2, (y0 + y1) / 2
# Fit to the box in both axes (width is horizontally condensed by SCALE_X).
w1 = _measure(nodes, 1.0)
top1, bot1 = _vbounds(nodes, 1.0)
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 * _UNIT_SCALE_X))
if bot1 - top1 > 0:
fs = min(fs, (y1 - y0) / (bot1 - top1))
# Center: baseline placed so the ink box's mid-height lands on yc; glyphs
# drawn from a natural left edge, then condensed horizontally about xc.
w = _measure(nodes, fs)
top, bot = _vbounds(nodes, fs)
w = _measure(nodes, fs, fd)
top, bot = _vbounds(nodes, fs, fd)
y_base = yc - (top + bot) / 2
parts, _ = _draw_nodes(nodes, xc - w / 2, y_base, fs, fill)
parts, _ = _draw_nodes(nodes, xc - w / 2, y_base, fs, fill, fd)
cond = f'translate({xc:.5f},0) scale({_UNIT_SCALE_X},1) translate({-xc:.5f},0)'
return f'<g transform="{cond}">\n{chr(10).join(parts)}\n</g>'
def _text_em_width(text: str) -> float:
"""Advance width of `text` in em units, from the font's own metrics."""
return sum(
_HMTX.get(_CMAP.get(ord(ch)), (0, 0))[0]
for ch in text if _CMAP.get(ord(ch))
) / _UPM
def _unit_font_size(unit: str) -> float:
# Fit the unit's true rendered width (measuring the parsed markup, so
# super/subscripts and fractions are accounted for) into the available
# area. Rendered width at a given size is em_width * font_size * scale_x.
em_w = _measure(_parse_markup(unit), 1.0)
def _unit_font_size(unit: str, fd: _FontData) -> float:
em_w = _measure(_parse_markup(unit), 1.0, fd)
if em_w <= 0:
return _UNIT_MAX_FS
return min(_UNIT_MAX_FS, _UNIT_AREA_WIDTH / (em_w * _UNIT_SCALE_X))
def _fmt(v: float) -> str:
if math.isinf(v):
return ''
# Snap near-integers — log-scale geometric values accumulate FP error
# (e.g. 9999.9999), which would otherwise miss the integer case.
r = round(v)
if abs(v - r) < 1e-9 * max(1.0, abs(v)):
return str(int(r))
# 4 significant figures in fixed-point notation (never scientific).
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 _text_to_paths(text, x, y, font_size, anchor='start', fill='#1a1a1a', wrap_transform=None):
s = font_size / _UPM
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 == 'middle':
total_w = sum(
_HMTX.get(_CMAP.get(ord(ch)), (0, 0))[0] * s
for ch in text if _CMAP.get(ord(ch))
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
parts = []
cx = x
for ch in text:
gn = _CMAP.get(ord(ch))
gn = fd.cmap.get(ord(ch))
if gn is None:
continue
pen = SVGPathPen(_GLYPH_SET)
_GLYPH_SET[gn].draw(pen)
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 += _HMTX.get(gn, (0, 0))[0] * s
cx += fd.hmtx.get(gn, (0, 0))[0] * s
inner = '\n'.join(parts)
if wrap_transform:
@@ -335,8 +302,23 @@ def _text_to_paths(text, x, y, font_size, anchor='start', fill='#1a1a1a', wrap_t
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, range_label, big_ticks, small_ticks, label_count,
use_paths=True, scale_type='linear', custom_labels=None, label_size=9):
use_paths=True, scale_type='linear', custom_labels=None, label_size=9,
font_key=None):
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.")
@@ -370,7 +352,6 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
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):
# Simplified form when max = ∞: x = ZERO_X + SCALE_LEN * min_val / v
def value_to_x(v):
if math.isinf(v):
return ZERO_X
@@ -383,7 +364,7 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
else:
if max_val <= 0:
raise ValueError("Reciprocal scale requires min and max values greater than 0.")
k = 1.0 / min_val - 1.0 / max_val # always positive
k = 1.0 / min_val - 1.0 / max_val
def value_to_x(v):
return ZERO_X + SCALE_LEN * (1.0 / v - 1.0 / max_val) / k
@@ -403,11 +384,9 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
return min_val + span * i / big_ticks
big_interval = SCALE_LEN / big_ticks
# Major ticks are always physically evenly spaced; only their values differ.
big_xs = [ZERO_X + i * big_interval for i in range(big_ticks + 1)]
big_vals = [major_value(i) for i in range(big_ticks + 1)]
# Custom labels, when supplied, override the calculated numbers and set the count.
if custom_labels:
label_count = max(1, min(len(custom_labels), big_ticks + 1))
custom_labels = custom_labels[:label_count]
@@ -419,6 +398,13 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
else:
label_indices = [round(k * big_ticks / (label_count - 1)) for k in range(label_count)]
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="157.18373mm" height="26.683672mm"'
@@ -429,7 +415,7 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
if use_paths:
parts.append(' <g transform="translate(-37.352226,-90.454928)">')
else:
parts += [_FONT_FACE, ' <g transform="translate(-37.352226,-90.454928)">']
parts += [font_face, ' <g transform="translate(-37.352226,-90.454928)">']
parts.append(
' <path style="fill:#ffffff;stroke:#1a1a1a;stroke-width:0.184;'
@@ -438,49 +424,36 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
' M 58.443978,107.54692 H 183.64409 v 6.19963 H 58.443978 Z" />'
)
# A unit with markup (super/subscripts, fractions) is a composite of glyph
# paths + a rule, so it can't be a single <text> node — render it as paths,
# scaled to fit and centered in the unit box, in both modes. A plain unit
# keeps the original baseline-anchored text/paths behaviour.
if _has_markup(unit):
unit_svg = ' ' + _markup_unit_svg(unit)
unit_svg = ' ' + _markup_unit_svg(unit, fd)
elif use_paths:
unit_svg = ' ' + _text_to_paths(
unit, 41.455711, 109.03796, _unit_font_size(unit),
unit, 41.455711, 109.03796, _unit_font_size(unit, fd), fd,
wrap_transform=f'scale({_UNIT_SCALE_X},1.0364155)'
)
else:
fs = _unit_font_size(unit)
fs = _unit_font_size(unit, fd)
unit_svg = (
f' <text style="font-size:{fs:.4f}px;font-family:\'ГОСТ тип А\',monospace;fill:#1a1a1a"'
f' <text style="font-size:{fs:.4f}px;font-family:\'{fd.label}\',monospace;fill:#1a1a1a"'
f' x="41.455711" y="109.03796"'
f' transform="scale({_UNIT_SCALE_X},1.0364155)">{escape(unit)}</text>'
)
if use_paths:
parts += [unit_svg, ' ' + _text_to_paths(range_label, 184.79707, 113.6755, 3.60539)]
parts += [unit_svg, ' ' + _text_to_paths(range_label, 184.79707, 113.6755, 3.60539, fd)]
else:
parts += [
unit_svg,
f' <text style="font-size:3.60539px;font-family:\'ГОСТ тип А\',monospace;fill:#1a1a1a"'
f' <text style="font-size:3.60539px;font-family:\'{fd.label}\',monospace;fill:#1a1a1a"'
f' x="184.79707" y="113.6755">{escape(range_label)}</text>',
]
# Major ticks
for x in big_xs:
parts.append(
f' <line x1="{x:.5f}" y1="{BAR_Y}" x2="{x:.5f}" y2="{BAR_Y - BIG_H:.5f}"'
f' style="stroke:#1a1a1a;stroke-width:0.555;stroke-linecap:butt" />'
)
# Minor ticks — placement depends on scale type:
# linear: uniform physical spacing (= uniform value spacing)
# log: linear value interpolation between geometric major values
# (crowds toward high end of each interval)
# sqrt: sqrt of fractional position within each interval, giving
# consistent high-end crowding across all intervals; using
# value interpolation instead would concentrate the crowding
# only near zero (where sqrt is steepest) and look linear elsewhere.
if small_ticks > 0:
sub = small_ticks + 1
for i in range(big_ticks):
@@ -488,9 +461,6 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
if scale_type == 'sqrt':
x = big_xs[i] + (j / sub) ** 2 * (big_xs[i + 1] - big_xs[i])
elif scale_type == 'reciprocal' or math.isinf(big_vals[i]):
# Reciprocal: interpolate in position space (= linear in 1/v).
# Linear value interpolation would map huge early value ranges
# through 1/v and pile all ticks against the left wall.
x = big_xs[i] + (j / sub) * (big_xs[i + 1] - big_xs[i])
else:
v = big_vals[i] + j * (big_vals[i + 1] - big_vals[i]) / sub
@@ -500,15 +470,14 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
f' style="stroke:#1a1a1a;stroke-width:0.302;stroke-linecap:butt" />'
)
# Numeric labels
for k, idx in enumerate(label_indices):
x = big_xs[idx]
label = custom_labels[k] if custom_labels else _fmt(big_vals[idx])
if use_paths:
parts.append(' ' + _text_to_paths(label, x, 101.49598, label_size, anchor='middle'))
parts.append(' ' + _text_to_paths(label, x, 101.49598, label_size, fd, anchor='middle'))
else:
parts.append(
f' <text style="font-size:{label_size:.5f}px;font-family:\'ГОСТ тип А\',monospace;fill:#1a1a1a"'
f' <text style="font-size:{label_size:.5f}px;font-family:\'{fd.label}\',monospace;fill:#1a1a1a"'
f' text-anchor="middle" x="{x:.5f}" y="101.49598">{escape(label)}</text>'
)
@@ -518,7 +487,9 @@ def generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks, la
@app.route('/')
def index():
return render_template('index.html', logo_b64=_LOGO_B64, version=VERSION)
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'])
@@ -532,6 +503,7 @@ def generate():
label_count = max(2, int(request.form.get('label_count', 6)))
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)
if request.form.get('max_is_inf') == '1':
max_val = math.inf
@@ -540,7 +512,8 @@ def generate():
try:
svg = generate_svg(unit, min_val, max_val, range_label, big_ticks, small_ticks,
label_count, use_paths, scale_type, custom_labels, label_size)
label_count, use_paths, scale_type, custom_labels, label_size,
font_key)
except ValueError as err:
return Response(str(err), status=400, mimetype='text/plain')
return Response(svg, mimetype='image/svg+xml')
+12
View File
@@ -368,6 +368,16 @@
<input name="label_size" type="number" step="any" min="0.5" max="25" value="9" required>
</div>
</div>
<div class="row row-2" style="margin-top:1.25rem">
<div class="field">
<label>Font</label>
<select name="font" id="font-select" style="background:var(--white);border:1px solid var(--rule);border-radius:1px;padding:0.5rem 0.7rem;font-family:var(--f-body);font-size:0.875rem;color:var(--ink);width:100%;outline:none;cursor:pointer">
{% for f in fonts %}
<option value="{{ f.key }}"{% if f.key == default_font %} selected{% endif %}>{{ f.label }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
<div class="actions">
@@ -499,6 +509,8 @@
URL.revokeObjectURL(a.href);
});
document.getElementById('font-select').addEventListener('change', doGenerate);
doGenerate();
</script>
</body>