-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path__init__.py
More file actions
147 lines (120 loc) · 3.98 KB
/
__init__.py
File metadata and controls
147 lines (120 loc) · 3.98 KB
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
from __future__ import annotations
import json
from typing import Any, Union
import altair
import narwhals as nw
from narwhals.typing import IntoFrame
from ggsql._ggsql import (
DuckDBReader,
VegaLiteWriter as _RustVegaLiteWriter,
Validated,
Spec,
validate,
execute,
)
__all__ = [
# Classes
"DuckDBReader",
"VegaLiteWriter",
"Validated",
"Spec",
# Functions
"validate",
"execute",
"render_altair",
]
__version__ = "0.1.0"
# Type alias for any Altair chart type
AltairChart = Union[
altair.Chart,
altair.LayerChart,
altair.FacetChart,
altair.ConcatChart,
altair.HConcatChart,
altair.VConcatChart,
altair.RepeatChart,
]
def _json_to_altair_chart(vegalite_json: str, **kwargs: Any) -> AltairChart:
"""Convert a Vega-Lite JSON string to the appropriate Altair chart type."""
spec = json.loads(vegalite_json)
if "layer" in spec:
return altair.LayerChart.from_json(vegalite_json, **kwargs)
elif "facet" in spec or "spec" in spec:
return altair.FacetChart.from_json(vegalite_json, **kwargs)
elif "concat" in spec:
return altair.ConcatChart.from_json(vegalite_json, **kwargs)
elif "hconcat" in spec:
return altair.HConcatChart.from_json(vegalite_json, **kwargs)
elif "vconcat" in spec:
return altair.VConcatChart.from_json(vegalite_json, **kwargs)
elif "repeat" in spec:
return altair.RepeatChart.from_json(vegalite_json, **kwargs)
else:
return altair.Chart.from_json(vegalite_json, **kwargs)
class VegaLiteWriter:
"""Vega-Lite v6 JSON output writer.
Methods
-------
render(spec)
Render a Spec to a Vega-Lite JSON string.
render_chart(spec, **kwargs)
Render a Spec to an Altair chart object.
"""
def __init__(self) -> None:
self._inner = _RustVegaLiteWriter()
def render(self, spec: Spec) -> str:
"""Render a Spec to a Vega-Lite JSON string."""
return self._inner.render(spec)
def render_chart(self, spec: Spec, **kwargs: Any) -> AltairChart:
"""Render a Spec to an Altair chart object.
Parameters
----------
spec
The resolved visualization specification from ``reader.execute()``.
**kwargs
Additional keyword arguments passed to ``altair.Chart.from_json()``.
Common options include ``validate=False`` to skip schema validation.
Returns
-------
AltairChart
An Altair chart object (Chart, LayerChart, FacetChart, etc.).
"""
vegalite_json = self.render(spec)
return _json_to_altair_chart(vegalite_json, **kwargs)
def render_altair(
df: IntoFrame,
viz: str,
**kwargs: Any,
) -> AltairChart:
"""Render a DataFrame with a VISUALISE spec to an Altair chart.
Parameters
----------
df
Data to visualize. Accepts polars, pandas, or any narwhals-compatible
DataFrame. LazyFrames are collected automatically.
viz
VISUALISE spec string (e.g., "VISUALISE x, y DRAW point")
**kwargs
Additional keyword arguments passed to `from_json()`.
Common options include `validate=False` to skip schema validation.
Returns
-------
AltairChart
An Altair chart object (Chart, LayerChart, FacetChart, etc.).
"""
df = nw.from_native(df, pass_through=True)
if isinstance(df, nw.LazyFrame):
df = df.collect()
if not isinstance(df, nw.DataFrame):
raise TypeError("df must be a narwhals DataFrame or compatible type")
pl_df = df.to_polars()
# Create temporary reader and register data
reader = DuckDBReader("duckdb://memory")
reader.register("__data__", pl_df)
# Build full query: SELECT * FROM __data__ + VISUALISE clause
query = f"SELECT * FROM __data__ {viz}"
# Execute and render
spec = reader.execute(query)
writer = VegaLiteWriter()
vegalite_json = writer.render(spec)
return _json_to_altair_chart(vegalite_json, **kwargs)