Skip to content

Commit a5d34b2

Browse files
authored
added get_semantic_model_definition (#308)
* added get_semantic_model_definition * update * updates per comments * added docs
1 parent ebd7b84 commit a5d34b2

File tree

4 files changed

+78
-21
lines changed

4 files changed

+78
-21
lines changed

src/sempy_labs/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@
190190
get_semantic_model_bim,
191191
get_semantic_model_size,
192192
update_semantic_model_from_bim,
193+
get_semantic_model_definition,
193194
)
194195
from sempy_labs._list_functions import (
195196
list_reports_using_semantic_model,
@@ -456,4 +457,5 @@
456457
"create_vnet_gateway",
457458
"update_vnet_gateway",
458459
"update_on_premises_gateway",
460+
"get_semantic_model_definition",
459461
]

src/sempy_labs/_generate_semantic_model.py

Lines changed: 73 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import pandas as pd
33
import json
44
import os
5-
from typing import Optional
5+
from typing import Optional, List
66
from sempy_labs._helper_functions import (
77
resolve_lakehouse_name,
88
resolve_workspace_name_and_id,
@@ -329,8 +329,6 @@ def get_semantic_model_bim(
329329
"""
330330
Extracts the Model.bim file for a given semantic model.
331331
332-
This is a wrapper function for the following API: `Items - Get Semantic Model Definition <https://learn.microsoft.com/rest/api/fabric/semanticmodel/items/get-semantic-model-definition>`_.
333-
334332
Parameters
335333
----------
336334
dataset : str
@@ -352,20 +350,7 @@ def get_semantic_model_bim(
352350
The Model.bim file for the semantic model.
353351
"""
354352

355-
(workspace, workspace_id) = resolve_workspace_name_and_id(workspace)
356-
357-
fmt = "TMSL"
358-
client = fabric.FabricRestClient()
359-
dataset_id = resolve_dataset_id(dataset=dataset, workspace=workspace)
360-
response = client.post(
361-
f"/v1/workspaces/{workspace_id}/semanticModels/{dataset_id}/getDefinition?format={fmt}",
362-
)
363-
result = lro(client, response).json()
364-
df_items = pd.json_normalize(result["definition"]["parts"])
365-
df_items_filt = df_items[df_items["path"] == "model.bim"]
366-
payload = df_items_filt["payload"].iloc[0]
367-
bimFile = _decode_b64(payload)
368-
bimJson = json.loads(bimFile)
353+
bimJson = get_semantic_model_definition(dataset=dataset, workspace=workspace, format='TMSL', return_dataframe=False)
369354

370355
if save_to_file_name is not None:
371356
if not lakehouse_attached():
@@ -384,12 +369,82 @@ def get_semantic_model_bim(
384369
with open(filePath, "w") as json_file:
385370
json.dump(bimJson, json_file, indent=4)
386371
print(
387-
f"{icons.green_dot} The .bim file for the '{dataset}' semantic model has been saved to the '{lakehouse}' in this location: '{filePath}'.\n\n"
372+
f"{icons.green_dot} The {fileExt} file for the '{dataset}' semantic model has been saved to the '{lakehouse}' in this location: '{filePath}'.\n\n"
388373
)
389374

390375
return bimJson
391376

392377

378+
def get_semantic_model_definition(
379+
dataset: str,
380+
format: str = "TMSL",
381+
workspace: Optional[str] = None,
382+
return_dataframe: bool = True,
383+
) -> pd.DataFrame | dict | List:
384+
"""
385+
Extracts the semantic model definition.
386+
387+
This is a wrapper function for the following API: `Items - Get Semantic Model Definition <https://learn.microsoft.com/rest/api/fabric/semanticmodel/items/get-semantic-model-definition>`_.
388+
389+
Parameters
390+
----------
391+
dataset : str
392+
Name of the semantic model.
393+
format : str, default="TMSL"
394+
The output format. Valid options are "TMSL" or "TMDL". "TMSL" returns the .bim file whereas "TMDL" returns the collection of TMDL files. Can also enter 'bim' for the TMSL version.
395+
workspace : str, default=None
396+
The Fabric workspace name in which the semantic model resides.
397+
Defaults to None which resolves to the workspace of the attached lakehouse
398+
or if no lakehouse attached, resolves to the workspace of the notebook.
399+
return_dataframe : bool, default=True
400+
If True, returns a dataframe.
401+
If False, returns the .bim file for TMSL format. Returns a list of the TMDL files (decoded) for TMDL format.
402+
403+
Returns
404+
-------
405+
pandas.DataFrame | dict | List
406+
A pandas dataframe with the semantic model definition or the file or files comprising the semantic model definition.
407+
"""
408+
409+
valid_formats = ['TMSL', 'TMDL']
410+
411+
format = format.upper()
412+
if format == 'BIM':
413+
format = "TMSL"
414+
if format not in valid_formats:
415+
raise ValueError(f"{icons.red_dot} Invalid format. Valid options: {valid_formats}.")
416+
417+
(workspace, workspace_id) = resolve_workspace_name_and_id(workspace)
418+
419+
client = fabric.FabricRestClient()
420+
dataset_id = resolve_dataset_id(dataset=dataset, workspace=workspace)
421+
response = client.post(
422+
f"/v1/workspaces/{workspace_id}/semanticModels/{dataset_id}/getDefinition?format={format}",
423+
)
424+
result = lro(client, response).json()
425+
426+
files = result["definition"]["parts"]
427+
428+
if return_dataframe:
429+
return pd.json_normalize(files)
430+
elif format == 'TMSL':
431+
payload = next(
432+
(part["payload"] for part in files if part["path"] == "model.bim"),
433+
None
434+
)
435+
return json.loads(_decode_b64(payload))
436+
else:
437+
decoded_parts = [
438+
{
439+
"file_name": part["path"],
440+
"content": _decode_b64(part['payload'])
441+
}
442+
for part in files
443+
]
444+
445+
return decoded_parts
446+
447+
393448
def get_semantic_model_size(dataset: str, workspace: Optional[str] = None):
394449

395450
workspace = fabric.resolve_workspace_name(workspace)

src/sempy_labs/_workspaces.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def add_user_to_workspace(
153153
Parameters
154154
----------
155155
email_address : str
156-
The email address of the user.
156+
The email address of the user. Also accepts the user identifier.
157157
role_name : str
158158
The `role <https://learn.microsoft.com/rest/api/power-bi/groups/add-group-user#groupuseraccessright>`_ of the user within the workspace.
159159
principal_type : str, default='User'

src/sempy_labs/admin/_basic_functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ def list_capacities(
126126
capacity: Optional[str | UUID] = None,
127127
) -> pd.DataFrame:
128128
"""
129-
Shows the a list of capacities and their properties. This function is the admin version.
129+
Shows the a list of capacities and their properties.
130130
131131
This is a wrapper function for the following API: `Admin - Get Capacities As Admin <https://learn.microsoft.com/rest/api/power-bi/admin/get-capacities-as-admin>`_.
132132
@@ -138,7 +138,7 @@ def list_capacities(
138138
Returns
139139
-------
140140
pandas.DataFrame
141-
A pandas dataframe showing the capacities and their properties
141+
A pandas dataframe showing the capacities and their properties.
142142
"""
143143
client = fabric.FabricRestClient()
144144

0 commit comments

Comments
 (0)