File size: 7,942 Bytes
ca05f78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
"""Palette and chart theming for the African Books Recovery Project.

Colour follows the validated reference palette: categorical hues are assigned in
fixed slot order and never cycled; sequential encodings use a single hue,
light -> dark; ordinal ramps (the recovery funnel) stay inside the steps that
clear contrast against the surface. Text always wears text tokens, never a
series colour.
"""

from __future__ import annotations

import altair as alt
import streamlit as st

# --- categorical slots, fixed order -------------------------------------------
CATEGORICAL = {
    "light": ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#4a3aa7", "#e34948"],
    "dark": ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767"],
}

# --- sequential / ordinal blue ramp -------------------------------------------
# Ordinal use starts no lighter than step 250 on light, no darker than 600 on dark.
ORDINAL = {
    "light": ["#86b6ef", "#5598e7", "#3987e5", "#2a78d6", "#256abf", "#1c5cab"],
    "dark": ["#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95"],
}

SURFACE = {"light": "#fcfcfb", "dark": "#1a1a19"}
TEXT_PRIMARY = {"light": "#0b0b0b", "dark": "#ffffff"}
TEXT_SECONDARY = {"light": "#52514e", "dark": "#c3c2b7"}
TEXT_MUTED = {"light": "#75736c", "dark": "#8f8d84"}
GRID = {"light": "#e8e7e3", "dark": "#2f2f2c"}
BORDER = {"light": "#dedcd6", "dark": "#33332f"}
PANEL = {"light": "#f5f4f1", "dark": "#212120"}

# status palette — reserved, never reused as "series N"
STATUS = {
    "light": {"good": "#008300", "warning": "#eda100", "serious": "#eb6834", "critical": "#e34948"},
    "dark": {"good": "#008300", "warning": "#c98500", "serious": "#d95926", "critical": "#e66767"},
}


def mode() -> str:
    """Resolve the viewer's theme. Falls back to light if Streamlit can't say."""
    try:
        t = st.context.theme
        if t and getattr(t, "type", None) in ("light", "dark"):
            return t.type
    except Exception:
        pass
    try:
        base = st.get_option("theme.base")
        if base in ("light", "dark"):
            return base
    except Exception:
        pass
    return "light"


class Palette:
    def __init__(self, m: str):
        self.m = m
        self.series = CATEGORICAL[m]
        self.ordinal = ORDINAL[m]
        self.surface = SURFACE[m]
        self.text = TEXT_PRIMARY[m]
        self.text2 = TEXT_SECONDARY[m]
        self.muted = TEXT_MUTED[m]
        self.grid = GRID[m]
        self.border = BORDER[m]
        self.panel = PANEL[m]
        self.status = STATUS[m]

    def scale(self, domain):
        """Categorical scale bound to an explicit domain, so colour follows the
        entity and a filter that drops series never repaints the survivors."""
        return alt.Scale(domain=list(domain), range=self.series[: len(domain)])


def palette() -> Palette:
    return Palette(mode())


def register_altair_theme(p: Palette) -> None:
    def _theme():
        return {
            "config": {
                "background": "transparent",
                "font": "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
                "view": {"stroke": "transparent", "continuousWidth": 400, "continuousHeight": 260},
                "axis": {
                    "labelColor": p.text2,
                    "titleColor": p.muted,
                    "titleFontSize": 11,
                    "titleFontWeight": "normal",
                    "labelFontSize": 11,
                    "domainColor": p.grid,
                    "tickColor": p.grid,
                    "gridColor": p.grid,
                    "gridOpacity": 0.7,
                    "gridWidth": 1,
                    "labelPadding": 6,
                },
                "legend": {
                    "labelColor": p.text2,
                    "titleColor": p.muted,
                    "labelFontSize": 11,
                    "titleFontSize": 11,
                    "titleFontWeight": "normal",
                    "symbolType": "square",
                    "symbolSize": 90,
                },
                "title": {"color": p.text, "fontSize": 13, "fontWeight": 600, "anchor": "start", "dy": -6},
                "bar": {"cornerRadiusEnd": 4},
                "line": {"strokeWidth": 2},
                "point": {"size": 90, "filled": True},
                "range": {"category": p.series, "ordinal": p.ordinal, "heatmap": p.ordinal},
            }
        }

    alt.theme.register("abrp", enable=True)(_theme)


