llm-latency-radar 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- llm_latency_radar-0.3.0/LICENSE +21 -0
- llm_latency_radar-0.3.0/PKG-INFO +30 -0
- llm_latency_radar-0.3.0/README.md +7 -0
- llm_latency_radar-0.3.0/llm_latency_radar/__init__.py +6 -0
- llm_latency_radar-0.3.0/llm_latency_radar/cli.py +184 -0
- llm_latency_radar-0.3.0/llm_latency_radar/cost_latency_pareto.py +32 -0
- llm_latency_radar-0.3.0/llm_latency_radar/exporters.py +204 -0
- llm_latency_radar-0.3.0/llm_latency_radar/har_importer.py +205 -0
- llm_latency_radar-0.3.0/llm_latency_radar/simulator.py +104 -0
- llm_latency_radar-0.3.0/llm_latency_radar/slo_gate.py +247 -0
- llm_latency_radar-0.3.0/llm_latency_radar/sse_parser.py +171 -0
- llm_latency_radar-0.3.0/llm_latency_radar/stats.py +71 -0
- llm_latency_radar-0.3.0/llm_latency_radar.egg-info/PKG-INFO +30 -0
- llm_latency_radar-0.3.0/llm_latency_radar.egg-info/SOURCES.txt +19 -0
- llm_latency_radar-0.3.0/llm_latency_radar.egg-info/dependency_links.txt +1 -0
- llm_latency_radar-0.3.0/llm_latency_radar.egg-info/entry_points.txt +2 -0
- llm_latency_radar-0.3.0/llm_latency_radar.egg-info/top_level.txt +1 -0
- llm_latency_radar-0.3.0/pyproject.toml +46 -0
- llm_latency_radar-0.3.0/setup.cfg +4 -0
- llm_latency_radar-0.3.0/tests/test_radar_full.py +365 -0
- llm_latency_radar-0.3.0/tests/test_wave9_slo_pareto_har.py +409 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-latency-radar
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Zero-dependency streaming latency profiler for Time-To-First-Token (TTFT), inter-token jitter, P95/P99 percentiles, and SLO regression gating across LLM providers.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/andrejpimenov122-lab/llm-latency-radar
|
|
7
|
+
Project-URL: Repository, https://github.com/andrejpimenov122-lab/llm-latency-radar
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/andrejpimenov122-lab/llm-latency-radar/issues
|
|
9
|
+
Keywords: llm,latency,ttft,streaming,profiler,jitter,benchmark,slo,observability
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Topic :: System :: Benchmark
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# ⚡ LLM Latency Radar
|
|
25
|
+
|
|
26
|
+
**Open-source browser-side streaming profiler for Time-To-First-Token (TTFT), P95 Jitter, and Tokens/sec across LLM providers.**
|
|
27
|
+
|
|
28
|
+
- Zero server storage — API keys never leave browser memory.
|
|
29
|
+
- Ready for 1-click deployment on **Vercel**.
|
|
30
|
+
- Includes Contributor Covenant [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) and MIT License.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# ⚡ LLM Latency Radar
|
|
2
|
+
|
|
3
|
+
**Open-source browser-side streaming profiler for Time-To-First-Token (TTFT), P95 Jitter, and Tokens/sec across LLM providers.**
|
|
4
|
+
|
|
5
|
+
- Zero server storage — API keys never leave browser memory.
|
|
6
|
+
- Ready for 1-click deployment on **Vercel**.
|
|
7
|
+
- Includes Contributor Covenant [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) and MIT License.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Command-line interface for LLM Latency Radar."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .exporters import export_csv, export_markdown_table, export_svg_chart
|
|
12
|
+
from .simulator import PROVIDER_PROFILES, simulate_provider_traces
|
|
13
|
+
from .stats import StreamTrace, aggregate_runs
|
|
14
|
+
|
|
15
|
+
SUPPORTED_FORMATS = ("json", "markdown", "csv", "svg")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_providers(raw_providers: list[str] | str | None) -> list[str]:
|
|
19
|
+
"""Normalize comma- or space-separated provider names against PROVIDER_PROFILES."""
|
|
20
|
+
if raw_providers is None:
|
|
21
|
+
return list(PROVIDER_PROFILES)
|
|
22
|
+
|
|
23
|
+
tokens_raw = [raw_providers] if isinstance(raw_providers, str) else list(raw_providers)
|
|
24
|
+
resolved: list[str] = []
|
|
25
|
+
seen: set[str] = set()
|
|
26
|
+
|
|
27
|
+
for entry in tokens_raw:
|
|
28
|
+
for part in entry.split(","):
|
|
29
|
+
name = part.strip().lower()
|
|
30
|
+
if not name:
|
|
31
|
+
continue
|
|
32
|
+
expanded = list(PROVIDER_PROFILES) if name == "all" else [name]
|
|
33
|
+
for provider in expanded:
|
|
34
|
+
if provider not in PROVIDER_PROFILES:
|
|
35
|
+
available = ", ".join(PROVIDER_PROFILES)
|
|
36
|
+
raise ValueError(f"Unknown provider {provider!r}; choose from {available}")
|
|
37
|
+
if provider not in seen:
|
|
38
|
+
seen.add(provider)
|
|
39
|
+
resolved.append(provider)
|
|
40
|
+
|
|
41
|
+
if not resolved:
|
|
42
|
+
raise ValueError("At least one provider must be specified")
|
|
43
|
+
return resolved
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def run_simulation(
|
|
47
|
+
providers: list[str],
|
|
48
|
+
runs: int = 10,
|
|
49
|
+
tokens: int = 64,
|
|
50
|
+
seed: int = 42,
|
|
51
|
+
slo_ttft_ms: float = 500.0,
|
|
52
|
+
) -> list[dict[str, Any]]:
|
|
53
|
+
"""Simulate streaming traces for each provider and aggregate latency metrics."""
|
|
54
|
+
rows: list[dict[str, Any]] = []
|
|
55
|
+
for provider in providers:
|
|
56
|
+
raw_traces = simulate_provider_traces(
|
|
57
|
+
provider=provider,
|
|
58
|
+
runs=runs,
|
|
59
|
+
output_tokens=tokens,
|
|
60
|
+
seed=seed,
|
|
61
|
+
)
|
|
62
|
+
traces = [StreamTrace(**record) for record in raw_traces]
|
|
63
|
+
summary = aggregate_runs(traces, slo_ttft_ms=slo_ttft_ms)
|
|
64
|
+
model = raw_traces[0]["model"] if raw_traces else PROVIDER_PROFILES[provider]["model"]
|
|
65
|
+
rows.append(
|
|
66
|
+
{
|
|
67
|
+
"provider": provider,
|
|
68
|
+
"model": model,
|
|
69
|
+
**summary,
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
return rows
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def format_simulation_output(rows: list[dict[str, Any]], output_format: str = "json") -> str:
|
|
76
|
+
"""Render aggregated latency rows in JSON, Markdown, CSV, or SVG format."""
|
|
77
|
+
if output_format == "json":
|
|
78
|
+
return json.dumps(rows, indent=2)
|
|
79
|
+
if output_format == "markdown":
|
|
80
|
+
return export_markdown_table(rows)
|
|
81
|
+
if output_format == "csv":
|
|
82
|
+
return export_csv(rows).rstrip("\r\n")
|
|
83
|
+
if output_format == "svg":
|
|
84
|
+
return export_svg_chart(rows, metric_key="ttft_p50_ms")
|
|
85
|
+
raise ValueError(f"Unsupported format {output_format!r}; choose from {', '.join(SUPPORTED_FORMATS)}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
89
|
+
"""Construct the CLI argument parser."""
|
|
90
|
+
parser = argparse.ArgumentParser(
|
|
91
|
+
prog="llm-latency-radar",
|
|
92
|
+
description="Zero-dependency streaming latency, TTFT, and jitter profiler for LLM providers.",
|
|
93
|
+
)
|
|
94
|
+
parser.add_argument(
|
|
95
|
+
"--version",
|
|
96
|
+
action="version",
|
|
97
|
+
version=f"%(prog)s {__version__}",
|
|
98
|
+
)
|
|
99
|
+
subparsers = parser.add_subparsers(dest="command")
|
|
100
|
+
|
|
101
|
+
sim_parser = subparsers.add_parser(
|
|
102
|
+
"simulate",
|
|
103
|
+
help="Run deterministic offline streaming latency simulations across providers",
|
|
104
|
+
)
|
|
105
|
+
sim_parser.add_argument(
|
|
106
|
+
"--providers",
|
|
107
|
+
action="extend",
|
|
108
|
+
nargs="+",
|
|
109
|
+
default=None,
|
|
110
|
+
metavar="PROVIDER",
|
|
111
|
+
help=(
|
|
112
|
+
"Provider name(s) to simulate (comma- or space-separated). "
|
|
113
|
+
f"Choices: {', '.join(PROVIDER_PROFILES)}, or 'all' (default: all)."
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
sim_parser.add_argument(
|
|
117
|
+
"--runs",
|
|
118
|
+
type=int,
|
|
119
|
+
default=10,
|
|
120
|
+
help="Number of simulated streaming runs per provider (default: 10).",
|
|
121
|
+
)
|
|
122
|
+
sim_parser.add_argument(
|
|
123
|
+
"--tokens",
|
|
124
|
+
type=int,
|
|
125
|
+
default=64,
|
|
126
|
+
help="Number of generated output tokens per run (default: 64).",
|
|
127
|
+
)
|
|
128
|
+
sim_parser.add_argument(
|
|
129
|
+
"--seed",
|
|
130
|
+
type=int,
|
|
131
|
+
default=42,
|
|
132
|
+
help="Deterministic random seed (default: 42).",
|
|
133
|
+
)
|
|
134
|
+
sim_parser.add_argument(
|
|
135
|
+
"--format",
|
|
136
|
+
choices=SUPPORTED_FORMATS,
|
|
137
|
+
default="json",
|
|
138
|
+
help="Output format: json, markdown, csv, or svg (default: json).",
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
subparsers.add_parser(
|
|
142
|
+
"version",
|
|
143
|
+
help="Print package version and exit",
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
return parser
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def main(argv: list[str] | None = None) -> int:
|
|
150
|
+
"""CLI entrypoint returning a POSIX exit status code."""
|
|
151
|
+
parser = build_parser()
|
|
152
|
+
args = parser.parse_args(argv)
|
|
153
|
+
|
|
154
|
+
if args.command is None:
|
|
155
|
+
parser.print_help()
|
|
156
|
+
return 0
|
|
157
|
+
|
|
158
|
+
if args.command == "version":
|
|
159
|
+
print(f"llm-latency-radar {__version__}")
|
|
160
|
+
return 0
|
|
161
|
+
|
|
162
|
+
if args.command == "simulate":
|
|
163
|
+
try:
|
|
164
|
+
providers = parse_providers(args.providers)
|
|
165
|
+
rows = run_simulation(
|
|
166
|
+
providers=providers,
|
|
167
|
+
runs=args.runs,
|
|
168
|
+
tokens=args.tokens,
|
|
169
|
+
seed=args.seed,
|
|
170
|
+
)
|
|
171
|
+
rendered = format_simulation_output(rows, output_format=args.format)
|
|
172
|
+
except (ValueError, TypeError) as exc:
|
|
173
|
+
sys.stderr.write(f"llm-latency-radar: error: {exc}\n")
|
|
174
|
+
return 1
|
|
175
|
+
|
|
176
|
+
print(rendered)
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
parser.print_help()
|
|
180
|
+
return 1
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
if __name__ == "__main__":
|
|
184
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Select models on the cost, first-token latency, and quality frontier."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def compute_pareto_frontier(candidates: list[dict]) -> list[dict]:
|
|
5
|
+
"""Return nondominated candidates in their original input order.
|
|
6
|
+
|
|
7
|
+
Lower ``cost_per_1m_usd`` and ``p50_ttft_ms`` are better; higher
|
|
8
|
+
``quality_score`` is better. A candidate dominates another only when
|
|
9
|
+
it is no worse on every metric and strictly better on at least one.
|
|
10
|
+
Consequently, candidates with identical metrics are all retained.
|
|
11
|
+
|
|
12
|
+
Each dictionary must contain all three metrics as comparable numeric
|
|
13
|
+
values (not NaN). The original dictionaries are returned unchanged.
|
|
14
|
+
The algorithm takes O(n**2) time and O(n) additional space.
|
|
15
|
+
"""
|
|
16
|
+
metrics = [
|
|
17
|
+
(candidate["cost_per_1m_usd"], candidate["p50_ttft_ms"],
|
|
18
|
+
candidate["quality_score"])
|
|
19
|
+
for candidate in candidates
|
|
20
|
+
]
|
|
21
|
+
frontier = []
|
|
22
|
+
for candidate, (cost, latency, quality) in zip(candidates, metrics):
|
|
23
|
+
dominated = any(
|
|
24
|
+
other_cost <= cost
|
|
25
|
+
and other_latency <= latency
|
|
26
|
+
and other_quality >= quality
|
|
27
|
+
and (other_cost < cost or other_latency < latency or other_quality > quality)
|
|
28
|
+
for other_cost, other_latency, other_quality in metrics
|
|
29
|
+
)
|
|
30
|
+
if not dominated:
|
|
31
|
+
frontier.append(candidate)
|
|
32
|
+
return frontier
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Markdown, CSV, and self-contained SVG chart exporters for latency radar rows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import html
|
|
7
|
+
import io
|
|
8
|
+
import math
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _collect_columns(rows: list[dict[str, Any]]) -> list[str]:
|
|
13
|
+
"""Collect column names in insertion order across all rows."""
|
|
14
|
+
columns: dict[str, None] = {}
|
|
15
|
+
for row in rows:
|
|
16
|
+
for key in row:
|
|
17
|
+
columns.setdefault(str(key), None)
|
|
18
|
+
return list(columns)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _format_cell(value: Any) -> str:
|
|
22
|
+
"""Format a cell value for Markdown table output."""
|
|
23
|
+
if value is None:
|
|
24
|
+
return ""
|
|
25
|
+
text = str(value)
|
|
26
|
+
return text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ").replace("|", "\\|")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _format_metric_value(value: float) -> str:
|
|
30
|
+
"""Format a numeric metric concisely for SVG labels."""
|
|
31
|
+
if value.is_integer():
|
|
32
|
+
return str(int(value))
|
|
33
|
+
return f"{value:.2f}".rstrip("0").rstrip(".")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _row_label(row: dict[str, Any], index: int) -> str:
|
|
37
|
+
"""Derive a human-readable label for a radar row."""
|
|
38
|
+
if row.get("label"):
|
|
39
|
+
return str(row["label"])
|
|
40
|
+
provider = row.get("provider")
|
|
41
|
+
model = row.get("model")
|
|
42
|
+
if provider and model:
|
|
43
|
+
return f"{provider} / {model}"
|
|
44
|
+
if provider:
|
|
45
|
+
return str(provider)
|
|
46
|
+
if model:
|
|
47
|
+
return str(model)
|
|
48
|
+
for fallback_key in ("name", "id"):
|
|
49
|
+
if row.get(fallback_key):
|
|
50
|
+
return str(row[fallback_key])
|
|
51
|
+
return f"Item {index + 1}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _extract_numeric(row: dict[str, Any], metric_key: str) -> float | None:
|
|
55
|
+
"""Extract a finite float value for metric_key, or None if unavailable."""
|
|
56
|
+
raw = row.get(metric_key)
|
|
57
|
+
if isinstance(raw, bool) or not isinstance(raw, (int, float)):
|
|
58
|
+
return None
|
|
59
|
+
val = float(raw)
|
|
60
|
+
return val if math.isfinite(val) else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def export_markdown_table(rows: list[dict]) -> str:
|
|
64
|
+
"""Render a list of row dicts as a GitHub-Flavored Markdown table."""
|
|
65
|
+
if not rows:
|
|
66
|
+
return ""
|
|
67
|
+
|
|
68
|
+
columns = _collect_columns(rows)
|
|
69
|
+
if not columns:
|
|
70
|
+
return ""
|
|
71
|
+
|
|
72
|
+
header = "| " + " | ".join(_format_cell(col) for col in columns) + " |"
|
|
73
|
+
separator = "| " + " | ".join("---" for _ in columns) + " |"
|
|
74
|
+
lines = [header, separator]
|
|
75
|
+
|
|
76
|
+
for row in rows:
|
|
77
|
+
cells = [_format_cell(row.get(col)) for col in columns]
|
|
78
|
+
lines.append("| " + " | ".join(cells) + " |")
|
|
79
|
+
|
|
80
|
+
return "\n".join(lines)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def export_csv(rows: list[dict]) -> str:
|
|
84
|
+
"""Render a list of row dicts as a UTF-8 CSV string with headers."""
|
|
85
|
+
if not rows:
|
|
86
|
+
return ""
|
|
87
|
+
|
|
88
|
+
columns = _collect_columns(rows)
|
|
89
|
+
if not columns:
|
|
90
|
+
return ""
|
|
91
|
+
|
|
92
|
+
buffer = io.StringIO(newline="")
|
|
93
|
+
writer = csv.DictWriter(
|
|
94
|
+
buffer,
|
|
95
|
+
fieldnames=columns,
|
|
96
|
+
restval="",
|
|
97
|
+
extrasaction="ignore",
|
|
98
|
+
lineterminator="\n",
|
|
99
|
+
)
|
|
100
|
+
writer.writeheader()
|
|
101
|
+
for row in rows:
|
|
102
|
+
normalized = {str(k): ("" if v is None else v) for k, v in row.items()}
|
|
103
|
+
writer.writerow(normalized)
|
|
104
|
+
|
|
105
|
+
return buffer.getvalue()
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def export_svg_chart(
|
|
109
|
+
rows: list[dict],
|
|
110
|
+
metric_key: str = "p50_ttft_ms",
|
|
111
|
+
title: str = "LLM TTFT Latency (ms)",
|
|
112
|
+
) -> str:
|
|
113
|
+
"""Generate a valid, self-contained SVG horizontal bar chart for a metric."""
|
|
114
|
+
width = 760
|
|
115
|
+
left_pad = 210
|
|
116
|
+
right_pad = 90
|
|
117
|
+
top_pad = 64
|
|
118
|
+
bottom_pad = 36
|
|
119
|
+
row_height = 36
|
|
120
|
+
bar_height = 22
|
|
121
|
+
chart_width = width - left_pad - right_pad
|
|
122
|
+
|
|
123
|
+
escaped_title = html.escape(title, quote=True)
|
|
124
|
+
escaped_metric = html.escape(metric_key, quote=True)
|
|
125
|
+
|
|
126
|
+
items: list[tuple[str, float]] = []
|
|
127
|
+
for idx, row in enumerate(rows):
|
|
128
|
+
val = _extract_numeric(row, metric_key)
|
|
129
|
+
if val is not None:
|
|
130
|
+
items.append((_row_label(row, idx), max(0.0, val)))
|
|
131
|
+
|
|
132
|
+
if not items:
|
|
133
|
+
height = 140
|
|
134
|
+
return (
|
|
135
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
|
|
136
|
+
f'width="{width}" height="{height}" role="img" aria-label="{escaped_title}">\n'
|
|
137
|
+
f" <title>{escaped_title}</title>\n"
|
|
138
|
+
f' <rect x="0" y="0" width="{width}" height="{height}" fill="#ffffff" rx="8" />\n'
|
|
139
|
+
f' <text x="24" y="34" font-family="ui-sans-serif, system-ui, sans-serif" '
|
|
140
|
+
f'font-size="18" font-weight="600" fill="#0f172a">{escaped_title}</text>\n'
|
|
141
|
+
f' <text x="24" y="84" font-family="ui-sans-serif, system-ui, sans-serif" '
|
|
142
|
+
f'font-size="13" fill="#64748b">No numeric data for metric "{escaped_metric}".</text>\n'
|
|
143
|
+
f"</svg>"
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
height = top_pad + len(items) * row_height + bottom_pad
|
|
147
|
+
max_val = max(val for _, val in items)
|
|
148
|
+
scale_max = max_val if max_val > 0 else 1.0
|
|
149
|
+
palette = ("#2563eb", "#0891b2", "#059669", "#7c3aed", "#d97706", "#dc2626")
|
|
150
|
+
|
|
151
|
+
parts = [
|
|
152
|
+
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
|
|
153
|
+
f'width="{width}" height="{height}" role="img" aria-label="{escaped_title}">',
|
|
154
|
+
f" <title>{escaped_title}</title>",
|
|
155
|
+
f' <rect x="0" y="0" width="{width}" height="{height}" fill="#ffffff" rx="8" />',
|
|
156
|
+
f' <text x="24" y="32" font-family="ui-sans-serif, system-ui, sans-serif" '
|
|
157
|
+
f'font-size="18" font-weight="600" fill="#0f172a">{escaped_title}</text>',
|
|
158
|
+
f' <text x="24" y="50" font-family="ui-sans-serif, system-ui, sans-serif" '
|
|
159
|
+
f'font-size="12" fill="#64748b">Metric: {escaped_metric}</text>',
|
|
160
|
+
]
|
|
161
|
+
|
|
162
|
+
# Vertical gridlines at 0%, 25%, 50%, 75%, 100%
|
|
163
|
+
y_grid_top = top_pad - 6
|
|
164
|
+
y_grid_bottom = top_pad + len(items) * row_height
|
|
165
|
+
for step in range(5):
|
|
166
|
+
frac = step / 4
|
|
167
|
+
gx = left_pad + frac * chart_width
|
|
168
|
+
tick_val = _format_metric_value(scale_max * frac)
|
|
169
|
+
parts.append(
|
|
170
|
+
f' <line x1="{gx:.1f}" y1="{y_grid_top}" x2="{gx:.1f}" y2="{y_grid_bottom}" '
|
|
171
|
+
f'stroke="#e2e8f0" stroke-width="1" />'
|
|
172
|
+
)
|
|
173
|
+
parts.append(
|
|
174
|
+
f' <text x="{gx:.1f}" y="{y_grid_bottom + 18}" text-anchor="middle" '
|
|
175
|
+
f'font-family="ui-sans-serif, system-ui, sans-serif" font-size="11" '
|
|
176
|
+
f'fill="#64748b">{html.escape(tick_val)}</text>'
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
for idx, (label, val) in enumerate(items):
|
|
180
|
+
y = top_pad + idx * row_height
|
|
181
|
+
bar_y = y + (row_height - bar_height) / 2
|
|
182
|
+
bar_w = (val / scale_max) * chart_width if max_val > 0 else 0.0
|
|
183
|
+
color = palette[idx % len(palette)]
|
|
184
|
+
display_label = label if len(label) <= 28 else label[:25] + "..."
|
|
185
|
+
escaped_label = html.escape(display_label)
|
|
186
|
+
val_str = html.escape(_format_metric_value(val))
|
|
187
|
+
|
|
188
|
+
parts.append(
|
|
189
|
+
f' <text x="{left_pad - 12}" y="{bar_y + bar_height / 2 + 4:.1f}" '
|
|
190
|
+
f'text-anchor="end" font-family="ui-sans-serif, system-ui, sans-serif" '
|
|
191
|
+
f'font-size="12" fill="#1e293b">{escaped_label}</text>'
|
|
192
|
+
)
|
|
193
|
+
parts.append(
|
|
194
|
+
f' <rect x="{left_pad}" y="{bar_y:.1f}" width="{bar_w:.1f}" '
|
|
195
|
+
f'height="{bar_height}" rx="4" fill="{color}" />'
|
|
196
|
+
)
|
|
197
|
+
parts.append(
|
|
198
|
+
f' <text x="{left_pad + bar_w + 8:.1f}" y="{bar_y + bar_height / 2 + 4:.1f}" '
|
|
199
|
+
f'font-family="ui-sans-serif, system-ui, sans-serif" font-size="12" '
|
|
200
|
+
f'font-weight="500" fill="#0f172a">{val_str}</text>'
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
parts.append("</svg>")
|
|
204
|
+
return "\n".join(parts)
|