unchartable 0.1.0__py3-none-any.whl

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.
Files changed (42) hide show
  1. unchartable/__init__.py +77 -0
  2. unchartable/audio_displays.py +101 -0
  3. unchartable/chart_axes.py +173 -0
  4. unchartable/chart_config.py +182 -0
  5. unchartable/chart_layout.py +184 -0
  6. unchartable/chart_model.py +235 -0
  7. unchartable/chart_service.py +41 -0
  8. unchartable/compat.py +19 -0
  9. unchartable/components.py +431 -0
  10. unchartable/composition_layout.py +307 -0
  11. unchartable/connection_curves.py +53 -0
  12. unchartable/connection_palette.py +45 -0
  13. unchartable/connection_skin.py +279 -0
  14. unchartable/data/schematic/symbols.json +8385 -0
  15. unchartable/directed_graph.py +220 -0
  16. unchartable/figure_service.py +51 -0
  17. unchartable/font_provider.py +13 -0
  18. unchartable/graph_layout.py +173 -0
  19. unchartable/graph_routing.py +49 -0
  20. unchartable/neostudio_adapter.py +208 -0
  21. unchartable/node_shapes.py +84 -0
  22. unchartable/radial_charts.py +207 -0
  23. unchartable/render_api.py +67 -0
  24. unchartable/renderers/__init__.py +5 -0
  25. unchartable/renderers/base.py +35 -0
  26. unchartable/renderers/pillow_renderer.py +126 -0
  27. unchartable/renderers/svg_renderer.py +55 -0
  28. unchartable/scene.py +152 -0
  29. unchartable/schematic_style.py +55 -0
  30. unchartable/schematic_symbols.py +54 -0
  31. unchartable/scientific_charts.py +380 -0
  32. unchartable/socials_adapter.py +185 -0
  33. unchartable/socials_panels.py +240 -0
  34. unchartable/submediant_adapter.py +31 -0
  35. unchartable/submediant_graph.py +97 -0
  36. unchartable/text_layout.py +86 -0
  37. unchartable/widget_skin.py +159 -0
  38. unchartable-0.1.0.dist-info/METADATA +114 -0
  39. unchartable-0.1.0.dist-info/RECORD +42 -0
  40. unchartable-0.1.0.dist-info/WHEEL +5 -0
  41. unchartable-0.1.0.dist-info/licenses/LICENSE +21 -0
  42. unchartable-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,77 @@
