Skip to content

Dash

Bases: ReportOutput

Implementation of Report Output interface that can create an interactive report document based on Dash framework.

Source code in smartreport/engine/outputs/dash_document.py
  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
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
class DashReportOutput(ReportOutput):
    """Implementation of Report Output interface that can create
    an interactive report document based on Dash framework.
    """

    export_extension = "gz"
    is_interactive = True
    WORKING_PAGE_WIDTH = 1440
    SPECIAL_CELLS = ("None",)
    CHARTS_COLUMNS = {1: "twelve", 2: "six", 3: "four", 4: "three", 6: "two", 12: "one"}

    def __init__(self, initial_document: Optional[List] = None):
        # Full document stores the whole list of components added to the Dash document
        # it is used when exporting the report
        self._initial_document = initial_document
        self.full_document: List = (
            self._initial_document if self._initial_document is not None else self._create_initial_document()
        )
        # `add` methods are always adding components to the `self.document` object
        # most of the time it is pointing to the `self.full_document`, but we play with it when working with columns
        self.document = self.full_document
        self.current_column_width = 1.0
        self.current_number_of_columns = 1
        self.global_ids = defaultdict(int)

    def _create_initial_document(self) -> List:
        """Returns a set of components that can be used as an initial document for Dash Report.
        It contains a right aligned Div with the ABB logo picture.

        Returns:
            List of components to be used as an initial Dash Report document.

        """
        elements = [
            html.Div(
                className="flex-right",
                children=[html.Div(html.Img(src=image_to_src(ReportConstants.ABB_LOGO_IMAGE_PATH)))],
            ),
        ]

        layout = html.Div(id=ReportConstants.ABB_LOGO_IMAGE_ID, children=elements)
        return [layout]

    def add_heading(self, text: str, level: int, **kwargs) -> None:
        """Adds heading to the report document.

        Heading is represented as HTML H1, H2, H3, H4, H5 or H6 tag.
        Heading text is defined by 'text' argument and level is defined by 'level'.
        When not supported level is provided the H1 tag is used.

        Heading are also used for building interactive Table of Content.
        By default, all headings are included in the Table of Content up to the ToC depth level.
        Heading can be explicitly excluded from ToC by providing `include_in_toc=False` parameter.

        Args:
          text: Text of the heading
          level: Level of the heading. Integer from range 1 to 6

        Keyword Args:
          include_in_toc (bool): Flag that defines if given heading should be included
            in Tabel of Content. (default: `True`)

        """
        include_in_toc = kwargs.get("include_in_toc", True)
        # Define the unique identifier of Heading HTML element
        _index = self.global_ids["heading"]
        _id = {"type": DashElementsId.TOC_HEADING, "index": _index, "level": level}
        self.global_ids["heading"] += 1

        # Try to find appropriate HTML tag, if not found use H1
        _html_header = getattr(html, f"H{level}", html.H1)
        header_element = _html_header(text, id=_id) if include_in_toc else _html_header(text)
        # Add it to the document
        self.document.append(header_element)
        log.debug(f"Heading{level}: '{text}' added.")
        return None

    def add_page_break(self, **kwargs) -> None:
        """Adds a page break to the report document.

        It is represented as an empty Div element with a PAGE_BREAK class. Even though it's not visible
        in the Dash Report, it will preserve the information about the page break that can be used
        when converting Dash document to Word document.

        """
        self.document.append(html.Div(className=DashComponentClass.PAGE_BREAK))
        log.debug("Page Break added.")
        return None

    def add_hyperlink(self, text: str, url: str, **kwargs) -> None:
        """Adds hyperlink to the report document.

        Hyperlink object can link the report reader to external url or to the another section of the report.

        Args:
          text: Text of the hyperlink.
          url: URL of the hyperlink.

        Keyword Args:
            target (str): Target of the hyperlink. It follows HTML convention: `_blank`, `_self`, `_parent`, `_top`.
                Default: `_blank`
            wrap_in_new_paragraph (bool): If true then the hyperlink is wrapped in <p> tags.
                Otherwise, it will be added alone. Default: `True`

        """
        target = kwargs.get("target", "_blank")
        wrap_in_new_paragraph = kwargs.get("wrap_in_new_paragraph", True)
        element = html.A(href=url, children=[text], target=target)
        if wrap_in_new_paragraph:
            element = html.P(children=[element])

        self.document.append(element)
        log.debug(f"Hyperlink ({url})[{text}] added.")
        return None

    def add_text(
        self, text: str, style: TextStyle = TextStyle.DEFAULT, dictionary: Optional[Dict] = None, **kwargs
    ) -> None:
        """Adds text paragraph to the report document.

        `text` is a string and `style` is an identifier of style that is applied to it.
        For Dash report, style's value it's a name of a class defined in CSS (see abb_dash.css file).

        This method supports a subset of Markdown formatting in provided text string.
        Following elements are supported:

        * Empty line adds a new paragraph.

        * Hashes (#) at the beginning of the line add heading.

        * Pattern `[TEXT](URL)` adds a hyperlink with TEXT that points to URL.

        * Any occurrence of `{{VARIABLE}}` will be replaced by the string that comes from
        provided `dictionary` keyword argument.

        Refer to [interface documentation](00_overview.md) for more details.

        Args:
          text: Input text
          style: Identifier of a text style that will be applied to the text
          dictionary: Dictionary that would be used to replace Variables located in input text

        """
        dictionary = dictionary if isinstance(dictionary, dict) else {}

        text_type = kwargs.pop("dash_type", DashElementsId.TEXT_PREFIX)
        text_index = kwargs.pop("dash_index", None)
        group_id = kwargs.pop("group_id", "")

        for line in text.split("\n"):
            # Extract the heading line
            heading_text, heading_level = get_heading_from_line(line)
            if heading_level is not None:
                self.add_heading(text=heading_text, level=heading_level)
                continue
            # Replace the variables
            new_line = replace_variables_in_line(line, dictionary)

            # Search for hyperlinks
            elements = []
            for sub_line in split_line_on_hyperlinks(line=new_line):
                if sub_line.get("type") == "text" and sub_line.get("text"):
                    _span = html.Span(sub_line.get("text"))
                    elements.append(_span)
                elif sub_line.get("type") == "link" and sub_line.get("text") and sub_line.get("url"):
                    _a = html.A(href=sub_line.get("url"), children=[sub_line.get("text")], target="_blank")
                    elements.append(_a)

            _index = text_index if text_index is not None else self.global_ids["text"]
            _id = {"type": text_type, "index": _index, "group_id": group_id}
            paragraph = html.P(id=_id, children=elements, className=style.value)
            self.global_ids["text"] += 1
            self.document.append(paragraph)
            # If line is not empty, log it in the trimmed version
            if new_line:
                log.debug(f'Paragraph "{trim_text(new_line, max_length=40)}" added.')
        return None

    def add_toc(self, **kwargs) -> None:
        """Adds automatic Table of Content placeholder to the report document.

        Dash Report renders interactive Table of Content with support of Dash Callbacks.

        When the Dash document is loaded into report viewer, `update_table_of_content`
        callback in called. It extracts all headings up to the `depth` level from the document,
        and builds list of divs with links to each section out of it.
        Refer to the callback docstring for the details.

        This method adds a Div placeholder where the output of this callback is added.
        Additionally, it stores all ToC parameters in dcc.Store object, so it can be used when
        doing Dash to Word conversion later.

        Parameters `heading_text`, `heading_level`, and `page_break` are kept only to support
        backward compatibility when converting Dash to Word document.
        However, they are not used by default in new documents.

        Keyword Args:
            depth (int): Depth of the ToC. It defines the maximum heading level included in the ToC. (default: `2`)
            heading_text (str): If provided, the ToC will be preceded with the heading component.
            heading_level (int): Level of the preceding heading component (default: `1`)
            page_break (bool): If provided, ToC will be followed by a page break (default: `False`)

        """
        depth = kwargs.get("depth", 2)
        heading_text = kwargs.get("heading_text", "")
        heading_level = kwargs.get("heading_level", 1)
        page_break = kwargs.get("page_break", False)

        if heading_text and heading_level:
            self.add_heading(text=heading_text, level=heading_level, include_in_toc=False)

        # Prepare an object that stores information about ToC parameters
        params_element = dcc.Store(id=DashElementsId.TOC_PARAMS, data=kwargs)
        # ToC Div will be populated by the `update_table_of_content` callback
        # but before that happens we add a text placeholder
        txt_placeholder = "Please wait for the Table of Content to load."
        toc_structure = html.Div(
            className=DashComponentClass.TOC,
            children=[params_element, html.Div(id=DashElementsId.TOC_DIV, children=txt_placeholder)],
        )
        self.document.append(toc_structure)
        log.debug(f"ToC(depth={depth}) added.")

        if page_break:
            self.add_page_break()
        return None

    def add_table(
        self,
        table_data: TableData,
        style: TableStyle = TableStyle.DEFAULT,
        column_widths: Sequence[float] = None,
        **kwargs,
    ) -> None:
        """Adds table to the report document.

        Input data should be provided as sequence of rows, where row is a sequence of cells
        and cells is either as simple string or a TableCell object that carries extra formatting information.
        Only 2-D structures with constant number of rows and columns are allowed.

        Merging can be achieved by using a special cell values `TableCell.MERGE_LEFT` and `TableCell.MERGE_ABOVE` that
        are located in .components module.

        Implementation details:

        * Cell merging is NOT implemented. The `TableCell.MERGE_ABOVE` is faked by removing the line between cells.
          However, the merge cells are preserved so the merging is applied when report is converted to Word Document.

        * This method ignores bold, italic and centered properties of TableCells.

        * This method uses dash conditional formatting that might be cryptic at first encounter, read more
          [here](https://dash.plotly.com/datatable/conditional-formatting)

        Args:
          table_data: Sequence rows, where row is a sequence of cells. Cell might be a simple string
            or a TableCell object, that also carries the information about cell formatting.
          style: TableStyle enum, Identifier of a style that will be applied to created table
          column_widths: Sequence of column widths as percents. They should sum up to 100%. If not provided,
            each implementation will figure out the best widths based on provided data.

        Keyword Args:
          use_markdown (bool): If true, Allow for markdown styling in table cells (default: `False`)
          sort_action (str): Sort action for table (default: `native`)
          sort_mode (str): Sort mode for table (default: `single`)
          filter_action (str): Filter action for table (default: `none`)
          filter_query (str): Filter query for table (default: '')
          dropdown_columns (dict): Dictionary of columns that should have dropdowns (default: `{}`)
          reset_button (bool): Show table reset button (default: `False`)
          store_data (bool): Store original table data in hidden field (default: `False`)
          row_deletable (bool): Allow deleting table rows (default: `False`)
          editable (bool): Allow editing table cells (default: `False`)
          cell_selectable (bool): Make table cell selectable / clickable (default: `True`)
          extra_styles (list): List of extra styles to be applied to table
          include_cell_styles (bool): Include cell styles in table styling (default: `True`)
          page_size (int): Table page size (default: `50`)

        """

        table_type: str = kwargs.pop("dash_type", DashElementsId.TABLE_PREFIX)
        table_index: int = kwargs.pop("dash_index", self.global_ids["table"])
        group_id: str = kwargs.get("group_id", f"{table_type}-{table_index}")
        use_markdown = kwargs.get("use_markdown", False)
        sort_action = kwargs.get("sort_action", "native")
        sort_mode = kwargs.get("sort_mode", "single")
        filter_action = kwargs.get("filter_action", "none")
        filter_query = kwargs.get("filter_query", "")
        dropdown_columns = kwargs.get("dropdown_columns", {})
        reset_button = kwargs.get("reset_table", False)
        store_data = kwargs.get("store_data", False)
        row_deletable = kwargs.get("row_deletable", False)
        editable = kwargs.get("editable", False)
        cell_selectable = kwargs.get("cell_selectable", True)
        extra_styles = kwargs.get("extra_styles", [])
        include_cell_styles = kwargs.get("include_cell_styles", True)
        page_size = kwargs.get("page_size", 50)
        no_of_row_headers = kwargs.get("no_of_row_headers", 0)
        markdown_options = kwargs.get("markdown_options", None)

        _id = {"type": table_type, "index": table_index, "group_id": group_id}
        _presentation = "markdown" if use_markdown is True else "input"
        _styles = extra_styles[:]

        # In Dash Report setting font size has currently no effect - default font size works and looks fine
        # we still need to preserve info about it for conversion to word

        if isinstance(style, TableStyle):
            word_table_style = style.value
        else:
            log.info(f"Unsupported type of table style: {type(style)}, defaulting to {TableStyle.DEFAULT}")
            word_table_style = TableStyle.DEFAULT

        # Check if table size is correct
        t_rows, t_cols = get_table_size(table_data)
        if t_rows is None or t_cols is None:
            return None

        # Parse column widths
        parsed_column_widths = self._parse_column_widths(widths=column_widths, no_of_columns=t_cols)
        # Initialize columns
        multi_title = False
        columns = []
        for name in table_data[0]:
            if isinstance(name, TableCell):
                name = name.text
                if isinstance(name, list):
                    columns.append(name)
                    multi_title = True
                else:
                    columns.append(str(name) if str(name) not in self.SPECIAL_CELLS else "")
            else:
                columns.append(str(name) if str(name) not in self.SPECIAL_CELLS else "")
        # Check if column names are empty, if so, replace them with empty string
        _column_data = [
            {
                "name": c,
                "id": clear_str(f"{c}{i}"),
                "presentation": _presentation,
            }
            for i, c in enumerate(columns)
        ]

        # Extracting cell text and formatting
        _rows, _cell_styles = self._extract_cell_data(table_data=table_data, column_data=_column_data)
        if include_cell_styles:
            _styles.extend(_cell_styles)
        # Additional Row Styling
        # Uses dash conditional formatting, read docstring
        _style_for_bottom_border = {"if": {"row_index": t_rows - 2}, "border_bottom": "1px solid black"}
        _header_style = {
            "backgroundColor": "white",
            "fontWeight": "bold",
            "border_top": "2px solid black",
            "border_bottom": "1px solid black",
        }
        # This will wrap too long texts in cells
        _data_style = {
            "whiteSpace": "pre-line",
            "height": "auto",
            "margin-left": 30,
            "textAlign": "left",
            # word_table_style size setting will have no effect in dash document
            # (word_table_style property doesn't exist in css)
            # but we will preserve this information for convert to word stage
            "word_table_style": word_table_style,
            # Specifies the no of header rows repeated on each page
            # for multi-page tables
            "no_of_row_headers": no_of_row_headers,
        }

        # Uses dash conditional formatting, read docstring
        for col_data, col_width in zip(_column_data, parsed_column_widths):
            if col_width is not None:
                column_style = {"if": {"column_id": col_data.get("id")}, "width": f"{col_width:.0f}%"}
                _styles.append(column_style)
        _styles.append(_style_for_bottom_border)

        # Some tables might require filtering by column value
        # The filtering logic is defined in Dash callbacks,
        # and below we add dropdown for each column that we want to filter by
        if dropdown_columns:
            self._add_dropdown_columns(
                dropdown_columns=dropdown_columns,
                rows=_rows,
                table_index=table_index,
                cd=_column_data,
                group_id=group_id,
            )
        # If filtering is used then the reset button is usually needed as well
        # To restore the table to its original state
        # The original data is stored in the store_element that is also a part of the report.
        if reset_button:
            self._add_reset_button(table_index=table_index, group_id=group_id)
        if store_data:
            store_element = dcc.Store(
                id={
                    "type": DashElementsId.DATA_STORAGE_PREFIX,
                    "index": table_index,
                    "group_id": group_id,
                },
                data=_rows,
            )
            self.document.append(store_element)

        # Finally, DataTable object is initialized with all custom styling defined above
        table_element = DataTable(
            columns=_column_data,
            id=_id,
            cell_selectable=cell_selectable,
            row_deletable=row_deletable,
            style_as_list_view=True,
            sort_action=sort_action,
            sort_mode=sort_mode,
            filter_action=filter_action,
            filter_query=filter_query,
            style_header=_header_style,
            style_data_conditional=_styles,
            style_cell=_data_style,
            data=_rows,
            editable=editable,
            page_size=page_size,
            merge_duplicate_headers=multi_title,
            markdown_options=markdown_options,
        )
        # dcc.Loading shows 'rotating wheel of waiting' in place of Table, when table is rendered
        self.document.append(dcc.Loading(table_element))
        self.global_ids["table"] += 1
        log.debug("Table added.")
        return None

    def add_table_legend(self, legend_cells: Sequence[LegendCell], **kwargs) -> None:
        """Adds a color-based legend table to the report document.

        It expects a sequence of LegendCell objects as an input.
        Each LegendCell object defines a title, color and description. Legend can be used to explain
        color encoding of a table. Widths of legend cells are automatically calculated. Based on the required space,
        legend is adjusted to the right or takes all the row space.

        Args:
          legend_cells: Sequence of LegendCell objects.

        """
        if not legend_cells:
            return None

        table_type: str = kwargs.pop("dash_type", DashElementsId.LEGEND_PREFIX)
        table_index: int = kwargs.pop("dash_index", self.global_ids["table_legend"])
        group_id: str = kwargs.get("group_id", f"{table_type}-{table_index}")
        size_multiplier: float = kwargs.get("size_multiplier", 1.0)
        add_top_margin: bool = kwargs.get("add_top_margin", False)

        _id = {"type": table_type, "index": table_index, "group_id": group_id}
        # first column is used to align legend to right side of the page
        _first_column_id = "first_column"
        # add color cells
        color_cells = [
            LegendCell(title="", color=cell.color, gradient_colors=cell.gradient_colors) for cell in legend_cells
        ]
        color_cell_width = 30 * size_multiplier
        longest_title_len = max([len(cell.title) for cell in legend_cells])
        pixels_per_char = 10 * size_multiplier
        computed_legend_cell_width = longest_title_len * pixels_per_char * size_multiplier
        first_column_width = self.WORKING_PAGE_WIDTH - (computed_legend_cell_width + color_cell_width) * len(
            legend_cells
        )

        first_column_width_css = f"{first_column_width * size_multiplier}px"
        color_cell_width_css = f"{color_cell_width}px"

        # this is for making the legend look nice and airy: little space after the text before next color
        def get_cell_length(title):
            title_length = len(title)
            if title_length < 13:
                return (title_length + 4) * pixels_per_char
            return title_length * pixels_per_char

        # add color cells to their places
        _legend_cells: Sequence[Any] = [None] * (len(legend_cells) + len(color_cells))
        _legend_cells[::2] = color_cells
        _legend_cells[1::2] = legend_cells
        legend_cells = _legend_cells

        legend_element = DataTable(
            id=_id,
            columns=[
                {"id": _first_column_id, "name": ""},
                *[
                    {"id": cell.title, "name": cell.title} if cell.title else {"id": cell.color, "name": ""}
                    for cell in legend_cells
                ],
            ],
            style_table={
                "marginBottom": f"{30 * size_multiplier}px",
                "fontSize": f"{17 * size_multiplier}px",
                "marginTop": f"{30 * size_multiplier if add_top_margin else 0}px",
            },
            style_header={
                "textAlign": "left",
                "border_top": "0",
                "border_bottom": "0",
                "padding": "5px",
            },
            style_header_conditional=[
                {
                    "if": {"column_id": _first_column_id},
                    "backgroundColor": ABBColors.WHITE.value,
                    "width": first_column_width_css,
                },
                *[
                    {
                        "if": {"column_id": cell.title},
                        "backgroundColor": ABBColors.WHITE.value,
                        "width": f"{get_cell_length(cell.title)}px",
                    }
                    for cell in legend_cells
                ],
                *[
                    {
                        "if": {"column_id": cell.color},
                        "backgroundColor": cell.color,
                        "background": f"linear-gradient(90deg, {', '.join(cell.gradient_colors)})",
                        "width": color_cell_width_css,
                    }
                    for cell in legend_cells
                ],
            ],
            tooltip_header={cell.title: cell.description for cell in legend_cells},
            tooltip_delay=0,
            tooltip_duration=None,
        )
        # dcc.Loading shows 'rotating wheel of waiting' in place of table, when table is rendered
        self.document.append(dcc.Loading(legend_element))
        self.global_ids["table_legend"] += 1
        log.debug("Table legend added.")
        return None

    def add_pictures(
        self, pictures: Sequence[Union[Path, str, bytes]], widths: Sequence[float] = None, **kwargs
    ) -> None:
        """Adds a sequence of static pictures to a single row in the report document.

        Each picture should be provided either as a sequence of bytes or as a path to the picture file.

        Args:
          pictures: Sequence of picture data provided either as a bytes sequence or picture file path.
          widths: Optional sequence of pictures widths. They should sum up to 100%. If not provided,
            each implementation will figure out the best widths based on provided data.

        """

        if not pictures:
            return None

        default_width = self.WORKING_PAGE_WIDTH / len(pictures)
        widths = widths if widths is not None else [default_width] * len(pictures)

        for picture, width in zip(pictures, widths):
            picture_element = self._prepare_single_picture(picture_path=picture, width=width, **kwargs)
            self.document.append(picture_element)
            self.global_ids[DashElementsId.PICTURE_PREFIX] += 1
        return None

    def add_figures(self, figures: Sequence[Figure], widths: Optional[Sequence[float]] = None, **kwargs) -> None:
        """Adds a sequence of Plotly figures to a single row in the report document.

        Dash reports natively supports Plotly figures, so they can be simply added to the dash document
        as a Graph object.

        Args:
          figures: Sequence of Plotly figure objects data provided either as a bytes sequence or string.
          widths: Optional sequence of pictures widths. They should sum up to 100%. If not provided,
        each implementation will figure out the best widths based on provided data.

        Keyword Args:
          plot_title (str): Plot title. It will be added as a heading just before the row with figures if provided.
          include_comments_box (bool): If true, the row with figures will be followed with a text area where
            report reader can add the comments. (default: `True`)
          add_loading (bool): If true, the figure row will be wrapped in loading spinner
            for the report initial loading time. (default `True`)

        """
        plot_title = kwargs.pop("plot_title", "")
        include_comments_box = kwargs.pop("include_comments_box", True)
        add_loading = kwargs.pop("add_loading", True)

        # Calculate widths of provided figures based on document page width
        widths_px = [figure.layout.width if figure.layout.width else self.WORKING_PAGE_WIDTH for figure in figures]
        total_width = sum(widths_px)
        widths = widths if widths is not None else [100.0 * w / total_width for w in widths_px]

        # Add a heading with plot title, if provided
        if plot_title:
            self.add_text(text=plot_title, style=TextStyle.PLOT_TITLE)

        # Build list of Dash Graph objects based on provided sequence of figures
        graph_elements = []
        for figure, width in zip(figures, widths):
            graph_object = self._prepare_single_figure(figure=figure, width=width, **kwargs)
            self.global_ids["figure"] += 1
            graph_elements.append(graph_object)

        # Add row with figures, to the document
        if graph_elements:
            div_with_figures = html.Div(children=graph_elements, className=DashComponentClass.FIGURE_ROW)
            if add_loading:
                div_with_figures = dcc.Loading(children=div_with_figures)
            self.document.append(div_with_figures)

        if include_comments_box:
            self.add_comment_box()
        return None

    @contextmanager
    def column_section(self, no_of_columns: int = 2) -> Generator[Callable[[], None], None, None]:
        """Creates a context in which the Report Output works in column layout.

        Number of columns is defined 'no_of_columns' parameter.
        You can add components to the document the same way as you would do for a standard (single column) layout,
        but within the context you hove a `next_column()` function available that can move you to the next column.
        When the context is finished the basic layout is restored (single column).

        Example of usage:
        ```python
        ro = DashReportOutput()
        with ro.column_section(3) as nc:  # 'nc' is the name of the function that can jump to next column
            # We start from the first column (on the left)
            # work with ReportOutput the same way as usual
            ro.add_text("Text in first column")
            nc()  # move the context to the next column (second)
            ro.add_heading("Heading in the middle", level=2)
            ro.add_text("Text in second column")
            nc()  # move the context to the next column (third, last)
            ro.add_text("Text in third column")
            nc()  # there were only three columns in this context, so this will do nothing
        ```

        Args:
          no_of_columns: Number of columns for this column section

        Returns:
          Function that moves the context to the next column

        """

        column_txt = self.CHARTS_COLUMNS.get(no_of_columns, "twelve")
        # 'full_document' holds all components of the Dash document
        # we will add a Div that will hold the multi-column layout
        self.full_document.append(html.Div(className=DashComponentClass.COLUMNS, children=[]))
        _row_with_columns = self.full_document[-1].children

        # First Column
        # We add the Div that will hold the content of the first column
        _row_with_columns.append(html.Div(className=f" {column_txt} {DashComponentClass.COLUMNS}", children=[]))
        # 'self.document' attribute is by default pointing to the full_document
        # Here we are pointing it to the newly created Div that will hold the content of the current column,
        # so we can work with the report output as we would be in the standard layout, and the content will be
        # added to current column
        self.document = _row_with_columns[-1].children
        # We update the current column width that controls the size of figures and pictures added to the document
        self.current_column_width = 1.0 / no_of_columns
        self.current_number_of_columns = no_of_columns

        log.debug(f"Working in column: 1 / {no_of_columns}")

        def move_to_next_column():
            """This function can jump to the next column within the context."""
            nonlocal _row_with_columns
            nonlocal self
            _column_id = len(_row_with_columns)

            # Check if we still have columns available to jump to
            if _column_id >= no_of_columns:
                log.warning(f"There is no next column to move to. ({_column_id} / {no_of_columns})")
                return None
            # Add a next Div container to row with columns and point the 'self.document' to it
            _row_with_columns.append(html.Div(className=f"{column_txt} {DashComponentClass.COLUMNS}", children=[]))
            self.document = _row_with_columns[-1].children
            _column_id = len(_row_with_columns)
            log.debug(f"Working in column: {_column_id} / {no_of_columns}")

        try:
            yield move_to_next_column
        finally:
            # Clean up the layout after the context is exited
            # Restore the column width to 1, since we have a single column
            # and point the 'self.document' back to 'self.full_document'
            self.current_column_width = 1.0
            self.current_number_of_columns = 1
            self.document = self.full_document

    def add_comment_box(self, **kwargs):
        """Adds an interactive field to the report document where the report readers can add theirs comments.

        It can only be implemented for the interactive report output types, but the comment text added by the reader
        can be saved and seen in the static reports after the conversion process.

        Keyword Args:
            placeholder (str): Placeholder text. (default: `Please put your comments here`)
            height (int): Height of text area. (default: `100`)
            initial_text (str): Initial text in the box. (default: "")

        """
        comment_index = kwargs.get("dash_index", self.global_ids["comment"])
        placeholder: str = kwargs.get("placeholder", "Please put your comments here")
        height: int = kwargs.get("height", 100)
        initial_text: str = kwargs.get("initial_text", "")
        _id = {"type": DashElementsId.COMMENT_PREFIX, "index": comment_index}
        box = html.Div(
            className="u-full-width",
            children=[
                dcc.Textarea(
                    className="u-full-width",
                    id=_id,
                    value=initial_text,
                    placeholder=placeholder,
                    style={"height": height},
                )
            ],
        )
        self.global_ids["comment"] += 1
        self.document.append(box)

    def add_audio_player(self, audio_data: bytes, **kwargs) -> None:
        """Adds an audio player to the report document.

        It takes any sequence of bytes that can be interpreted as sound
        wave, and creates HTML Audio element with based on this data.

        Args:
          audio_data: Sequence of bytes that can be interpreted as a sound wave.

        """
        # Convert bytes to Base64 encoded string.
        b64wave = base64.b64encode(audio_data).decode("utf-8")
        # Create an audio player and initialize it with WAVE data
        player = html.Audio(loop=True, controls=True, src=f"data:audio/x-wav;base64,{b64wave}")
        self.document.append(player)
        return None

    def add_slider(self, initial_value: float, button_text: str, **kwargs) -> None:
        """Adds a button to the report document that opens an extra window with a slider that allow the report reader
        to adjust some values that affect the report content.

        It can only be implemented for the interactive report
        output types, but the results of the content modification caused by the slider can be saved,
        and therefore seen in the static report after the conversion process.

        Currently, only Dash Report Output implements it.

        Args:
          initial_value: Initial value of the slider
          button_text: Text on the button that opens the slider window

        Keyword Args:
          min_value (float): Minimum value of the slider (default: `0.0`)
          max_value (float): Minimum value of the slider (default: `100.0`)
          resolution (float): Resolution of the slider (default: `0.1`)
          no_of_visible_steps (int): Number of main ticks on the slider (default: `10`)
          unit (str): Unit of values on the slider
          title (str): Title visible in the slider window
          group_id (str): Optional ID of the group that this component should belong to
          hide_slider_button (bool): if True hides button, essentially disabling it (default: `False`)

        """
        min_value: float = kwargs.get("min_value", 0.0)
        max_value: float = kwargs.get("max_value", 60.0)
        resolution: float = kwargs.get("resolution", 0.1)
        no_of_visible_steps: int = kwargs.get("no_of_visible_steps", 10)
        unit = kwargs.get("unit", "")
        title = kwargs.get("title")
        group_id = kwargs.get("group_id")
        hide_slider_button = kwargs.get("hide_slider_button", False)
        # Prepare IDs
        _text_id = {"type": DashElementsId.GROUP_SLIDER_TEXT, "group_id": group_id}
        _div_id = {"type": DashElementsId.GROUP_SLIDER_DIV, "group_id": group_id}
        _button_id = {"type": DashElementsId.GROUP_SLIDER_BUTTON, "group_id": group_id}
        _close_id = {"type": DashElementsId.GROUP_SLIDER_CLOSE, "group_id": group_id}
        _slider_id = {"type": DashElementsId.GROUP_SLIDER, "group_id": group_id}

        # Configure Slider component
        resolution_array = np.arange(min_value + resolution, max_value + resolution, resolution)
        steps_array = resolution_array
        steps_no = len(steps_array)
        label_step = int(steps_no / no_of_visible_steps)
        value = steps_array[nearest_point(steps_array, initial_value)]
        marks = {step: (f"{step:.1f} [{unit}]" if i % label_step == 0 else "") for i, step in enumerate(steps_array)}
        dash_slider = dcc.Slider(
            id=_slider_id,
            min=min_value,
            max=max_value,
            value=value,
            marks=marks,
            step=None,
            included=False,
            updatemode="drag",
        )
        # Configure slider Button
        slider_button = html.Div(
            children=[html.Button(button_text, id=_button_id, n_clicks=0), html.Br(), html.Br(), html.Br()],
            className="slider-buttons",
            hidden=hide_slider_button,
        )
        # Create other components: Close button, text box for current slider value and hidden storage object
        close_button = html.Button("X", id=_close_id, n_clicks=0, className="slider-close-button")
        text_box = html.P(children=[html.Span(initial_value, id=_text_id), html.Span(unit)])
        storage = html.Pre(value, id={"type": DashElementsId.GROUP_SLIDER_STORAGE, "group_id": group_id}, hidden=True)
        # Create hidden div that collects all slider components
        slider_div = html.Div(children=[], id=_div_id, className="slider-container", hidden=True)
        if title:
            slider_div.children.append(html.H2(title))
        slider_div.children.extend([text_box, dash_slider, storage, close_button])

        self.document.append(slider_button)
        self.document.append(slider_div)
        log.debug(f"Slider added to the document (group_id={group_id}).")
        return None

    def export(self, filepath: Union[str, Path], **kwargs) -> None:
        """
        Exports a report document to a file path provided in the `filepath` argument.

        Args:
          filepath: Path of the exported document file.

        Keyword Args:
            format (str): Format of the export file. Supported formats: `gz`, `json`. Default: `gz`
            encoding (str): Data encoding. Default: `utf-8`
            compression_level (int): Compression level. Works only if exporting to `gz` format. Default: `9`

        Note:
            Even if you provide an extension in the filepath it will be overwritten based on `format` argument.

        """
        _format = kwargs.get("format", self.export_extension)

        filepath = Path(filepath).with_suffix(f".{_format}")
        bytes_data = self.to_bytes(**kwargs)
        try:
            filepath.write_bytes(bytes_data)
            log.debug(f"Report based on {self.__class__.__name__} exported to {filepath}")
        except PermissionError:
            new_filepath = filepath.with_stem(f"{filepath.stem}_1")
            self.export(filepath=new_filepath, **kwargs)

    def to_bytes(self, **kwargs) -> bytes:
        """
        Converts content of the report document to bytes.

        Keyword Args:
            format (str): Format of the export file. Supported formats: `gz`, `json`. (default: `gz`)
            encoding (str): Data encoding. Default: `utf-8`
            compression_level (int): Compression level. Works only with `gz` format. Default: `9`

        Returns:
            Bytes that contains the binary content of the report document.
        """
        _format = kwargs.get("format", "gz")
        encoding = kwargs.get("encoding", "utf-8")
        compression_level = kwargs.get("compression_level", 9)
        metadata = {"output_orientation": self.OUTPUT_ORIENTATION.value}
        document_with_metadata = {
            "metadata": metadata,
            "document": self.full_document,
        }
        data = json.dumps(document_with_metadata, cls=plotly.utils.PlotlyJSONEncoder)

        if _format == "gz":
            data = gzip.compress(data.encode(encoding), compresslevel=compression_level)
            return data

        bytes_data = bytes(data, encoding=encoding)
        return bytes_data

    def reset(self) -> None:
        """Resets the document to the initial state"""

        self.full_document: List = (
            self._initial_document if self._initial_document is not None else self._create_initial_document()
        )
        # `add` methods are always adding components to the `self.document` object
        # most of the time it is pointing to the `self.full_document`, but we play with it when working with columns
        self.document = self.full_document

    @staticmethod
    def read_layout_from_file(path: Union[str, Path], **kwargs) -> Optional[Tuple[List, Dict]]:
        """
        Reads Dash Report layout from a file.
        It supports default `gz` format as well as `json` format.

        Args:
            path: Path to file that contains the exported document.

        Keyword Args:
            encoding: Expected file encoding. Default: `utf-8`

        Returns:
            Dash document layout.
        """
        metadata = {}
        encoding = kwargs.get("encoding", "utf-8")
        file_extension = os.path.splitext(path)[1]
        if file_extension == ".gz":
            with gzip.open(path, "r") as f:
                data = f.read().decode(encoding=encoding)
        elif file_extension == ".json":
            with open(path, "r", encoding=encoding) as f:
                data = f.read()
        else:
            raise ValueError(f"Unsupported file extension: {path}. Only: .gz and .json are supported")
        data_content = json.loads(data)
        if isinstance(data_content, dict):
            metadata = data_content.get("metadata", {})
            data_content = data_content.get("document", [])

        return data_content, metadata

    def _add_dropdown_columns(
        self,
        dropdown_columns: Dict,
        rows: List[Dict[Optional[str], str]],
        table_index: int,
        cd: List[Dict[str, Optional[str]]],
        group_id: str,
    ):
        """Adds dropdown columns to existing table.

        Dropdown columns are a nice dash feature that allow interactive filtering of data in the table by column values.
        See example of usage in Drive Asset Report -> Events Table

        """
        list_of_dropdown = []
        col_ids = []
        for col_dict in cd:
            if col_dict["name"] in dropdown_columns.keys():
                col_ids.append(col_dict["id"])

        no_clicks = 0
        df = pd.DataFrame(rows)
        for i, (_col, (_col_name, _initial_values)) in enumerate(zip(col_ids, dropdown_columns.items())):
            unique_values = df[_col].unique()
            intersec_values = set(_initial_values).intersection(unique_values)
            if intersec_values:
                no_clicks = 1
            list_of_dropdown.append(
                dcc.Dropdown(
                    id={"type": DashElementsId.FILTER_DROPDOWN_PREFIX, "group_id": group_id, "index": i},
                    options=[{"label": _val, "value": _val, "title": _col} for _val in unique_values],
                    value=[_val for _val in intersec_values],
                    multi=True,
                    placeholder=f"Filter by {_col_name}",
                )
            )
        list_of_dropdown.append(
            html.Button(
                "Apply Filters",
                id={"type": DashElementsId.FILTER_BUTTON_PREFIX, "index": table_index, "group_id": group_id},
                n_clicks=no_clicks,
            )
        )
        list_of_dropdown += [html.Br()] * 3
        dropdown_element = html.Div(list_of_dropdown)
        self.document.append(dropdown_element)
        return None

    def _add_reset_button(self, table_index: int, group_id: str) -> None:
        """Adds button to reset interactive table filtering.

        Args:
          table_index: Index of a corresponding table
          group_id: Group ID of a corresponding table

        """
        reset_element = html.Div(
            [
                html.Button(
                    "Reset Table",
                    id={"type": DashElementsId.RESET_BUTTON_PREFIX, "index": table_index, "group_id": group_id},
                    n_clicks=0,
                ),
                html.Button(
                    "Undo",
                    id={"type": DashElementsId.UNDO_BUTTON_PREFIX, "index": table_index, "group_id": group_id},
                    n_clicks=0,
                ),
                html.Br(),
                html.Br(),
                html.Br(),
            ]
        )
        self.document.append(reset_element)
        return None

    def _extract_cell_style(
        self,
        cell: Union[str, TableCell],
        row_index: int,
        col_index: int,
        special_row: str,
        column_data: List[Dict[str, Optional[str]]],
    ) -> Dict[str, Union[str, Dict[str, str]]]:
        """Extracts cell styling and returns as a dictionary."""
        _cell_style = {}
        if cell == TableCell.MERGE_ABOVE:
            _cell_style.update({"border_top": "none"})
        # individual cell styles are derived from TableCell attributes
        # and transformed to CSS properties
        # cell.color -> backgroundColor   / As #RRGGBB string
        # cell.bold == True -> fontWeight: bold
        # cell.italic == True -> fontStyle: italic
        if isinstance(cell, TableCell):
            _cell_style = self._extract_table_cell_arguments(cell, _cell_style)

        if _cell_style:
            # Uses dash conditional formatting
            # check following link for more details
            # https://dash.plotly.com/datatable/conditional-formatting
            _cell_style.update(
                {
                    "if": {
                        "filter_query": f"{{{special_row}}} = {row_index}",
                        "column_id": f"{column_data[col_index].get('id')}",
                    },
                }
            )

        return _cell_style

    @staticmethod
    def _extract_table_cell_arguments(cell: Union[str, TableCell], _cell_style: Dict) -> Dict:
        if getattr(cell, "color", None):
            _cell_style.update({"backgroundColor": cell.color})
        if getattr(cell, "bold", False):
            _cell_style.update({"fontWeight": "bold"})
        if getattr(cell, "italic", False):
            _cell_style.update({"fontStyle": "italic"})
        if getattr(cell, "padding_left", 10):
            _cell_style.update({"paddingLeft": cell.padding_left})
        if getattr(cell, "white_space", None):
            _cell_style.update({"white-space": cell.white_space})
        if getattr(cell, "font_color", None):
            _cell_style.update({"color": cell.font_color})
        if getattr(cell, "font_size", None):
            _cell_style.update({"font-size": f"{cell.font_size}px"})
        if getattr(cell, "h_center", None):
            _cell_style.update({"textAlign": "center"})
        return _cell_style

    def _extract_cell_data(
        self, table_data: Sequence[Sequence[Union[str, TableCell]]], column_data: List[Dict[str, Optional[str]]]
    ):
        """Method extracts and returns cell texts and cell style formatting."""
        _special_row = "_row_id"

        _styles = []
        _rows = []
        for i, row in enumerate(table_data):
            new_row = {_special_row: str(i)}
            for j, cell in enumerate(row):
                # Styling of individual cell
                _cell_style = self._extract_cell_style(
                    cell=cell, row_index=i, col_index=j, special_row=_special_row, column_data=column_data
                )
                _styles.append(_cell_style)
                # Removing special cell values
                if not isinstance(cell, HeaderCell):
                    cell_string = str(cell) if str(cell) not in self.SPECIAL_CELLS else ""
                    cell_string = TableIcons.HTML_ICON if cell_string == TableIcons.DOCX_ICON else cell_string
                    # use float_val if it is available, otherwise use string value
                    # if cell is a TableCell object, it has float_val attribute
                    cell_string = cell.float_val if hasattr(cell, "float_val") and cell.float_val else cell_string
                    if isinstance(cell, Base64TableCell):
                        new_row[column_data[j].get("id")] = markdown.markdown(cell.value)

                    # Update data dictionary
                    else:
                        new_row[column_data[j].get("id")] = cell_string

            # We drop the text of header row, yet we had to go through the loop in order to extract header cell
            # formatting
            if i > 0:
                _rows.append(new_row)

        return _rows, _styles

    def _prepare_single_picture(self, picture_path: Union[Path, str], width: float, **kwargs) -> Optional[html.Img]:
        """Prepares a Dash HTML IMG object based on provided picture path"""
        picture_type: str = kwargs.get("dash_type", DashElementsId.PICTURE_PREFIX)
        picture_index = kwargs.get("dash_index", self.global_ids[DashElementsId.PICTURE_PREFIX])
        group_id: str = kwargs.get("group_id", f"{picture_type}-{picture_index}")
        _id = {
            "type": picture_type,
            "index": picture_index,
            "group_id": group_id,
        }
        _width_pct = f"{width / self.WORKING_PAGE_WIDTH * 100}%"

        if not Path(picture_path).exists():
            raise ValueError(f"Picture: {picture_path} not exists, please check the path.")

        picture_data = image_to_src(picture_path)
        if picture_data is None:
            log.warning(f"Unable to add picture: {picture_path}")
            return None
        picture_element = html.Img(src=picture_data, width=_width_pct, id=_id)
        log.debug(f"Picture successfully added: {picture_path}")
        return picture_element

    def _prepare_single_figure(self, figure: Figure, width: float, **kwargs) -> dcc.Graph:
        """Prepares a Dash Graph object based on provided Plotly figure"""
        config = kwargs.get("config", DEFAULT_CONFIG)
        plot_type = kwargs.get("dash_type", DashElementsId.FIGURE_PREFIX)
        storage_type = kwargs.get("storage_type", f"{DashElementsId.DATA_STORAGE_PREFIX}-{plot_type}")
        plot_index = kwargs.get("dash_index", self.global_ids["figure"])
        group_id = kwargs.get("group_id", "")
        add_data = kwargs.get("add_data", {})

        _id = {"type": plot_type, "index": plot_index, "group_id": group_id}

        relative_width = width * self.current_column_width
        figure = self.rescale_figure_size(figure, scale=relative_width / 100.0)

        _classes = [
            DashComponentClass.NON_BREAKABLE,
            DashComponentClass.COLUMNS,
            f"{DashComponentClass.COLUMNS_NUMBER_PREFIX}{self.current_number_of_columns}",
        ]

        graph = dcc.Graph(
            figure=figure,
            config=config,
            className=" ".join(_classes),
            id=_id,
            style=dict(width=f"{relative_width:.1f}%"),
        )
        _title = getattr(figure.layout.title, "text", "NO_TITLE")
        log.debug(f"Figure '{_title}' added to the document.")
        if add_data:
            _data_id = {
                "type": storage_type,
                "index": plot_index,
                "group_id": group_id,
            }
            data_storage = html.Pre("", id=_data_id, **add_data, hidden=True)
            self.document.append(data_storage)
        return graph

    @staticmethod
    def _parse_column_widths(widths: Optional[Sequence[float]], no_of_columns: int) -> Sequence[Optional[float]]:
        """
        Parses a `column_widths` input from add_table method into a valid sequence of column width values.
        We expect the input to be provided as sequence of percents that sums up to 100%, but to be sure we normalize
        the widths by dividing each width by total widths sum.
        """
        _default_widths = [None] * no_of_columns

        # If no widths are provided or its number doesn't match the number of columns then we return a list of Nones
        if widths is None or len(widths) != no_of_columns:
            return _default_widths

        try:
            total_width = sum(widths)
            normalized_widths = [w / total_width * 100.0 for w in widths]
            return normalized_widths
        except (ValueError, TypeError):
            return _default_widths