def css(p: Palette) -> str:
    return f"""
<style>
  .block-container {{ padding-top: 3.1rem; max-width: 1280px; }}
  .abrp-hero h1 {{ font-size: 1.65rem; margin: 0 0 .25rem 0; letter-spacing: -.02em; color: {p.text}; }}
  .abrp-hero p {{ color: {p.text2}; margin: 0; font-size: .93rem; line-height: 1.5; max-width: 62rem; }}
  .abrp-eyebrow {{ font-size: .7rem; letter-spacing: .14em; text-transform: uppercase;
                   color: {p.muted}; margin-bottom: .35rem; }}
  .abrp-tiles {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
                 gap: .6rem; margin: 1.1rem 0 .4rem 0; }}
  .abrp-tile {{ background: {p.panel}; border: 1px solid {p.border}; border-radius: 10px;
                padding: .7rem .8rem; }}
  .abrp-tile .v {{ font-size: 1.5rem; font-weight: 650; color: {p.text}; line-height: 1.15;
                   font-variant-numeric: tabular-nums; }}
  .abrp-tile .k {{ font-size: .7rem; letter-spacing: .06em; text-transform: uppercase;
                   color: {p.muted}; margin-top: .2rem; }}
  .abrp-tile .s {{ font-size: .74rem; color: {p.text2}; margin-top: .3rem; line-height: 1.35; }}
  .abrp-note {{ background: {p.panel}; border-left: 3px solid {p.series[0]}; border-radius: 0 8px 8px 0;
                padding: .65rem .85rem; font-size: .82rem; color: {p.text2}; line-height: 1.5;
                margin: .5rem 0 1rem 0; }}
  .abrp-warn {{ background: {p.panel}; border-left: 3px solid {p.status['warning']};
                border-radius: 0 8px 8px 0; padding: .65rem .85rem; font-size: .82rem;
                color: {p.text2}; line-height: 1.5; margin: .5rem 0 1rem 0; }}
  .abrp-card {{ background: {p.panel}; border: 1px solid {p.border}; border-radius: 10px;
                padding: .9rem 1rem; margin-bottom: .6rem; }}
  .abrp-card h4 {{ margin: 0 0 .25rem 0; font-size: .98rem; color: {p.text}; }}
  .abrp-card .meta {{ font-size: .76rem; color: {p.muted}; margin-bottom: .45rem; }}
  .abrp-card p {{ font-size: .84rem; color: {p.text2}; line-height: 1.55; margin: .35rem 0 0 0; }}
  .abrp-chip {{ display: inline-block; font-size: .68rem; letter-spacing: .04em; padding: .1rem .45rem;
                border-radius: 999px; border: 1px solid {p.border}; color: {p.text2};
                margin-right: .3rem; white-space: nowrap; }}
  .abrp-chip.hi {{ border-color: {p.status['good']}; color: {p.status['good']}; }}
  .abrp-chip.me {{ border-color: {p.status['warning']}; color: {p.status['warning']}; }}
  .abrp-chip.lo {{ border-color: {p.status['critical']}; color: {p.status['critical']}; }}
  .abrp-foot {{ color: {p.muted}; font-size: .74rem; line-height: 1.6; border-top: 1px solid {p.border};
                padding-top: .7rem; margin-top: 2rem; }}
  section[data-testid="stSidebar"] {{ border-right: 1px solid {p.border}; }}
  div[data-testid="stMetricValue"] {{ font-variant-numeric: tabular-nums; }}
</style>
"""


def tiles(items) -> str:
    """items: iterable of (value, key, subtext)."""
    cells = "".join(
        f'<div class="abrp-tile"><div class="v">{v}</div><div class="k">{k}</div>'
        f'<div class="s">{s}</div></div>'
        for v, k, s in items
    )
    return f'<div class="abrp-tiles">{cells}</div>'


def chip(confidence: str) -> str:
    cls = {"high": "hi", "medium": "me", "low": "lo"}.get(confidence, "")
    return f'<span class="abrp-chip {cls}">{confidence} confidence</span>'