Output Steps

All steps can be imported directly from the ppc_robot_lib.steps.output module.

Notifications

class NotificationOutputStep(condition, text, code, category=None, text_localized=True, text_plural=None, text_number=None, text_params=None, score=None, level=NotificationLevel.WARNING, details_table=None, entity_id_column=None)[source]

Issues a notification of the given conditions are met.

Several prepared conditions from the ppc_robot_lib.steps.conditions module can be used.

Example:

>>> from ppc_robot_lib.steps import conditions
>>> from ppc_robot_lib.steps.output import NotificationOutputStep
>>> from ppc_robot_lib.steps.transformations import GroupByAndAggregateStep, RenameStep
>>> # Table errors contains two coumns: ``url`` and ``error`` text.
... # The following code groups it by the error text.
>>> yield GroupByAndAggregateStep('errors', 'error', {
...     'url': 'count',
... }, 'notifications_error')
... yield RenameStep('notifications_error', {'error': 'Error', 'url': 'Number of URLs'})
>>> def get_error_count(task_ctx):
...     return task_ctx.work_set.get_table('notifications')['Number of URLs'].sum()
>>> def get_text_params(task_ctx):
...     return [get_error_count(task_ctx)]
>>> yield NotificationOutputStep(
...     condition=conditions.table_not_empty('notifications'),
...     text='URL checker found %d error.',
...     text_plural='URL Checker found %d errors.',
...     text_number=get_error_count,
...     text_params=get_text_params,
...     category=4,
...     code=0,
...     details_table='notifications'
... )
Parameters:
  • condition (Callable[[TaskContextInterface], bool]) – Condition – callable that receives a TaskContext and returns bool. If True is returned, the notification issued.

  • text – Notification text.

  • code (FactoryMethod | int) – Notification code – can be either int, or reference to ppc_robot_lib.exceptions.FactoryMethod. If a FactoryMethod is given, code and category is extracted from its definition. See Categories and Codes for list of categories and codes.

  • category – Category code, when not given it is extracted from the object given in the code argument. See Categories and Codes for list of categories and codes.

  • text_localized – Should the given text be localized in the interface?

  • text_plural – Plural version of the text, used for localization.

  • text_number (Callable[[TaskContextInterface], int] | int) – Number that will be used to determine which plural form shall be used. Can be given as int, or callable that receives a TaskContext and returns int.

  • text_params (dict[str, Any] | list[Any] | None | Callable[[TaskContextInterface], dict[str, Any] | list[Any] | None]) – Text parameters, if given it will be used as expansion parameters for the % operator when rendering the text. It can be a dict, `list/`tuple, or a callable that receives TaskContext and returns either of the types.

  • score (Callable[[TaskContextInterface], int] | int) – Overall score used to rank notifications. Higher score means more important (severe) notification. The score can be given either as an int, or a callable that receives a TaskContext and returns int.

  • level – One of ppc_robot_lib.models.notification.NotificationLevel constants.

  • details_table – Name of the table that will be attached to the notification.

  • entity_id_column – IDs of entities that are related to the given notification.

Generic Output Step

class TablesOutputStep(tables)[source]

This step writes collection of tables as a spreadsheet (Excel), or writes them to external service (Google Sheets). This step prepares all the data, loads previously stored state, and delegates the output process to a specified adapter.

After the adapter completes (or fails with an exception), state is stored for further use for the current job.

Parameters:

tables (list[Table]) – List of tables to output. See ppc_robot_lib.utils.types.Table for more details.

Table definition

class Table(table_name, sheet_name, header=None, data_builder=None, freeze_header=False, freeze_columns=0, sheet_id=None, row_height=None, create_filter=False, currency_column=None, embedded_charts=None)[source]

Definition of a table that will be written to output. It defines internal name of the table, output sheet, table header, a function used to transform the data, number of columns to freeze and whether to freeze top rows containing header or not.

The header will be used as colum mapping and to generate the header. It is a collection of ppc_robot_lib.utils.types.Column or ppc_robot_lib.utils.types.ColumnGroup instances. ColumnGroup can contain multiple columns and even another ColumnGroup. These groups will be used to generate multi-row headers.

Each column must have at least title and number of column to use. You can also set style for the header and format for the values. See the ppc_robot_lib.utils.types.Column and ppc_robot_lib.utils.types.ColumnGroup classes for more details. The output adapter might ignore styles, or tailor them to its needs. They are best suited for Google Spreadsheet and Excel outputs.

If no header is given, it shall be derived from input table.

Header example:

