codepbi 0.1.7__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.
codepbi/writer.py ADDED
@@ -0,0 +1,238 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from .ids import guid
7
+ from .model import Filter, Page, Report, Visual, field_ref
8
+
9
+ PBIP_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/pbip/pbipProperties/1.0.0/schema.json"
10
+ PLATFORM_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/gitIntegration/platformProperties/2.0.0/schema.json"
11
+ PBIR_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definitionProperties/2.0.0/schema.json"
12
+ REPORT_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/report/3.3.0/schema.json"
13
+ VERSION_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/versionMetadata/1.0.0/schema.json"
14
+ PAGES_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/pagesMetadata/1.1.0/schema.json"
15
+ PAGE_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/page/2.1.0/schema.json"
16
+ VISUAL_SCHEMA = "https://developer.microsoft.com/json-schemas/fabric/item/report/definition/visualContainer/2.12.0/schema.json"
17
+
18
+
19
+ def _write_json(path: Path, data: dict) -> None:
20
+ path.parent.mkdir(parents=True, exist_ok=True)
21
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
22
+
23
+
24
+ def _projection(f) -> dict:
25
+ return {
26
+ "field": field_ref(f.entity, f.property, f.is_measure),
27
+ "queryRef": f.query_ref,
28
+ "nativeQueryRef": f.native_query_ref,
29
+ }
30
+
31
+
32
+ def _filter_json(filt: Filter) -> dict:
33
+ base = {
34
+ "name": filt.name,
35
+ "field": field_ref(filt.entity, filt.property),
36
+ "type": filt.kind,
37
+ }
38
+ if filt.kind == "Advanced" and filt.value is not None:
39
+ base["filter"] = {
40
+ "Version": 2,
41
+ "From": [{"Name": "c", "Entity": filt.entity, "Type": 0}],
42
+ "Where": [
43
+ {
44
+ "Condition": {
45
+ "Comparison": {
46
+ "ComparisonKind": 0,
47
+ "Left": {
48
+ "Column": {
49
+ "Expression": {"SourceRef": {"Source": "c"}},
50
+ "Property": filt.property,
51
+ }
52
+ },
53
+ "Right": {"Literal": {"Value": f"'{filt.value}'"}},
54
+ }
55
+ }
56
+ }
57
+ ],
58
+ }
59
+ base["howCreated"] = "User"
60
+ return base
61
+
62
+
63
+ def _visual_json(visual: Visual) -> dict:
64
+ pos = visual.position
65
+ data = {
66
+ "$schema": VISUAL_SCHEMA,
67
+ "name": visual.name,
68
+ "position": {
69
+ "x": pos.x,
70
+ "y": pos.y,
71
+ "z": pos.z,
72
+ "height": pos.height,
73
+ "width": pos.width,
74
+ "tabOrder": pos.tab_order,
75
+ },
76
+ }
77
+ if visual.visual_group is not None:
78
+ group_body = dict(visual.visual_group)
79
+ if visual.objects:
80
+ group_body["objects"] = visual.objects
81
+ data["visualGroup"] = group_body
82
+ else:
83
+ visual_body = {
84
+ "visualType": visual.visual_type,
85
+ "drillFilterOtherVisuals": visual.drill_filter_other_visuals,
86
+ }
87
+ if visual.roles:
88
+ # Static visuals (textbox, image) have no query roles at all -- confirmed from
89
+ # real Desktop-saved examples, not just an empty queryState.
90
+ query_state = {
91
+ role: {"projections": [_projection(f) for f in fields]}
92
+ for role, fields in visual.roles.items()
93
+ }
94
+ visual_body["query"] = {"queryState": query_state}
95
+ if visual.objects:
96
+ visual_body["objects"] = visual.objects
97
+ if visual.visual_container_objects:
98
+ visual_body["visualContainerObjects"] = visual.visual_container_objects
99
+ data["visual"] = visual_body
100
+ if visual.parent_group_name:
101
+ data["parentGroupName"] = visual.parent_group_name
102
+ if visual.filters:
103
+ data["filterConfig"] = {"filters": [_filter_json(f) for f in visual.filters]}
104
+ return data
105
+
106
+
107
+ def _page_json(page: Page) -> dict:
108
+ data = {
109
+ "$schema": PAGE_SCHEMA,
110
+ "name": page.name,
111
+ "displayName": page.display_name,
112
+ "displayOption": page.display_option,
113
+ "height": page.height,
114
+ "width": page.width,
115
+ }
116
+ if page.page_type:
117
+ data["type"] = page.page_type
118
+ if page.page_binding:
119
+ data["pageBinding"] = page.page_binding
120
+ if page.visual_interactions:
121
+ data["visualInteractions"] = page.visual_interactions
122
+ if page.objects:
123
+ data["objects"] = page.objects
124
+ if page.filters:
125
+ data["filterConfig"] = {"filters": [_filter_json(f) for f in page.filters]}
126
+ return data
127
+
128
+
129
+ def _report_json(report: Report) -> dict:
130
+ theme_collection = {}
131
+ # Theme + images share ONE "RegisteredResources" package -- confirmed from a real
132
+ # Desktop-saved report with both a custom theme and a logo image.
133
+ registered_items = []
134
+ if report.theme:
135
+ theme_name = report.theme["name"]
136
+ theme_collection["customTheme"] = {
137
+ "name": theme_name,
138
+ "reportVersionAtImport": {"visual": "1.0.0", "page": "1.0.0", "report": "1.0.0"},
139
+ "type": "RegisteredResources",
140
+ }
141
+ # path is just the bare theme name -- no folder prefix, no extension. Confirmed:
142
+ # Desktop normalized our original "RegisteredResources/<name>.json" guess down to this.
143
+ registered_items.append({"name": theme_name, "path": theme_name, "type": "CustomTheme"})
144
+ for resource_name, _local_path in report.images:
145
+ registered_items.append({"name": resource_name, "path": resource_name, "type": "Image"})
146
+ resource_packages = (
147
+ [{"name": "RegisteredResources", "type": "RegisteredResources", "items": registered_items}]
148
+ if registered_items else []
149
+ )
150
+ data = {
151
+ "$schema": REPORT_SCHEMA,
152
+ # Required by the schema -- an empty object is valid (baseTheme/customTheme
153
+ # are both optional sub-fields), and Desktop applies its own default theme.
154
+ "themeCollection": theme_collection,
155
+ "settings": {
156
+ "useStylableVisualContainerHeader": True,
157
+ "exportDataMode": "AllowSummarized",
158
+ "defaultDrillFilterOtherVisuals": True,
159
+ "allowChangeFilterTypes": True,
160
+ "useEnhancedTooltips": True,
161
+ "useDefaultAggregateDisplayName": True,
162
+ },
163
+ }
164
+ if resource_packages:
165
+ data["resourcePackages"] = resource_packages
166
+ if report.filters:
167
+ data["filterConfig"] = {"filters": [_filter_json(f) for f in report.filters]}
168
+ return data
169
+
170
+
171
+ def write_report(report: Report, parent_dir: str) -> str:
172
+ """Write a full .pbip + .Report folder tree. Does not create the semantic model --
173
+ `report.semantic_model_path` must point at one that already exists (relative to the .Report folder)."""
174
+ parent = Path(parent_dir)
175
+ report_dir = parent / f"{report.name}.Report"
176
+
177
+ _write_json(
178
+ parent / f"{report.name}.pbip",
179
+ {
180
+ "$schema": PBIP_SCHEMA,
181
+ "version": "1.0",
182
+ "artifacts": [{"report": {"path": f"{report.name}.Report"}}],
183
+ "settings": {"enableAutoRecovery": True},
184
+ },
185
+ )
186
+
187
+ _write_json(
188
+ report_dir / ".platform",
189
+ {
190
+ "$schema": PLATFORM_SCHEMA,
191
+ "metadata": {"type": "Report", "displayName": report.name},
192
+ "config": {"version": "2.0", "logicalId": guid()},
193
+ },
194
+ )
195
+
196
+ _write_json(
197
+ report_dir / "definition.pbir",
198
+ {
199
+ "$schema": PBIR_SCHEMA,
200
+ "version": "4.0",
201
+ "datasetReference": {"byPath": {"path": report.semantic_model_path}},
202
+ },
203
+ )
204
+
205
+ _write_json(report_dir / "definition" / "report.json", _report_json(report))
206
+
207
+ if report.theme:
208
+ _write_json(
209
+ report_dir / "StaticResources" / "RegisteredResources" / f"{report.theme['name']}.json",
210
+ report.theme,
211
+ )
212
+
213
+ for resource_name, local_path in report.images:
214
+ dest = report_dir / "StaticResources" / "RegisteredResources" / resource_name
215
+ dest.parent.mkdir(parents=True, exist_ok=True)
216
+ dest.write_bytes(Path(local_path).read_bytes())
217
+
218
+ _write_json(
219
+ report_dir / "definition" / "version.json",
220
+ {"$schema": VERSION_SCHEMA, "version": "2.0.0"},
221
+ )
222
+
223
+ _write_json(
224
+ report_dir / "definition" / "pages" / "pages.json",
225
+ {
226
+ "$schema": PAGES_SCHEMA,
227
+ "pageOrder": [p.name for p in report.pages],
228
+ "activePageName": report.active_page_name,
229
+ },
230
+ )
231
+
232
+ for page in report.pages:
233
+ page_dir = report_dir / "definition" / "pages" / page.name
234
+ _write_json(page_dir / "page.json", _page_json(page))
235
+ for visual in page.visuals:
236
+ _write_json(page_dir / "visuals" / visual.name / "visual.json", _visual_json(visual))
237
+
238
+ return str(report_dir)
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: codepbi
3
+ Version: 0.1.7
4
+ Summary: Code-first Power BI — define pages/visuals in Python and emit a working PBIP/PBIR report; sync a TMDL semantic model from a dbt project.
5
+ Author: Ryan Thomas
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ryantthomas/codepbi
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Provides-Extra: semantic
12
+ Requires-Dist: pyyaml; extra == "semantic"
13
+ Requires-Dist: sqlglot; extra == "semantic"
14
+ Requires-Dist: pythonnet; extra == "semantic"
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # codepbi
20
+
21
+ Code-first Power BI. Define pages and visuals in Python, get a working PBIP/PBIR
22
+ report that opens and edits normally in Power BI Desktop.
23
+
24
+ ```python
25
+ from codepbi import Field, Filter, Position, Report
26
+
27
+ report = Report(name="Sales Overview", semantic_model_path="../Sales.SemanticModel")
28
+ page = report.add_page("Overview")
29
+ page.add_slicer(Field("Orders", "Region"), Position(x=0, y=0, width=200, height=400))
30
+ page.add_table(
31
+ fields=[Field("Orders", "Region"), Field("Orders", "Order Amount")],
32
+ position=Position(x=220, y=0, width=800, height=400),
33
+ filters=[Filter.equals("Orders", "Status", "Active")],
34
+ )
35
+ report.save("output_dir")
36
+ ```
37
+
38
+ ## `codepbi.semantic`
39
+
40
+ A separate module for the other half of the workflow: syncing a Power BI TMDL
41
+ semantic model *from* a dbt project, via the Tabular Object Model (TOM). Treats
42
+ dbt's schema YAML as the source of truth for columns, and a dbt-semantic-layer-
43
+ style `semantic_models/*.yml` (entities + measures) as the source of truth for
44
+ joins and DAX measures.
45
+
46
+ ```python
47
+ from codepbi.semantic import TmdlProjectConfig, sync_descriptions, sync_measures, sync_relationships
48
+
49
+ config = TmdlProjectConfig(
50
+ dbt_project_dir="path/to/dbt_project",
51
+ semantic_model_definition_dir="path/to/Model.SemanticModel/definition",
52
+ tom_lib_dir="path/to/analysis-services-dlls",
53
+ )
54
+
55
+ sync_measures.sync(config)
56
+ sync_descriptions.sync(config) # also validates the resulting model
57
+ sync_relationships.sync(config)
58
+ ```
59
+
60
+ Requires the `semantic` extra (`pip install codepbi[semantic]`) plus the
61
+ `Microsoft.AnalysisServices.NetCore.retail.amd64` NuGet package's DLLs, obtained
62
+ separately and pointed at via `tom_lib_dir` (not redistributed here).
63
+
64
+ ## Install
65
+
66
+ ```bash
67
+ pip install -e . # report/visual builder only
68
+ pip install -e ".[semantic]" # + the dbt-to-TMDL sync module
69
+ ```
70
+
71
+ ## License
72
+
73
+ MIT
@@ -0,0 +1,20 @@
1
+ codepbi/__init__.py,sha256=sAC2xsHqqSST-_arq8GEFeDZ9nDPX67vw_gERVOgTYM,334
2
+ codepbi/ids.py,sha256=5i4ALYWLZYp9bj5u__BpzFD3k3Jwcr0enDFMvQ9IP0Y,272
3
+ codepbi/model.py,sha256=Hk_omy24KrCUwOWgQUT14S9uPuFEf9GKn9CfmUAr5vI,16933
4
+ codepbi/writer.py,sha256=YnSRyV7W_Adx9NvE6S_XW1U0wLwBjWD9cTc73-SupfI,9064
5
+ codepbi/semantic/__init__.py,sha256=3MiYIdZCd6fXcxyWoWLodmuIDy9KkenDcalnP5hc-F0,1408
6
+ codepbi/semantic/check_drift.py,sha256=TMSYRYiXpeXJq5gLaV4HshKDaqmnQ6KN8ZteSmZlB8k,1691
7
+ codepbi/semantic/check_schema_vs_sql.py,sha256=CvV84Qg-t6aQqIg3QOu630Jzx_rpQSSbaqkXD6HVxPc,2623
8
+ codepbi/semantic/config.py,sha256=GxChvIe3OwThfMPmwHjHS2d1MEBWf4MON5fFEDVq5gY,3291
9
+ codepbi/semantic/dbt_sql.py,sha256=mRh2BGhf25dGSUwWSAwjm5VDUDcdMRBsBnLZL_1Xk0A,2850
10
+ codepbi/semantic/schema_loader.py,sha256=h4WFjrvjU7ZfTzCuDK5NE9roxEAvQQYusRYMeU4jUV0,6012
11
+ codepbi/semantic/sync_descriptions.py,sha256=t_te5YrBVqq8opNQIgrbDcjZnlJf1VlHf6OZ-xPrkSA,6084
12
+ codepbi/semantic/sync_measures.py,sha256=J78B2yP3idc6_3YKyP1yIM-yUl_ClT1Bxw33ryIhMM8,5020
13
+ codepbi/semantic/sync_relationships.py,sha256=TnHg6b3MXBwWhh0Btht8KJs6AocUwVd_6HaFbj0ieds,9920
14
+ codepbi/semantic/tom_utils.py,sha256=Q9YjhNaHel33e007SQFLZltUmgab5_FYvvn8PY3FIz4,3812
15
+ codepbi/semantic/validate_tmdl.py,sha256=85oDtZ97_B-rfH0uAFu9sGG7HwkzncOMmbCziejcVeU,9893
16
+ codepbi-0.1.7.dist-info/licenses/LICENSE,sha256=7GtHbapYMAtkjp_8KUJr9WO_7QvuML78C0u1ECJ0rOk,1068
17
+ codepbi-0.1.7.dist-info/METADATA,sha256=byIZ9VXe0DZCmCepydhdEviW3vgN2u3-pF8xPri4MbY,2557
18
+ codepbi-0.1.7.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
19
+ codepbi-0.1.7.dist-info/top_level.txt,sha256=SYYZLt2dpUrDnveNvzA3ukuPDEanEX0ReeLYexlZOlo,8
20
+ codepbi-0.1.7.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ryan Thomas
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 @@
1
+ codepbi