1
+ """Create renderer-independent charts, diagrams and composed figures in Python.
2
+
3
+ Start with render(value), which accepts a Cartesian Chart, a chart Component
4
+ (such as Heatmap or PieChart), or an explicit Figure. The returned RenderedChart
5
+ contains image bytes and a media type; save those bytes with pathlib.
6
+ SVG is the default. PNG uses config=PillowChartConfig and the pillow extra.
7
+ Use help(Chart), help(Heatmap), etc. for parameters and executable examples.
8
+
9
+ >>> from unchartable import Chart, Series, render
10
+ >>> image = render(Chart(('Jan', 'Feb'), (Series('Orders', (12, 18)),)))
11
+ >>> image.media_type
12
+ 'image/svg+xml'
13
+
14
+ Config subclasses and create_chart_service()/create_figure_service() expose
15
+ advanced styling, renderer replacement and reusable locally injected services.
16
+ The recommended API is documented in docs/reference/public-api.md; legacy and
17
+ compatibility exports are retained but are not a claim of 1.0 stability.
18
+ """
19
+ from .chart_model import Chart, Series, ChartKind, BarMode
20
+ from .chart_service import ChartService
21
+ from .chart_config import ChartConfig, PillowChartConfig, create_chart_service
22
+ from .scene import Skin
23
+
24
+ __all__ = ['Chart', 'Series', 'ChartKind', 'BarMode', 'ChartService', 'ChartConfig', 'PillowChartConfig', 'create_chart_service', 'Skin']
25
+
26
+ from .components import Figure, Window, ChartView, TerminalView, Column, Component
27
+ from .figure_service import FigureService
28
+ from .widget_skin import WidgetSkin, AquaSkin
29
+
30
+ __all__ += ['Figure', 'Window', 'ChartView', 'TerminalView', 'Column', 'Component', 'FigureService', 'WidgetSkin', 'AquaSkin']
31
+
32
+ from .components import Row, TextBlock, Button, Desktop, PlacedWindow
33
+ __all__ += ['Row', 'TextBlock', 'Button', 'Desktop', 'PlacedWindow']
34
+
35
+ from .chart_axes import Axis, Scale, Annotation
36
+ from .scientific_charts import PanelChart, Heatmap, ColorScale, waveform, spectrum, density
37
+ from .radial_charts import PieChart, DoughnutChart, RingChart
38
+ from .composition_layout import Grid, MeasuredColumn, Sized, RichText, Span, ImageView, PathView
39
+ from .scene import Path
40
+ __all__ += ['Axis', 'Scale', 'Annotation', 'PanelChart', 'Heatmap', 'ColorScale',
41
+ 'waveform', 'spectrum', 'density', 'PieChart', 'DoughnutChart', 'RingChart',
42
+ 'Grid', 'MeasuredColumn', 'Sized', 'RichText', 'Span', 'ImageView', 'PathView', 'Path']
43
+
44
+ from .directed_graph import DirectedGraph, GraphNode, GraphPort, GraphEdge, ConnectionStyle
45
+ from .graph_layout import GraphLayout, GraphOptions
46
+ from .schematic_symbols import SchematicSymbols
47
+ __all__ += ['DirectedGraph', 'GraphNode', 'GraphPort', 'GraphEdge', 'ConnectionStyle',
48
+ 'GraphLayout', 'GraphOptions', 'SchematicSymbols']
49
+ from .submediant_graph import component_graph, studio_graph
50
+ __all__ += ['component_graph', 'studio_graph']
51
+
52
+ from .schematic_style import SchematicStyle
53
+ __all__ += ['SchematicStyle']
54
+ from .audio_displays import LevelMeter, dbfs
55
+ __all__ += ['LevelMeter', 'dbfs']
56
+ from .connection_skin import ConnectionSkin, FuseConnectionSkin, QuarterInchCableSkin
57
+ __all__ += ['ConnectionSkin', 'FuseConnectionSkin', 'QuarterInchCableSkin']
58
+ from .node_shapes import NodeShape, BombNodeShape
59
+ __all__ += ['NodeShape', 'BombNodeShape']
60
+ from .connection_palette import ConnectionPalette
61
+ __all__ += ['ConnectionPalette']
62
+ # Compatibility imports remain available; new integrations use the core models.
63
+ from .compat import (
64
+ SocialsChartService, socials_chart, socials_skin, NeoStudioSceneService,
65
+ SubmediantDiagramService, submediant_skin, SocialsPanelService, socials_panels,
66
+ )
67
+ __all__ += ['SocialsChartService', 'socials_chart', 'socials_skin',
68
+ 'NeoStudioSceneService', 'SubmediantDiagramService', 'submediant_skin',
69
+ 'SocialsPanelService', 'socials_panels']
70
+
71
+ from .chart_config import create_figure_service
72
+ from .render_api import render
73
+ from .renderers.base import RenderedChart
74
+ __all__ += ['render', 'create_figure_service', 'RenderedChart']
75
+
76
+ from .widget_skin import PaletteSkin, palette_skin
77
+ __all__ += ['PaletteSkin', 'palette_skin']
@@ -0,0 +1,101 @@
1
+ """Static audio observations presented with shared scene primitives."""
2
+ from dataclasses import dataclass
3
+ import math
4
+ from .chart_model import finite_number
5
+ from .components import label
6
+ from .scene import Rectangle, Text, Polyline
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class LevelMeter:
11
+ """Static channel levels with optional peak markers, expressed in dBFS.
12
+
13
+ Parameters
14
+ ----------
15
+ values : sequence[float]
16
+ 1–32 finite channel levels in dBFS. Values outside the display range are
17
+ visually clamped; this does not compute audio levels or animate a meter.
18
+ labels : sequence[str], default ()
19
+ One short label per channel; empty generates channel numbers starting at 1.
20
+ minimum_db, maximum_db : float, defaults -60, 0
21
+ Finite increasing display bounds.
22
+ peaks : sequence[float] or None
23
+ Optional finite peak level per channel. Peak markers use the same bounds.
24
+
25
+ Raises
26
+ ------
27
+ ValueError
28
+ Invalid bounds, counts or observations; rendering rejects cramped labels.
29
+
30
+ Notes
31
+ -----
32
+ Use dbfs(amplitude) to convert a nonnegative linear amplitude before plotting.
33
+
34
+
35
+ Examples
36
+ --------
37
+ >>> from unchartable import LevelMeter, render
38
+ >>> chart = LevelMeter((-18, -9), ('Left', 'Right'), peaks=(-10, -3))
39
+ >>> image = render(chart)
40
+ >>> image.media_type
41
+ 'image/svg+xml'
42
+ >>> import xml.etree.ElementTree as ET
43
+ >>> ET.fromstring(image.data).tag.endswith('svg')
44
+ True
45
+ """
46
+ values: tuple[float, ...]
47
+ labels: tuple[str, ...] = ()
48
+ minimum_db: float = -60
49
+ maximum_db: float = 0
50
+ peaks: tuple[float, ...] | None = None
51
+
52
+ def __post_init__(self):
53
+ object.__setattr__(self, 'values', tuple(self.values))
54
+ object.__setattr__(self, 'labels', tuple(self.labels) or tuple(str(i+1) for i in range(len(self.values))))
55
+ if self.peaks is not None: object.__setattr__(self, 'peaks', tuple(self.peaks))
56
+ if not self.values or len(self.values)>32 or len(self.labels)!=len(self.values) or (self.peaks is not None and len(self.peaks)!=len(self.values)):
57
+ raise ValueError('Meter needs 1–32 channels with matching labels and peaks')
58
+ for text in self.labels: label(text)
59
+ for value in (self.minimum_db, self.maximum_db, *self.values, *(self.peaks or ())): finite_number(value)
60
+ if self.minimum_db>=self.maximum_db: raise ValueError('Meter dB range must increase')
61
+
62
+ def arrange(self, context, width, height):
63
+ skin=context.skin.chart_skin()
64
+ left=60; right=width-16; top=28; bottom=height-40
65
+ slot=(right-left)/len(self.values)
66
+ if slot<24 or bottom-top<40 or any(context.renderer.measure_text(t,12)>slot-4 for t in self.labels):
67
+ raise ValueError('Meter needs a larger viewport or shorter labels')
68
+ items=[Rectangle(0,0,width,height,skin.background),Text(12,8,'Level (dBFS)',skin.text,14)]
69
+ fraction=lambda db:max(0,min(1,(db-self.minimum_db)/(self.maximum_db-self.minimum_db)))
70
+ for tick in (self.minimum_db,(self.minimum_db+self.maximum_db)/2,self.maximum_db):
71
+ y=bottom-fraction(tick)*(bottom-top)
72
+ items.extend((Polyline(((left,y),(right,y)),skin.grid,1),Text(left-7,y-6,f'{tick:g}',skin.text,12,'end')))
73
+ for i,(value,name) in enumerate(zip(self.values,self.labels)):
74
+ x=left+(i+.2)*slot;bar=slot*.6
75
+ y=bottom-fraction(value)*(bottom-top)
76
+ items.extend((Rectangle(x,top,bar,bottom-top,skin.grid),Rectangle(x,y,bar,bottom-y,skin.colors[i%len(skin.colors)]),Text(x+bar/2,bottom+10,name,skin.text,12,'middle')))
77
+ if self.peaks is not None:
78
+ peak=bottom-fraction(self.peaks[i])*(bottom-top)
79
+ items.append(Polyline(((x,peak),(x+bar,peak)),skin.text,2))
80
+ return tuple(items)
81
+
82
+
83
+ def dbfs(amplitude, floor=-60):
84
+ """Convert linear amplitude magnitude to a floored dBFS value.
85
+
86
+ Parameters and behaviour
87
+ ------------------------
88
+ amplitude is finite and nonnegative; 1 means full scale (0 dBFS). floor
89
+ defaults to -60 and must be finite and negative. Returns max(floor,
90
+ 20*log10(amplitude)); zero returns floor. This does not compute RMS or peak
91
+ levels from a signal. Invalid input raises ValueError.
92
+
93
+ Examples
94
+ --------
95
+ >>> from unchartable import dbfs
96
+ >>> dbfs(1), dbfs(0)
97
+ (0.0, -60)
98
+ """
99
+ finite_number(amplitude);finite_number(floor)
100
+ if amplitude<0 or floor>=0: raise ValueError('Magnitude must be nonnegative and floor negative')
101
+ return max(floor,20*math.log10(amplitude)) if amplitude else floor
@@ -0,0 +1,173 @@
1
+ """Reusable numeric/date scales and axis policies, independent of rendering."""
2
+ from dataclasses import dataclass
3
+ from datetime import date, datetime, timezone
4
+ import math
5
+
6
+
7
+ def coordinate(value):
8
+ if isinstance(value, datetime):
9
+ if value.tzinfo is None:
10
+ value = value.replace(tzinfo=timezone.utc)
11
+ return value.timestamp()
12
+ if isinstance(value, date):
13
+ return datetime(value.year, value.month, value.day, tzinfo=timezone.utc).timestamp()
14
+ from .chart_model import finite_number
15
+ finite_number(value)
16
+ return float(value)
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Scale:
21
+ """Numeric or UTC date coordinate transformation and domain policy.
22
+
23
+ Parameters
24
+ ----------
25
+ kind : str, default 'linear'
26
+ 'linear', 'log' (base 10), or 'date'. Log observations must be positive.
27
+ domain : (number | date | datetime, number | date | datetime) or None
28
+ Explicit finite increasing bounds; None infers bounds from observations.
29
+ Naive datetimes and dates are interpreted as UTC.
30
+ reverse : bool, default False
31
+ Reverse coordinate direction without changing the domain ordering.
32
+
33
+ >>> from unchartable import Scale
34
+ >>> Scale('log').fraction(10, (1, 100))
35
+ 0.5
36
+ """
37
+ kind: str = 'linear'
38
+ domain: tuple | None = None
39
+ reverse: bool = False
40
+
41
+ def __post_init__(self):
42
+ if self.kind not in ('linear', 'log', 'date'):
43
+ raise ValueError('Scale kind must be linear, log or date')
44
+ if type(self.reverse) is not bool:
45
+ raise ValueError('Scale reverse must be boolean')
46
+ if self.domain is not None:
47
+ if len(self.domain) != 2:
48
+ raise ValueError('Domain needs two endpoints')
49
+ bounds = tuple(coordinate(v) for v in self.domain)
50
+ if bounds[0] >= bounds[1] or not math.isfinite(bounds[1]-bounds[0]):
51
+ raise ValueError('Domain must be finite and increasing')
52
+ if self.kind == 'log' and bounds[0] <= 0:
53
+ raise ValueError('Log domains must be positive')
54
+ object.__setattr__(self, 'domain', bounds)
55
+
56
+ def resolve(self, values, zero=False):
57
+ values = tuple(coordinate(v) for v in values)
58
+ if not values:
59
+ raise ValueError('Scale needs observations')
60
+ if self.kind == 'log' and any(v <= 0 for v in values):
61
+ raise ValueError('Log observations must be positive')
62
+ if self.domain is not None:
63
+ return self.domain
64
+ from .chart_layout import domain
65
+ if self.kind == 'log':
66
+ low, high = min(values), max(values)
67
+ bounds = (low/10, high*10) if low == high else (low, high)
68
+ if bounds[0] <= 0 or not all(math.isfinite(v) for v in bounds):
69
+ raise ValueError('Log range is too extreme; supply an explicit domain')
70
+ return bounds
71
+ return domain(values, zero)
72
+
73
+ def fraction(self, value, bounds):
74
+ value = coordinate(value)
75
+ low, high = bounds
76
+ if self.kind == 'log':
77
+ if value <= 0:
78
+ raise ValueError('Log coordinates must be positive')
79
+ low, high, value = math.log10(low), math.log10(high), math.log10(value)
80
+ fraction = (value-low)/(high-low)
81
+ return 1-fraction if self.reverse else fraction
82
+
83
+
84
+ @dataclass(frozen=True)
85
+ class Axis:
86
+ """Axis scale, label, tick positions and text formatting.
87
+
88
+ Parameters
89
+ ----------
90
+ scale : Scale
91
+ Coordinate transform and optional explicit domain.
92
+ label : str, default ''
93
+ Single-line axis caption.
94
+ ticks : sequence[number | date | datetime] or None
95
+ 1–100 explicit ticks; ticks outside the resolved domain are omitted.
96
+ None generates ticks from the scale.
97
+ format : str or None
98
+ Python numeric format specification (for example '.1f') or strftime
99
+ pattern for dates (for example '%b %d'). None chooses a default.
100
+
101
+ >>> from unchartable import Axis
102
+ >>> Axis(ticks=(0, 1), format='.1f').tick_pairs((0, 1))
103
+ ((0.0, '0.0'), (1.0, '1.0'))
104
+ """
105
+ scale: Scale = Scale()
106
+ label: str = ''
107
+ ticks: tuple | None = None
108
+ format: str | None = None
109
+
110
+ def __post_init__(self):
111
+ if not isinstance(self.label, str) or any(ord(c) < 32 for c in self.label):
112
+ raise ValueError('Axis label must be single-line text')
113
+ if self.ticks is not None:
114
+ object.__setattr__(self, 'ticks', tuple(coordinate(v) for v in self.ticks))
115
+ if not self.ticks or len(self.ticks) > 100:
116
+ raise ValueError('Provide 1–100 axis ticks')
117
+
118
+ def tick_pairs(self, bounds):
119
+ from .chart_layout import axis_ticks
120
+ low, high = bounds
121
+ if self.ticks is not None:
122
+ values = [v for v in self.ticks if low <= v <= high]
123
+ elif self.scale.kind == 'date':
124
+ values = [low+(high-low)*i/2 for i in range(3)]
125
+ elif self.scale.kind == 'log':
126
+ values = [10.**i for i in range(math.ceil(math.log10(low)), math.floor(math.log10(high))+1)]
127
+ if not values:
128
+ values = [low, high]
129
+ else:
130
+ values, _ = axis_ticks(low, high)
131
+ if self.scale.kind == 'date':
132
+ default_format = '%Y-%m-%d' if high-low >= 172800 else '%m-%d %H:%M' if high-low >= 86400 else '%H:%M:%S'
133
+ labels = [datetime.fromtimestamp(v, timezone.utc).strftime(self.format or default_format) for v in values]
134
+ elif self.format:
135
+ labels = [format(v, self.format) for v in values]
136
+ elif self.ticks is None and self.scale.kind == 'linear':
137
+ _, labels = axis_ticks(low, high)
138
+ else:
139
+ labels = [format(v, '.6g') for v in values]
140
+ return tuple(zip(values, labels))
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class Annotation:
145
+ """A single-line callout anchored to chart data coordinates.
146
+
147
+ Parameters
148
+ ----------
149
+ x, y : number or date-like coordinate
150
+ Data coordinates. For categorical X, use zero-based category indices.
151
+ text : str
152
+ Nonempty single-line caption.
153
+ max_width : int, default 180
154
+ Maximum callout text width in scene units, at least 20.
155
+
156
+ >>> from unchartable import Annotation
157
+ >>> Annotation(1, 18, 'Peak').text
158
+ 'Peak'
159
+ """
160
+ x: float
161
+ y: float
162
+ text: str
163
+ max_width: int = 180
164
+
165
+ def __post_init__(self):
166
+ coordinate(self.x)
167
+ coordinate(self.y)
168
+ if not isinstance(self.text, str) or not self.text or any(ord(c) < 32 for c in self.text):
169
+ raise ValueError('Annotation text must be a nonempty single-line string')
170
+ if type(self.max_width) is not int or self.max_width < 20:
171
+ raise ValueError('Annotation width must be at least 20')
172
+
173
+ # Coordinates are data values; categorical x uses zero-based category indices.
@@ -0,0 +1,182 @@
1
+ """pyiv composition roots. Subclass hooks to replace rendering, layout, or styling."""
2
+ from pyiv import Config, get_injector
3
+ from .chart_layout import ChartLayout
4
+ from .chart_service import ChartService
5
+ from .scene import Skin
6
+ from .font_provider import FontProvider
7
+ from .schematic_symbols import SchematicSymbols
8
+ from .graph_layout import GraphLayout, GraphOptions
9
+ from .connection_skin import ConnectionSkin
10
+ from .text_layout import TextLayout
11
+ from .widget_skin import WidgetSkin
12
+ from .figure_service import FigureService
13
+ from .renderers.base import Renderer
14
+ from .renderers.svg_renderer import SVGRenderer
15
+
16
+
17
+ class ChartConfig(Config):
18
+ """SVG composition root for the public rendering services.
19
+
20
+ Pass this class (not an instance) to render(), create_chart_service() or
21
+ create_figure_service(). Each call to a factory creates a local pyiv injector.
22
+ Subclass get_widget_skin() for component/diagram styling, get_skin() for bare
23
+ Cartesian charts, get_connection_skin() for routed lines, or
24
+ get_font_provider_class() for explicitly supplied fonts. The default
25
+ get_skin() delegates to get_widget_skin().chart_skin(), so overriding the
26
+ widget skin is the consistent way to style both chart and figure rendering.
27
+
28
+ get_renderer_class(), get_layout_class() and get_graph_layout_class() are
29
+ advanced replacement hooks. When overriding configure(), call super().configure()
30
+ to preserve the built-in registrations. Models remain independent of pyiv.
31
+
32
+ >>> from unchartable import ChartConfig, AquaSkin, PieChart, render
33
+ >>> class ReportConfig(ChartConfig):
34
+ ... def get_widget_skin(self):
35
+ ... return AquaSkin()
36
+ >>> render(PieChart(('A','B'),(2,3)), config=ReportConfig).media_type
37
+ 'image/svg+xml'
38
+ """
39
+ def get_socials_service_class(self):
40
+ from .socials_adapter import SocialsChartService
41
+ return SocialsChartService
42
+
43
+ def get_socials_panel_service_class(self):
44
+ from .socials_panels import SocialsPanelService
45
+ return SocialsPanelService
46
+
47
+ def get_neostudio_service_class(self):
48
+ from .neostudio_adapter import NeoStudioSceneService
49
+ return NeoStudioSceneService
50
+
51
+ def get_submediant_service_class(self):
52
+ from .submediant_adapter import SubmediantDiagramService
53
+ return SubmediantDiagramService
54
+
55
+ def get_connection_skin(self):
56
+ return ConnectionSkin()
57
+
58
+ def get_graph_layout_class(self):
59
+ return GraphLayout
60
+
61
+ def get_graph_options(self):
62
+ return GraphOptions()
63
+
64
+ def get_schematic_symbols_class(self):
65
+ return SchematicSymbols
66
+
67
+ def get_font_provider_class(self):
68
+ return FontProvider
69
+
70
+ def get_text_layout_class(self):
71
+ return TextLayout
72
+
73
+ def get_renderer_class(self):
74
+ return SVGRenderer
75
+
76
+ def get_layout_class(self):
77
+ return ChartLayout
78
+
79
+ def get_widget_skin(self):
80
+ return WidgetSkin()
81
+
82
+ def get_skin(self):
83
+ return self.get_widget_skin().chart_skin()
84
+
85
+ def configure(self):
86
+ super().configure()
87
+ from .socials_adapter import SocialsChartService
88
+ from .socials_panels import SocialsPanelService
89
+ from .neostudio_adapter import NeoStudioSceneService
90
+ from .submediant_adapter import SubmediantDiagramService
91
+ self.register(SocialsChartService, self.get_socials_service_class())
92
+ self.register(SocialsPanelService, self.get_socials_panel_service_class())
93
+ self.register(NeoStudioSceneService, self.get_neostudio_service_class())
94
+ self.register(SubmediantDiagramService, self.get_submediant_service_class())
95
+ self.register(GraphLayout, self.get_graph_layout_class())
96
+ self.register(GraphOptions, self.get_graph_options, singleton=True)
97
+ self.register(ConnectionSkin, self.get_connection_skin, singleton=True)
98
+ self.register(SchematicSymbols, self.get_schematic_symbols_class(), singleton=True)
99
+ self.register(TextLayout, self.get_text_layout_class(), singleton=True)
100
+ self.register(FontProvider, self.get_font_provider_class(), singleton=True)
101
+ self.register(WidgetSkin, self.get_widget_skin, singleton=True)
102
+ self.register(FigureService, FigureService)
103
+ self.register(Skin, self.get_skin, singleton=True)
104
+ self.register(Renderer, self.get_renderer_class(), singleton=True)
105
+ self.register(ChartLayout, self.get_layout_class())
106
+ self.register(ChartService, ChartService)
107
+
108
+
109
+ class PillowChartConfig(ChartConfig):
110
+ """PNG composition root using the same chart layout as SVG.
111
+
112
+ Install the pillow extra before using this class. Pass the class as
113
+ config=PillowChartConfig to render(). Subclass its inherited styling hooks
114
+ for custom PNG skins. get_pillow_options() supplies renderer-owned rasterisation
115
+ settings. PNG output may contain transparency; the filename does not select it.
116
+
117
+ >>> from unchartable import Chart, Series, PillowChartConfig, render
118
+ >>> image = render(Chart(('A',), (Series('Count',(2,)),)), config=PillowChartConfig)
119
+ >>> image.media_type
120
+ 'image/png'
121
+ >>> image.data[:8] == bytes((137,80,78,71,13,10,26,10))
122
+ True
123
+ """
124
+ def get_renderer_class(self):
125
+ from .renderers.pillow_renderer import PillowRenderer
126
+ return PillowRenderer
127
+
128
+ def get_pillow_options(self):
129
+ from .renderers.pillow_renderer import PillowOptions
130
+ return PillowOptions()
131
+
132
+ def configure(self):
133
+ super().configure()
134
+ from .renderers.pillow_renderer import PillowOptions
135
+ self.register(PillowOptions, self.get_pillow_options, singleton=True)
136
+
137
+
138
+ def create_chart_service(config=ChartConfig) -> ChartService:
139
+ """Create a reusable Cartesian chart service using a fresh local injector.
140
+
141
+ Parameters
142
+ ----------
143
+ config : type[ChartConfig]
144
+ Composition-root class; defaults to SVG. PillowChartConfig selects PNG.
145
+ Subclass Config hooks to replace fonts, layout or renderer implementations.
146
+
147
+ Returns
148
+ -------
149
+ ChartService
150
+ Call render(chart) for bytes or layout(chart) for the resolved Scene.
151
+ This service accepts Chart, not radial or other Component objects.
152
+ Use create_figure_service() for Figure or render() for either kind.
153
+
154
+ >>> from unchartable import Chart, Series, create_chart_service
155
+ >>> service = create_chart_service()
156
+ >>> service.render(Chart(('A',), (Series('Count', (3,)),))).media_type
157
+ 'image/svg+xml'
158
+ """
159
+ return get_injector(config).inject(ChartService)
160
+
161
+
162
+ def create_figure_service(config=ChartConfig) -> FigureService:
163
+ """Create a reusable figure service with a fresh local dependency injector.
164
+
165
+ Parameters
166
+ ----------
167
+ config : type[ChartConfig]
168
+ Config class supplying renderer, widget skin, fonts and graph layout.
169
+ Defaults to SVG. Use PillowChartConfig for PNG.
170
+
171
+ Returns
172
+ -------
173
+ FigureService
174
+ Reuse this service for multiple figures with the same configuration.
175
+ Use render() for a single chart without explicit service management.
176
+
177
+ >>> from unchartable import create_figure_service, Figure, PieChart
178
+ >>> service = create_figure_service()
179
+ >>> service.render(Figure(PieChart(('A', 'B'), (2, 3)))).media_type
180
+ 'image/svg+xml'
181
+ """
182
+ return get_injector(config).inject(FigureService)