add_text(text, style=TextStyle.DEFAULT, dictionary=None, **kwargs)

Adds text paragraph to the report document.

text is a string and style is an identifier of style that is applied to it. For Dash report, style's value it's a name of a class defined in CSS (see abb_dash.css file).

This method supports a subset of Markdown formatting in provided text string. Following elements are supported:

  • Empty line adds a new paragraph.

  • Hashes (#) at the beginning of the line add heading.

  • Pattern [TEXT](URL) adds a hyperlink with TEXT that points to URL.

  • Any occurrence of {{VARIABLE}} will be replaced by the string that comes from provided dictionary keyword argument.

Refer to interface documentation for more details.

Parameters:

Name Type Description Default
text str

Input text

required
style TextStyle

Identifier of a text style that will be applied to the text

DEFAULT
dictionary Optional[Dict]

Dictionary that would be used to replace Variables located in input text

None
Source code in smartreport/engine/outputs/dash_document.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def add_text(
    self, text: str, style: TextStyle = TextStyle.DEFAULT, dictionary: Optional[Dict] = None, **kwargs
) -> None:
    """Adds text paragraph to the report document.

    `text` is a string and `style` is an identifier of style that is applied to it.
    For Dash report, style's value it's a name of a class defined in CSS (see abb_dash.css file).

    This method supports a subset of Markdown formatting in provided text string.
    Following elements are supported:

    * Empty line adds a new paragraph.

    * Hashes (#) at the beginning of the line add heading.

    * Pattern `[TEXT](URL)` adds a hyperlink with TEXT that points to URL.

    * Any occurrence of `{{VARIABLE}}` will be replaced by the string that comes from
    provided `dictionary` keyword argument.

    Refer to [interface documentation](00_overview.md) for more details.

    Args:
      text: Input text
      style: Identifier of a text style that will be applied to the text
      dictionary: Dictionary that would be used to replace Variables located in input text

    """
    dictionary = dictionary if isinstance(dictionary, dict) else {}

    text_type = kwargs.pop("dash_type", DashElementsId.TEXT_PREFIX)
    text_index = kwargs.pop("dash_index", None)
    group_id = kwargs.pop("group_id", "")

    for line in text.split("\n"):
        # Extract the heading line
        heading_text, heading_level = get_heading_from_line(line)
        if heading_level is not None:
            self.add_heading(text=heading_text, level=heading_level)
            continue
        # Replace the variables
        new_line = replace_variables_in_line(line, dictionary)

        # Search for hyperlinks
        elements = []
        for sub_line in split_line_on_hyperlinks(line=new_line):
            if sub_line.get("type") == "text" and sub_line.get("text"):
                _span = html.Span(sub_line.get("text"))
                elements.append(_span)
            elif sub_line.get("type") == "link" and sub_line.get("text") and sub_line.get("url"):
                _a = html.A(href=sub_line.get("url"), children=[sub_line.get("text")], target="_blank")
                elements.append(_a)

        _index = text_index if text_index is not None else self.global_ids["text"]
        _id = {"type": text_type, "index": _index, "group_id": group_id}
        paragraph = html.P(id=_id, children=elements, className=style.value)
        self.global_ids["text"] += 1
        self.document.append(paragraph)
        # If line is not empty, log it in the trimmed version
        if new_line:
            log.debug(f'Paragraph "{trim_text(new_line, max_length=40)}" added.')
    return None

Adds hyperlink to the report document.

Hyperlink object can link the report reader to external url or to the another section of the report.

Parameters:

Name Type Description Default
text str

Text of the hyperlink.

required
url str

URL of the hyperlink.

required

Other Parameters:

Name Type Description
target str

Target of the hyperlink. It follows HTML convention: _blank, _self, _parent, _top. Default: _blank

wrap_in_new_paragraph bool

If true then the hyperlink is wrapped in

tags. Otherwise, it will be added alone. Default: True

Source code in smartreport/engine/outputs/dash_document.py
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
def add_hyperlink(self, text: str, url: str, **kwargs) -> None:
    """Adds hyperlink to the report document.

    Hyperlink object can link the report reader to external url or to the another section of the report.

    Args:
      text: Text of the hyperlink.
      url: URL of the hyperlink.

    Keyword Args:
        target (str): Target of the hyperlink. It follows HTML convention: `_blank`, `_self`, `_parent`, `_top`.
            Default: `_blank`
        wrap_in_new_paragraph (bool): If true then the hyperlink is wrapped in <p> tags.
            Otherwise, it will be added alone. Default: `True`

    """
    target = kwargs.get("target", "_blank")
    wrap_in_new_paragraph = kwargs.get("wrap_in_new_paragraph", True)
    element = html.A(href=url, children=[text], target=target)
    if wrap_in_new_paragraph:
        element = html.P(children=[element])

    self.document.append(element)
    log.debug(f"Hyperlink ({url})[{text}] added.")
    return None

add_heading(text, level, **kwargs)

Adds heading to the report document.

Heading is represented as HTML H1, H2, H3, H4, H5 or H6 tag. Heading text is defined by 'text' argument and level is defined by 'level'. When not supported level is provided the H1 tag is used.

Heading are also used for building interactive Table of Content. By default, all headings are included in the Table of Content up to the ToC depth level. Heading can be explicitly excluded from ToC by providing include_in_toc=False parameter.

Parameters:

Name Type Description Default
text str

Text of the heading

required
level int

Level of the heading. Integer from range 1 to 6

required

Other Parameters:

Name Type Description
include_in_toc bool

Flag that defines if given heading should be included in Tabel of Content. (default: True)

Source code in smartreport/engine/outputs/dash_document.py
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
def add_heading(self, text: str, level: int, **kwargs) -> None:
    """Adds heading to the report document.

    Heading is represented as HTML H1, H2, H3, H4, H5 or H6 tag.
    Heading text is defined by 'text' argument and level is defined by 'level'.
    When not supported level is provided the H1 tag is used.

    Heading are also used for building interactive Table of Content.
    By default, all headings are included in the Table of Content up to the ToC depth level.
    Heading can be explicitly excluded from ToC by providing `include_in_toc=False` parameter.

    Args:
      text: Text of the heading
      level: Level of the heading. Integer from range 1 to 6

    Keyword Args:
      include_in_toc (bool): Flag that defines if given heading should be included
        in Tabel of Content. (default: `True`)

    """
    include_in_toc = kwargs.get("include_in_toc", True)
    # Define the unique identifier of Heading HTML element
    _index = self.global_ids["heading"]
    _id = {"type": DashElementsId.TOC_HEADING, "index": _index, "level": level}
    self.global_ids["heading"] += 1

    # Try to find appropriate HTML tag, if not found use H1
    _html_header = getattr(html, f"H{level}", html.H1)
    header_element = _html_header(text, id=_id) if include_in_toc else _html_header(text)
    # Add it to the document
    self.document.append(header_element)
    log.debug(f"Heading{level}: '{text}' added.")
    return None

add_page_break(**kwargs)

Adds a page break to the report document.

It is represented as an empty Div element with a PAGE_BREAK class. Even though it's not visible in the Dash Report, it will preserve the information about the page break that can be used when converting Dash document to Word document.

Source code in smartreport/engine/outputs/dash_document.py
135
136
137
138
139
140
141
142
143
144
145
def add_page_break(self, **kwargs) -> None:
    """Adds a page break to the report document.

    It is represented as an empty Div element with a PAGE_BREAK class. Even though it's not visible
    in the Dash Report, it will preserve the information about the page break that can be used
    when converting Dash document to Word document.

    """
    self.document.append(html.Div(className=DashComponentClass.PAGE_BREAK))
    log.debug("Page Break added.")
    return None

add_toc(**kwargs)

Adds automatic Table of Content placeholder to the report document.

Dash Report renders interactive Table of Content with support of Dash Callbacks.

When the Dash document is loaded into report viewer, update_table_of_content callback in called. It extracts all headings up to the depth level from the document, and builds list of divs with links to each section out of it. Refer to the callback docstring for the details.

This method adds a Div placeholder where the output of this callback is added. Additionally, it stores all ToC parameters in dcc.Store object, so it can be used when doing Dash to Word conversion later.

Parameters heading_text, heading_level, and page_break are kept only to support backward compatibility when converting Dash to Word document. However, they are not used by default in new documents.

Other Parameters:

Name Type Description
depth int

Depth of the ToC. It defines the maximum heading level included in the ToC. (default: 2)

heading_text str

If provided, the ToC will be preceded with the heading component.

heading_level int

Level of the preceding heading component (default: 1)

page_break bool

If provided, ToC will be followed by a page break (default: False)

Source code in smartreport/engine/outputs/dash_document.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def add_toc(self, **kwargs) -> None:
    """Adds automatic Table of Content placeholder to the report document.

    Dash Report renders interactive Table of Content with support of Dash Callbacks.

    When the Dash document is loaded into report viewer, `update_table_of_content`
    callback in called. It extracts all headings up to the `depth` level from the document,
    and builds list of divs with links to each section out of it.
    Refer to the callback docstring for the details.

    This method adds a Div placeholder where the output of this callback is added.
    Additionally, it stores all ToC parameters in dcc.Store object, so it can be used when
    doing Dash to Word conversion later.

    Parameters `heading_text`, `heading_level`, and `page_break` are kept only to support
    backward compatibility when converting Dash to Word document.
    However, they are not used by default in new documents.

    Keyword Args:
        depth (int): Depth of the ToC. It defines the maximum heading level included in the ToC. (default: `2`)
        heading_text (str): If provided, the ToC will be preceded with the heading component.
        heading_level (int): Level of the preceding heading component (default: `1`)
        page_break (bool): If provided, ToC will be followed by a page break (default: `False`)

    """
    depth = kwargs.get("depth", 2)
    heading_text = kwargs.get("heading_text", "")
    heading_level = kwargs.get("heading_level", 1)
    page_break = kwargs.get("page_break", False)

    if heading_text and heading_level:
        self.add_heading(text=heading_text, level=heading_level, include_in_toc=False)

    # Prepare an object that stores information about ToC parameters
    params_element = dcc.Store(id=DashElementsId.TOC_PARAMS, data=kwargs)
    # ToC Div will be populated by the `update_table_of_content` callback
    # but before that happens we add a text placeholder
    txt_placeholder = "Please wait for the Table of Content to load."
    toc_structure = html.Div(
        className=DashComponentClass.TOC,
        children=[params_element, html.Div(id=DashElementsId.TOC_DIV, children=txt_placeholder)],
    )
    self.document.append(toc_structure)
    log.debug(f"ToC(depth={depth}) added.")

    if page_break:
        self.add_page_break()
    return None

add_table(table_data, style=TableStyle.DEFAULT, column_widths=None, **kwargs)

Adds table to the report document.

Input data should be provided as sequence of rows, where row is a sequence of cells and cells is either as simple string or a TableCell object that carries extra formatting information. Only 2-D structures with constant number of rows and columns are allowed.

Merging can be achieved by using a special cell values TableCell.MERGE_LEFT and TableCell.MERGE_ABOVE that are located in .components module.

Implementation details:

  • Cell merging is NOT implemented. The TableCell.MERGE_ABOVE is faked by removing the line between cells. However, the merge cells are preserved so the merging is applied when report is converted to Word Document.

  • This method ignores bold, italic and centered properties of TableCells.

  • This method uses dash conditional formatting that might be cryptic at first encounter, read more here

Parameters:

Name Type Description Default
table_data TableData

Sequence rows, where row is a sequence of cells. Cell might be a simple string or a TableCell object, that also carries the information about cell formatting.

required
style TableStyle

TableStyle enum, Identifier of a style that will be applied to created table

DEFAULT
column_widths Sequence[float]

Sequence of column widths as percents. They should sum up to 100%. If not provided, each implementation will figure out the best widths based on provided data.

None

Other Parameters:

Name Type Description
use_markdown bool

If true, Allow for markdown styling in table cells (default: False)

sort_action str

Sort action for table (default: native)

sort_mode str

Sort mode for table (default: single)

filter_action str

Filter action for table (default: none)

filter_query str

Filter query for table (default: '')

dropdown_columns dict

Dictionary of columns that should have dropdowns (default: {})

reset_button bool

Show table reset button (default: False)

store_data bool

Store original table data in hidden field (default: False)

row_deletable bool

Allow deleting table rows (default: False)

editable bool

Allow editing table cells (default: False)

cell_selectable bool

Make table cell selectable / clickable (default: True)

extra_styles list

List of extra styles to be applied to table

include_cell_styles bool

Include cell styles in table styling (default: True)

page_size int

Table page size (default: 50)

Source code in smartreport/engine/outputs/dash_document.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
def add_table(
    self,
    table_data: TableData,
    style: TableStyle = TableStyle.DEFAULT,
    column_widths: Sequence[float] = None,
    **kwargs,
) -> None:
    """Adds table to the report document.

    Input data should be provided as sequence of rows, where row is a sequence of cells
    and cells is either as simple string or a TableCell object that carries extra formatting information.
    Only 2-D structures with constant number of rows and columns are allowed.

    Merging can be achieved by using a special cell values `TableCell.MERGE_LEFT` and `TableCell.MERGE_ABOVE` that
    are located in .components module.

    Implementation details:

    * Cell merging is NOT implemented. The `TableCell.MERGE_ABOVE` is faked by removing the line between cells.
      However, the merge cells are preserved so the merging is applied when report is converted to Word Document.

    * This method ignores bold, italic and centered properties of TableCells.

    * This method uses dash conditional formatting that might be cryptic at first encounter, read more
      [here](https://dash.plotly.com/datatable/conditional-formatting)

    Args:
      table_data: Sequence rows, where row is a sequence of cells. Cell might be a simple string
        or a TableCell object, that also carries the information about cell formatting.
      style: TableStyle enum, Identifier of a style that will be applied to created table
      column_widths: Sequence of column widths as percents. They should sum up to 100%. If not provided,
        each implementation will figure out the best widths based on provided data.

    Keyword Args:
      use_markdown (bool): If true, Allow for markdown styling in table cells (default: `False`)
      sort_action (str): Sort action for table (default: `native`)
      sort_mode (str): Sort mode for table (default: `single`)
      filter_action (str): Filter action for table (default: `none`)
      filter_query (str): Filter query for table (default: '')
      dropdown_columns (dict): Dictionary of columns that should have dropdowns (default: `{}`)
      reset_button (bool): Show table reset button (default: `False`)
      store_data (bool): Store original table data in hidden field (default: `False`)
      row_deletable (bool): Allow deleting table rows (default: `False`)
      editable (bool): Allow editing table cells (default: `False`)
      cell_selectable (bool): Make table cell selectable / clickable (default: `True`)
      extra_styles (list): List of extra styles to be applied to table
      include_cell_styles (bool): Include cell styles in table styling (default: `True`)
      page_size (int): Table page size (default: `50`)

    """

    table_type: str = kwargs.pop("dash_type", DashElementsId.TABLE_PREFIX)
    table_index: int = kwargs.pop("dash_index", self.global_ids["table"])
    group_id: str = kwargs.get("group_id", f"{table_type}-{table_index}")
    use_markdown = kwargs.get("use_markdown", False)
    sort_action = kwargs.get("sort_action", "native")
    sort_mode = kwargs.get("sort_mode", "single")
    filter_action = kwargs.get("filter_action", "none")
    filter_query = kwargs.get("filter_query", "")
    dropdown_columns = kwargs.get("dropdown_columns", {})
    reset_button = kwargs.get("reset_table", False)
    store_data = kwargs.get("store_data", False)
    row_deletable = kwargs.get("row_deletable", False)
    editable = kwargs.get("editable", False)
    cell_selectable = kwargs.get("cell_selectable", True)
    extra_styles = kwargs.get("extra_styles", [])
    include_cell_styles = kwargs.get("include_cell_styles", True)
    page_size = kwargs.get("page_size", 50)
    no_of_row_headers = kwargs.get("no_of_row_headers", 0)
    markdown_options = kwargs.get("markdown_options", None)

    _id = {"type": table_type, "index": table_index, "group_id": group_id}
    _presentation = "markdown" if use_markdown is True else "input"
    _styles = extra_styles[:]

    # In Dash Report setting font size has currently no effect - default font size works and looks fine
    # we still need to preserve info about it for conversion to word

    if isinstance(style, TableStyle):
        word_table_style = style.value
    else:
        log.info(f"Unsupported type of table style: {type(style)}, defaulting to {TableStyle.DEFAULT}")
        word_table_style = TableStyle.DEFAULT

    # Check if table size is correct
    t_rows, t_cols = get_table_size(table_data)
    if t_rows is None or t_cols is None:
        return None

    # Parse column widths
    parsed_column_widths = self._parse_column_widths(widths=column_widths, no_of_columns=t_cols)
    # Initialize columns
    multi_title = False
    columns = []
    for name in table_data[0]:
        if isinstance(name, TableCell):
            name = name.text
            if isinstance(name, list):
                columns.append(name)
                multi_title = True
            else:
                columns.append(str(name) if str(name) not in self.SPECIAL_CELLS else "")
        else:
            columns.append(str(name) if str(name) not in self.SPECIAL_CELLS else "")
    # Check if column names are empty, if so, replace them with empty string
    _column_data = [
        {
            "name": c,
            "id": clear_str(f"{c}{i}"),
            "presentation": _presentation,
        }
        for i, c in enumerate(columns)
    ]

    # Extracting cell text and formatting
    _rows, _cell_styles = self._extract_cell_data(table_data=table_data, column_data=_column_data)
    if include_cell_styles:
        _styles.extend(_cell_styles)
    # Additional Row Styling
    # Uses dash conditional formatting, read docstring
    _style_for_bottom_border = {"if": {"row_index": t_rows - 2}, "border_bottom": "1px solid black"}
    _header_style = {
        "backgroundColor": "white",
        "fontWeight": "bold",
        "border_top": "2px solid black",
        "border_bottom": "1px solid black",
    }
    # This will wrap too long texts in cells
    _data_style = {
        "whiteSpace": "pre-line",
        "height": "auto",
        "margin-left": 30,
        "textAlign": "left",
        # word_table_style size setting will have no effect in dash document
        # (word_table_style property doesn't exist in css)
        # but we will preserve this information for convert to word stage
        "word_table_style": word_table_style,
        # Specifies the no of header rows repeated on each page
        # for multi-page tables
        "no_of_row_headers": no_of_row_headers,
    }

    # Uses dash conditional formatting, read docstring
    for col_data, col_width in zip(_column_data, parsed_column_widths):
        if col_width is not None:
            column_style = {"if": {"column_id": col_data.get("id")}, "width": f"{col_width:.0f}%"}
            _styles.append(column_style)
    _styles.append(_style_for_bottom_border)

    # Some tables might require filtering by column value
    # The filtering logic is defined in Dash callbacks,
    # and below we add dropdown for each column that we want to filter by
    if dropdown_columns:
        self._add_dropdown_columns(
            dropdown_columns=dropdown_columns,
            rows=_rows,
            table_index=table_index,
            cd=_column_data,
            group_id=group_id,
        )
    # If filtering is used then the reset button is usually needed as well
    # To restore the table to its original state
    # The original data is stored in the store_element that is also a part of the report.
    if reset_button:
        self._add_reset_button(table_index=table_index, group_id=group_id)
    if store_data:
        store_element = dcc.Store(
            id={
                "type": DashElementsId.DATA_STORAGE_PREFIX,
                "index": table_index,
                "group_id": group_id,
            },
            data=_rows,
        )
        self.document.append(store_element)

    # Finally, DataTable object is initialized with all custom styling defined above
    table_element = DataTable(
        columns=_column_data,
        id=_id,
        cell_selectable=cell_selectable,
        row_deletable=row_deletable,
        style_as_list_view=True,
        sort_action=sort_action,
        sort_mode=sort_mode,
        filter_action=filter_action,
        filter_query=filter_query,
        style_header=_header_style,
        style_data_conditional=_styles,
        style_cell=_data_style,
        data=_rows,
        editable=editable,
        page_size=page_size,
        merge_duplicate_headers=multi_title,
        markdown_options=markdown_options,
    )
    # dcc.Loading shows 'rotating wheel of waiting' in place of Table, when table is rendered
    self.document.append(dcc.Loading(table_element))
    self.global_ids["table"] += 1
    log.debug("Table added.")
    return None

add_table_legend(legend_cells, **kwargs)

Adds a color-based legend table to the report document.

It expects a sequence of LegendCell objects as an input. Each LegendCell object defines a title, color and description. Legend can be used to explain color encoding of a table. Widths of legend cells are automatically calculated. Based on the required space, legend is adjusted to the right or takes all the row space.

Parameters:

Name Type Description Default
legend_cells Sequence[LegendCell]

Sequence of LegendCell objects.

required
Source code in smartreport/engine/outputs/dash_document.py
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def add_table_legend(self, legend_cells: Sequence[LegendCell], **kwargs) -> None:
    """Adds a color-based legend table to the report document.

    It expects a sequence of LegendCell objects as an input.
    Each LegendCell object defines a title, color and description. Legend can be used to explain
    color encoding of a table. Widths of legend cells are automatically calculated. Based on the required space,
    legend is adjusted to the right or takes all the row space.

    Args:
      legend_cells: Sequence of LegendCell objects.

    """
    if not legend_cells:
        return None

    table_type: str = kwargs.pop("dash_type", DashElementsId.LEGEND_PREFIX)
    table_index: int = kwargs.pop("dash_index", self.global_ids["table_legend"])
    group_id: str = kwargs.get("group_id", f"{table_type}-{table_index}")
    size_multiplier: float = kwargs.get("size_multiplier", 1.0)
    add_top_margin: bool = kwargs.get("add_top_margin", False)

    _id = {"type": table_type, "index": table_index, "group_id": group_id}
    # first column is used to align legend to right side of the page
    _first_column_id = "first_column"
    # add color cells
    color_cells = [
        LegendCell(title="", color=cell.color, gradient_colors=cell.gradient_colors) for cell in legend_cells
    ]
    color_cell_width = 30 * size_multiplier
    longest_title_len = max([len(cell.title) for cell in legend_cells])
    pixels_per_char = 10 * size_multiplier
    computed_legend_cell_width = longest_title_len * pixels_per_char * size_multiplier
    first_column_width = self.WORKING_PAGE_WIDTH - (computed_legend_cell_width + color_cell_width) * len(
        legend_cells
    )

    first_column_width_css = f"{first_column_width * size_multiplier}px"
    color_cell_width_css = f"{color_cell_width}px"

    # this is for making the legend look nice and airy: little space after the text before next color
    def get_cell_length(title):
        title_length = len(title)
        if title_length < 13:
            return (title_length + 4) * pixels_per_char
        return title_length * pixels_per_char

    # add color cells to their places
    _legend_cells: Sequence[Any] = [None] * (len(legend_cells) + len(color_cells))
    _legend_cells[::2] = color_cells
    _legend_cells[1::2] = legend_cells
    legend_cells = _legend_cells

    legend_element = DataTable(
        id=_id,
        columns=[
            {"id": _first_column_id, "name": ""},
            *[
                {"id": cell.title, "name": cell.title} if cell.title else {"id": cell.color, "name": ""}
                for cell in legend_cells
            ],
        ],
        style_table={
            "marginBottom": f"{30 * size_multiplier}px",
            "fontSize": f"{17 * size_multiplier}px",
            "marginTop": f"{30 * size_multiplier if add_top_margin else 0}px",
        },
        style_header={
            "textAlign": "left",
            "border_top": "0",
            "border_bottom": "0",
            "padding": "5px",
        },
        style_header_conditional=[
            {
                "if": {"column_id": _first_column_id},
                "backgroundColor": ABBColors.WHITE.value,
                "width": first_column_width_css,
            },
            *[
                {
                    "if": {"column_id": cell.title},
                    "backgroundColor": ABBColors.WHITE.value,
                    "width": f"{get_cell_length(cell.title)}px",
                }
                for cell in legend_cells
            ],
            *[
                {
                    "if": {"column_id": cell.color},
                    "backgroundColor": cell.color,
                    "background": f"linear-gradient(90deg, {', '.join(cell.gradient_colors)})",
                    "width": color_cell_width_css,
                }
                for cell in legend_cells
            ],
        ],
        tooltip_header={cell.title: cell.description for cell in legend_cells},
        tooltip_delay=0,
        tooltip_duration=None,
    )
    # dcc.Loading shows 'rotating wheel of waiting' in place of table, when table is rendered
    self.document.append(dcc.Loading(legend_element))
    self.global_ids["table_legend"] += 1
    log.debug("Table legend added.")
    return None

add_pictures(pictures, widths=None, **kwargs)

Adds a sequence of static pictures to a single row in the report document.

Each picture should be provided either as a sequence of bytes or as a path to the picture file.

Parameters:

Name Type Description Default
pictures Sequence[Union[Path, str, bytes]]

Sequence of picture data provided either as a bytes sequence or picture file path.

required
widths Sequence[float]

Optional sequence of pictures widths. They should sum up to 100%. If not provided, each implementation will figure out the best widths based on provided data.

None
Source code in smartreport/engine/outputs/dash_document.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
def add_pictures(
    self, pictures: Sequence[Union[Path, str, bytes]], widths: Sequence[float] = None, **kwargs
) -> None:
    """Adds a sequence of static pictures to a single row in the report document.

    Each picture should be provided either as a sequence of bytes or as a path to the picture file.

    Args:
      pictures: Sequence of picture data provided either as a bytes sequence or picture file path.
      widths: Optional sequence of pictures widths. They should sum up to 100%. If not provided,
        each implementation will figure out the best widths based on provided data.

    """

    if not pictures:
        return None

    default_width = self.WORKING_PAGE_WIDTH / len(pictures)
    widths = widths if widths is not None else [default_width] * len(pictures)

    for picture, width in zip(pictures, widths):
        picture_element = self._prepare_single_picture(picture_path=picture, width=width, **kwargs)
        self.document.append(picture_element)
        self.global_ids[DashElementsId.PICTURE_PREFIX] += 1
    return None

add_figures(figures, widths=None, **kwargs)

Adds a sequence of Plotly figures to a single row in the report document.

Dash reports natively supports Plotly figures, so they can be simply added to the dash document as a Graph object.

Parameters:

Name Type Description Default
figures Sequence[Figure]

Sequence of Plotly figure objects data provided either as a bytes sequence or string.

required
widths Optional[Sequence[float]]

Optional sequence of pictures widths. They should sum up to 100%. If not provided,

None

each implementation will figure out the best widths based on provided data.

Other Parameters:

Name Type Description
plot_title str

Plot title. It will be added as a heading just before the row with figures if provided.

include_comments_box bool

If true, the row with figures will be followed with a text area where report reader can add the comments. (default: True)

add_loading bool

If true, the figure row will be wrapped in loading spinner for the report initial loading time. (default True)

Source code in smartreport/engine/outputs/dash_document.py
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def add_figures(self, figures: Sequence[Figure], widths: Optional[Sequence[float]] = None, **kwargs) -> None:
    """Adds a sequence of Plotly figures to a single row in the report document.

    Dash reports natively supports Plotly figures, so they can be simply added to the dash document
    as a Graph object.

    Args:
      figures: Sequence of Plotly figure objects data provided either as a bytes sequence or string.
      widths: Optional sequence of pictures widths. They should sum up to 100%. If not provided,
    each implementation will figure out the best widths based on provided data.

    Keyword Args:
      plot_title (str): Plot title. It will be added as a heading just before the row with figures if provided.
      include_comments_box (bool): If true, the row with figures will be followed with a text area where
        report reader can add the comments. (default: `True`)
      add_loading (bool): If true, the figure row will be wrapped in loading spinner
        for the report initial loading time. (default `True`)

    """
    plot_title = kwargs.pop("plot_title", "")
    include_comments_box = kwargs.pop("include_comments_box", True)
    add_loading = kwargs.pop("add_loading", True)

    # Calculate widths of provided figures based on document page width
    widths_px = [figure.layout.width if figure.layout.width else self.WORKING_PAGE_WIDTH for figure in figures]
    total_width = sum(widths_px)
    widths = widths if widths is not None else [100.0 * w / total_width for w in widths_px]

    # Add a heading with plot title, if provided
    if plot_title:
        self.add_text(text=plot_title, style=TextStyle.PLOT_TITLE)

    # Build list of Dash Graph objects based on provided sequence of figures
    graph_elements = []
    for figure, width in zip(figures, widths):
        graph_object = self._prepare_single_figure(figure=figure, width=width, **kwargs)
        self.global_ids["figure"] += 1
        graph_elements.append(graph_object)

    # Add row with figures, to the document
    if graph_elements:
        div_with_figures = html.Div(children=graph_elements, className=DashComponentClass.FIGURE_ROW)
        if add_loading:
            div_with_figures = dcc.Loading(children=div_with_figures)
        self.document.append(div_with_figures)

    if include_comments_box:
        self.add_comment_box()
    return None

column_section(no_of_columns=2)

Creates a context in which the Report Output works in column layout.

Number of columns is defined 'no_of_columns' parameter. You can add components to the document the same way as you would do for a standard (single column) layout, but within the context you hove a next_column() function available that can move you to the next column. When the context is finished the basic layout is restored (single column).

Example of usage:

ro = DashReportOutput()
with ro.column_section(3) as nc:  # 'nc' is the name of the function that can jump to next column
    # We start from the first column (on the left)
    # work with ReportOutput the same way as usual
    ro.add_text("Text in first column")
    nc()  # move the context to the next column (second)
    ro.add_heading("Heading in the middle", level=2)
    ro.add_text("Text in second column")
    nc()  # move the context to the next column (third, last)
    ro.add_text("Text in third column")
    nc()  # there were only three columns in this context, so this will do nothing

Parameters:

Name Type Description Default
no_of_columns int

Number of columns for this column section

2

Returns:

Type Description
None

Function that moves the context to the next column

Source code in smartreport/engine/outputs/dash_document.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
@contextmanager
def column_section(self, no_of_columns: int = 2) -> Generator[Callable[[], None], None, None]:
    """Creates a context in which the Report Output works in column layout.

    Number of columns is defined 'no_of_columns' parameter.
    You can add components to the document the same way as you would do for a standard (single column) layout,
    but within the context you hove a `next_column()` function available that can move you to the next column.
    When the context is finished the basic layout is restored (single column).

    Example of usage:
    ```python
    ro = DashReportOutput()
    with ro.column_section(3) as nc:  # 'nc' is the name of the function that can jump to next column
        # We start from the first column (on the left)
        # work with ReportOutput the same way as usual
        ro.add_text("Text in first column")
        nc()  # move the context to the next column (second)
        ro.add_heading("Heading in the middle", level=2)
        ro.add_text("Text in second column")
        nc()  # move the context to the next column (third, last)
        ro.add_text("Text in third column")
        nc()  # there were only three columns in this context, so this will do nothing
    ```

    Args:
      no_of_columns: Number of columns for this column section

    Returns:
      Function that moves the context to the next column

    """

    column_txt = self.CHARTS_COLUMNS.get(no_of_columns, "twelve")
    # 'full_document' holds all components of the Dash document
    # we will add a Div that will hold the multi-column layout
    self.full_document.append(html.Div(className=DashComponentClass.COLUMNS, children=[]))
    _row_with_columns = self.full_document[-1].children

    # First Column
    # We add the Div that will hold the content of the first column
    _row_with_columns.append(html.Div(className=f" {column_txt} {DashComponentClass.COLUMNS}", children=[]))
    # 'self.document' attribute is by default pointing to the full_document
    # Here we are pointing it to the newly created Div that will hold the content of the current column,
    # so we can work with the report output as we would be in the standard layout, and the content will be
    # added to current column
    self.document = _row_with_columns[-1].children
    # We update the current column width that controls the size of figures and pictures added to the document
    self.current_column_width = 1.0 / no_of_columns
    self.current_number_of_columns = no_of_columns

    log.debug(f"Working in column: 1 / {no_of_columns}")

    def move_to_next_column():
        """This function can jump to the next column within the context."""
        nonlocal _row_with_columns
        nonlocal self
        _column_id = len(_row_with_columns)

        # Check if we still have columns available to jump to
        if _column_id >= no_of_columns:
            log.warning(f"There is no next column to move to. ({_column_id} / {no_of_columns})")
            return None
        # Add a next Div container to row with columns and point the 'self.document' to it
        _row_with_columns.append(html.Div(className=f"{column_txt} {DashComponentClass.COLUMNS}", children=[]))
        self.document = _row_with_columns[-1].children
        _column_id = len(_row_with_columns)
        log.debug(f"Working in column: {_column_id} / {no_of_columns}")

    try:
        yield move_to_next_column
    finally:
        # Clean up the layout after the context is exited
        # Restore the column width to 1, since we have a single column
        # and point the 'self.document' back to 'self.full_document'
        self.current_column_width = 1.0
        self.current_number_of_columns = 1
        self.document = self.full_document

export(filepath, **kwargs)

Exports a report document to a file path provided in the filepath argument.

Parameters:

Name Type Description Default
filepath Union[str, Path]

Path of the exported document file.

required

Other Parameters:

Name Type Description
format str

Format of the export file. Supported formats: gz, json. Default: gz

encoding str

Data encoding. Default: utf-8

compression_level int

Compression level. Works only if exporting to gz format. Default: 9

Note

Even if you provide an extension in the filepath it will be overwritten based on format argument.

Source code in smartreport/engine/outputs/dash_document.py
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
def export(self, filepath: Union[str, Path], **kwargs) -> None:
    """
    Exports a report document to a file path provided in the `filepath` argument.

    Args:
      filepath: Path of the exported document file.

    Keyword Args:
        format (str): Format of the export file. Supported formats: `gz`, `json`. Default: `gz`
        encoding (str): Data encoding. Default: `utf-8`
        compression_level (int): Compression level. Works only if exporting to `gz` format. Default: `9`

    Note:
        Even if you provide an extension in the filepath it will be overwritten based on `format` argument.

    """
    _format = kwargs.get("format", self.export_extension)

    filepath = Path(filepath).with_suffix(f".{_format}")
    bytes_data = self.to_bytes(**kwargs)
    try:
        filepath.write_bytes(bytes_data)
        log.debug(f"Report based on {self.__class__.__name__} exported to {filepath}")
    except PermissionError:
        new_filepath = filepath.with_stem(f"{filepath.stem}_1")
        self.export(filepath=new_filepath, **kwargs)

add_slider(initial_value, button_text, **kwargs)

Adds a button to the report document that opens an extra window with a slider that allow the report reader to adjust some values that affect the report content.

It can only be implemented for the interactive report output types, but the results of the content modification caused by the slider can be saved, and therefore seen in the static report after the conversion process.

Currently, only Dash Report Output implements it.

Parameters:

Name Type Description Default
initial_value float

Initial value of the slider

required
button_text str

Text on the button that opens the slider window

required

Other Parameters:

Name Type Description
min_value float

Minimum value of the slider (default: 0.0)

max_value float

Minimum value of the slider (default: 100.0)

resolution float

Resolution of the slider (default: 0.1)

no_of_visible_steps int

Number of main ticks on the slider (default: 10)

unit str

Unit of values on the slider

title str

Title visible in the slider window

group_id str

Optional ID of the group that this component should belong to

hide_slider_button bool

if True hides button, essentially disabling it (default: False)

Source code in smartreport/engine/outputs/dash_document.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
def add_slider(self, initial_value: float, button_text: str, **kwargs) -> None:
    """Adds a button to the report document that opens an extra window with a slider that allow the report reader
    to adjust some values that affect the report content.

    It can only be implemented for the interactive report
    output types, but the results of the content modification caused by the slider can be saved,
    and therefore seen in the static report after the conversion process.

    Currently, only Dash Report Output implements it.

    Args:
      initial_value: Initial value of the slider
      button_text: Text on the button that opens the slider window

    Keyword Args:
      min_value (float): Minimum value of the slider (default: `0.0`)
      max_value (float): Minimum value of the slider (default: `100.0`)
      resolution (float): Resolution of the slider (default: `0.1`)
      no_of_visible_steps (int): Number of main ticks on the slider (default: `10`)
      unit (str): Unit of values on the slider
      title (str): Title visible in the slider window
      group_id (str): Optional ID of the group that this component should belong to
      hide_slider_button (bool): if True hides button, essentially disabling it (default: `False`)

    """
    min_value: float = kwargs.get("min_value", 0.0)
    max_value: float = kwargs.get("max_value", 60.0)
    resolution: float = kwargs.get("resolution", 0.1)
    no_of_visible_steps: int = kwargs.get("no_of_visible_steps", 10)
    unit = kwargs.get("unit", "")
    title = kwargs.get("title")
    group_id = kwargs.get("group_id")
    hide_slider_button = kwargs.get("hide_slider_button", False)
    # Prepare IDs
    _text_id = {"type": DashElementsId.GROUP_SLIDER_TEXT, "group_id": group_id}
    _div_id = {"type": DashElementsId.GROUP_SLIDER_DIV, "group_id": group_id}
    _button_id = {"type": DashElementsId.GROUP_SLIDER_BUTTON, "group_id": group_id}
    _close_id = {"type": DashElementsId.GROUP_SLIDER_CLOSE, "group_id": group_id}
    _slider_id = {"type": DashElementsId.GROUP_SLIDER, "group_id": group_id}

    # Configure Slider component
    resolution_array = np.arange(min_value + resolution, max_value + resolution, resolution)
    steps_array = resolution_array
    steps_no = len(steps_array)
    label_step = int(steps_no / no_of_visible_steps)
    value = steps_array[nearest_point(steps_array, initial_value)]
    marks = {step: (f"{step:.1f} [{unit}]" if i % label_step == 0 else "") for i, step in enumerate(steps_array)}
    dash_slider = dcc.Slider(
        id=_slider_id,
        min=min_value,
        max=max_value,
        value=value,
        marks=marks,
        step=None,
        included=False,
        updatemode="drag",
    )
    # Configure slider Button
    slider_button = html.Div(
        children=[html.Button(button_text, id=_button_id, n_clicks=0), html.Br(), html.Br(), html.Br()],
        className="slider-buttons",
        hidden=hide_slider_button,
    )
    # Create other components: Close button, text box for current slider value and hidden storage object
    close_button = html.Button("X", id=_close_id, n_clicks=0, className="slider-close-button")
    text_box = html.P(children=[html.Span(initial_value, id=_text_id), html.Span(unit)])
    storage = html.Pre(value, id={"type": DashElementsId.GROUP_SLIDER_STORAGE, "group_id": group_id}, hidden=True)
    # Create hidden div that collects all slider components
    slider_div = html.Div(children=[], id=_div_id, className="slider-container", hidden=True)
    if title:
        slider_div.children.append(html.H2(title))
    slider_div.children.extend([text_box, dash_slider, storage, close_button])

    self.document.append(slider_button)
    self.document.append(slider_div)
    log.debug(f"Slider added to the document (group_id={group_id}).")
    return None

add_comment_box(**kwargs)

Adds an interactive field to the report document where the report readers can add theirs comments.

It can only be implemented for the interactive report output types, but the comment text added by the reader can be saved and seen in the static reports after the conversion process.

Other Parameters:

Name Type Description
placeholder str

Placeholder text. (default: Please put your comments here)

height int

Height of text area. (default: 100)

initial_text str

Initial text in the box. (default: "")

Source code in smartreport/engine/outputs/dash_document.py
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def add_comment_box(self, **kwargs):
    """Adds an interactive field to the report document where the report readers can add theirs comments.

    It can only be implemented for the interactive report output types, but the comment text added by the reader
    can be saved and seen in the static reports after the conversion process.

    Keyword Args:
        placeholder (str): Placeholder text. (default: `Please put your comments here`)
        height (int): Height of text area. (default: `100`)
        initial_text (str): Initial text in the box. (default: "")

    """
    comment_index = kwargs.get("dash_index", self.global_ids["comment"])
    placeholder: str = kwargs.get("placeholder", "Please put your comments here")
    height: int = kwargs.get("height", 100)
    initial_text: str = kwargs.get("initial_text", "")
    _id = {"type": DashElementsId.COMMENT_PREFIX, "index": comment_index}
    box = html.Div(
        className="u-full-width",
        children=[
            dcc.Textarea(
                className="u-full-width",
                id=_id,
                value=initial_text,
                placeholder=placeholder,
                style={"height": height},
            )
        ],
    )
    self.global_ids["comment"] += 1
    self.document.append(box)

add_audio_player(audio_data, **kwargs)

Adds an audio player to the report document.

It takes any sequence of bytes that can be interpreted as sound wave, and creates HTML Audio element with based on this data.

Parameters:

Name Type Description Default
audio_data bytes

Sequence of bytes that can be interpreted as a sound wave.

required
Source code in smartreport/engine/outputs/dash_document.py
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
def add_audio_player(self, audio_data: bytes, **kwargs) -> None:
    """Adds an audio player to the report document.

    It takes any sequence of bytes that can be interpreted as sound
    wave, and creates HTML Audio element with based on this data.

    Args:
      audio_data: Sequence of bytes that can be interpreted as a sound wave.

    """
    # Convert bytes to Base64 encoded string.
    b64wave = base64.b64encode(audio_data).decode("utf-8")
    # Create an audio player and initialize it with WAVE data
    player = html.Audio(loop=True, controls=True, src=f"data:audio/x-wav;base64,{b64wave}")
    self.document.append(player)
    return None