>>> from ppc_robot_lib.utils.types import Color, Column, ColumnGroup, Format, FormatType
>>> percent_fmt = Format(FormatType.PERCENT, pattern="#.00%")
>>> money_fmt = Format(FormatType.CURRENCY)
>>> header = [
...     Column('Account Name', 'AccountDescriptiveName'),
...     Column('Account Number', 'AccountNumber'),
...     ColumnGroup('PNO', columns=[
...         Column('PNO Yday', 'Pno_yesterday', cell_format=percent_fmt),
...         Column('PNO 7 Days', 'Pno_last_7_days', cell_format=percent_fmt),
...         Column('PNO 30 Days', 'Pno_last_30_days', cell_format=percent_fmt),
...     ]),
...     ColumnGroup('Conversion Value', columns=[
...         Column('Value Yesterday', 'AllConversionValue_yesterday', cell_format=money_fmt),
...         Column('Value Last Week', 'AllConversionValue_last_week', cell_format=money_fmt),
...         Column('Value This Month', 'AllConversionValue_this_month', cell_format=money_fmt),
...         Column('Value Last Month', 'AllConversionValue_last_month', cell_format=money_fmt),
...     ]),
... ]

The data_builder function will recieve the following positional arguments, in order:

  1. data – empty list of rows. It is the functions’s responsibility to fill-in the list. Each row must be a list of cell values.

  2. tablepandas.DataFrame with data.

  3. row_columns – flattend list of ppc_robot_lib.utils.types.Column. Can be used to map table columns to values in rows.

  4. task_ctxppc_robot_lib.tasks.task_context.TaskContextInterface instance.

Both number and order of columns in output must match the header given in the header argument.

Data Builder example:

>>> def data_builder(data, table, columns, task_ctx):
...     for row in table.itertuples():
...         data.append([row.CampaignName, row.Impressions])
Parameters:
  • table_name (str | DataFrame) – Name of the table (pandas.DataFrame) in the current ppc_robot_lib.work_set.WorkSet or pandas.DataFrame instance.

  • sheet_name (str | Callable[[TaskContextInterface], str]) – Name of sheet in the output. It can be either a string or a callable that returns string.

  • header (list[ColumnGroup | Column]) – A collection of columns, see example above. If not given, it will be derived from the table.

  • data_builder (Callable[[DataFrame, TaskContextInterface], list]) – Optional function used for generating the output rows.

  • freeze_header – Set to True if you would like to freeze all header rows.

  • freeze_columns – Number of columns to freeze (row header).

  • sheet_id (int) – Internal sheet identifier. Used for renaming sheets to prevent dropping original one in case the user changes name of the spreadsheet. Can be any integer that can be represented in JSON.

  • row_height (int | None) – Row height. If not set, default of the given output platform will be used.

  • create_filter (bool) – Create a filterable table in the output sheet. If not given, no filtering will be applied and no user-changes will be discarded.

  • currency_column (str) – Name of the column that will be used to store the currency.

class EmbeddedChart(spec, width=600, height=400, data_sheet_id=None)[source]

Represents a chart that is embedded directly in the sheet.

A chart specification must be set. The used specification determines the type of chart that will be created.

Parameters:
  • spec (ChartSpec) – Chart type with parameters

  • width (int) – Width in pixels.

  • height (int) – Height in pixels.

  • data_sheet_id (int | None) – ID of sheet with data that will be used for the graph.

class ChartSpec(title, subtitle='', hidden_dimensions=HiddenDimensionOptions.SHOW_ALL)[source]

Represents specification of a chart type. Do not use directly, but use any of the sub-classes:

class LineChart(title, subtitle, domain_column, bottom_axis_title='', left_axis_title='', right_axis_title=None, hidden_dimensions=HiddenDimensionOptions.SHOW_ALL, line_smoothing=False, stacked=StackType.NOT_STACKED, use_column_headers=True)[source]

Represents a line chart.

Parameters:
  • title (str) – Chart title.

  • subtitle (str) – Chart subtitle.

  • domain_column (str) – Name of the column that will be used as the label of the X axis.

  • bottom_axis_title (str) – Description of the X axis.

  • left_axis_title (str) – Description of the main Y axis on the left.

  • right_axis_title (str | None) – Optional description of the secondary Y axis on the right. If not given, right Y axis is not created.

  • hidden_dimensions (HiddenDimensionOptions) – How to handle hidden columns and rows.

  • line_smoothing (bool) – Enable line-smoothing?

  • use_column_headers (bool) – Use column names as series labels?

add_series(column, color, line_style=None, axis=AxisPosition.LEFT)[source]
Parameters:
  • column (str) – Name of the column that should be used as data for the series.

  • color (Color) – Line color.

  • line_style (LineStyle) – Line style, if not given, solid line is used.

  • axis (AxisPosition) – What axis to use to plot the data.

Return type:

LineChart

class LineStyle(width, line_type=LineType.SOLID)[source]
Parameters:
  • width (int) – Line width in pixels.

  • line_type (LineType) – Line type.

class LineType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
DOTTED = 2

Dotted line.

LONG_DASHED = 4

Dashed line, long dashes.

MEDIUM_DASHED = 3

Dashed line, medium dashes.

SOLID = 1

Solid line.

class AxisPosition(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
LEFT = 1

Left axis.

RIGHT = 2

Right axis.