gofigr package

Submodules

gofigr.jupyter module

Copyright (c) 2022, Flagstaff Solutions, LLC All rights reserved.

class gofigr.jupyter.ApiId(api_id)

Bases: tuple

api_id

Alias for field number 0

class gofigr.jupyter.FindByName(name, description=None, create=False)[source]

Bases: object

Used as argument to configure() to specify that we want to find an analysis/workspace by name instead of using an API ID

class gofigr.jupyter.GfDisplayPublisher(pub)[source]

Bases: object

Custom IPython DisplayPublisher which traps all calls to publish() (e.g. when display(…) is called).

clear_output(*args, **kwargs)[source]

IPython’s clear_output. Defers to self.pub

publish(data, *args, **kwargs)[source]

IPython calls this method whenever it needs data displayed. Our function traps the call and calls DISPLAY_TRAP instead, giving it an option to suppress the figure from being displayed.

We use this trap to publish the figure if auto_publish is True. Suppression is useful when we want to show a watermarked version of the figure, and prevents it from being showed twice (once with the watermark inside the trap, and once without in the originating call).

Parameters:
  • data – dictionary of mimetypes -> data

  • args – implementation-dependent

  • kwargs – implementation-dependend

Returns:

None

class gofigr.jupyter.Publisher(gf, annotators, backends, watermark=None, image_formats=('png', 'eps', 'svg'), interactive=True, default_metadata=None, clear=True)[source]

Bases: object

Publishes revisions to the GoFigr server.

annotate(rev)[source]

Annotates a FigureRevision using self.annotators. :param rev: revision to annotate :return: annotated revision

auto_publish_hook(extension, data, suppress_display=None)[source]

Hook for automatically publishing figures without an explicit call to publish().

Parameters:
  • extension – GoFigrExtension instance

  • data – data being published. This will usually be a dictionary of mime formats.

  • native_publish – callable which will publish the figure using the native backend

Returns:

None

publish(fig=None, target=None, gf=None, dataframes=None, metadata=None, backend=None, image_options=None, suppress_display=None)[source]

Publishes a revision to the server.

Parameters:
  • fig – figure to publish. If None, we’ll use plt.gcf()

  • target – Target figure to publish this revision under. Can be a gf.Figure instance, an API ID, or a FindByName instance.

  • gf – GoFigure instance

  • dataframes – dictionary of dataframes to associate & publish with the figure

  • metadata – metadata (JSON) to attach to this revision

usage this will cause Jupyter to print the whole object which we don’t want. :param backend: backend to use, e.g. MatplotlibBackend. If None it will be inferred automatically based on figure type :param image_options: backend-specific params passed to backend.figure_to_bytes :param suppress_display: if used in an auto-publish hook, this will contain a callable which will suppress the display of this figure using the native IPython backend. :return: FigureRevision instance

class gofigr.jupyter.SuppressDisplayTrap[source]

Bases: object

Context manager which temporarily suspends all display traps.

gofigr.jupyter.configure(username, password, workspace=None, analysis=None, url='https://api.gofigr.io', default_metadata=None, auto_publish=True, watermark=None, annotators=(<class 'gofigr.annotators.NotebookNameAnnotator'>, <class 'gofigr.annotators.CellIdAnnotator'>, <class 'gofigr.annotators.CellCodeAnnotator'>, <class 'gofigr.annotators.SystemAnnotator'>, <class 'gofigr.annotators.PipFreezeAnnotator'>), notebook_name=None, notebook_path=None, backends=(<class 'gofigr.backends.matplotlib.MatplotlibBackend'>, <class 'gofigr.backends.plotly.PlotlyBackend'>))[source]

Configures the Jupyter plugin for use.

Parameters:
  • username – GoFigr username

  • password – GoFigr password

  • url – API URL

  • workspace – one of: API ID (string), ApiId instance, or FindByName instance

  • analysis – one of: API ID (string), ApiId instance, or FindByName instance

  • default_metadata – dictionary of default metadata values to save for each revision

  • auto_publish – if True, all figures will be published automatically without needing to call publish()

  • watermark – custom watermark instance (e.g. DefaultWatermark with custom arguments)

  • annotators – list of annotators to use. Default: DEFAULT_ANNOTATORS

  • notebook_name – name of the notebook (if you don’t want it to be inferred automatically)

  • notebook_path – path to the notebook (if you don’t want it to be inferred automatically)

  • backends – backends to use (e.g. MatplotlibBackend, PlotlyBackend)

Returns:

None

gofigr.jupyter.find_workspace_by_name(gf, search)[source]

Finds a workspace by name.

Parameters:
  • gf – GoFigr client

  • search – FindByName instance

Returns:

a Workspace object

gofigr.jupyter.from_config_or_env(env_prefix, config_path)[source]

Decorator that binds function arguments in order of priority (most important first): 1. args/kwargs 2. environment variables 3. config file 4. function defaults

Parameters:
  • env_prefix – prefix for environment variables. Variables are assumed to be named <prefix> + <name of function argument in all caps>, e.g. if prefix is MYAPP and function argument is called host_name, we’ll look for an environment variable named MYAPP_HOST_NAME.

  • config_path – path to the JSON config file. Function arguments will be looked up using their verbatim names.

Returns:

decorated function

gofigr.jupyter.get_extension()[source]

Returns the GoFigr Jupyter extension instance

gofigr.jupyter.get_gofigr()[source]

Gets the active GoFigr object.

gofigr.jupyter.listener_callback(result)[source]

WebSocket callback

gofigr.jupyter.parse_model_instance(model_class, value, find_by_name)[source]

Parses a model instance from a value, e.g. the API ID or a name.

Parameters:
  • model_class – class of the model, e.g. gf.Workspace

  • value – value to parse into a model instance

  • find_by_name – callable to find the model instance by name

Returns:

model instance

gofigr.jupyter.parse_uuid(val)[source]

Attempts to parse a UUID, returning None if input is not a valid UUID.

Parameters:

val – value to parse

Returns:

UUID (as a string) or None

gofigr.jupyter.publish(fig=None, backend=None, **kwargs)[source]

Publishes a figure. See gofigr.jupyter.Publisher.publish() for a list of arguments. If figure and backend are both None, will publish default figures across all available backends.

Parameters:
  • fig – figure to publish

  • backend – backend to use

  • kwargs

Returns:

gofigr.jupyter.require_configured(func)[source]

Decorator which throws an exception if configure() has not been called yet.

Parameters:

func

Returns:

gofigr.models module

Copyright (c) 2022, Flagstaff Solutions, LLC All rights reserved.

class gofigr.models.CodeData(contents=None, **kwargs)[source]

Bases: Data

Serialized code data (it’s text, but stored and transmitted as bytes)

DATA_TYPE = 'code'
property contents

Code contents.

Returns:

encoding

Field which is embedded inside the JSON metadata

format

Field which is embedded inside the JSON metadata

language

Field which is embedded inside the JSON metadata

class gofigr.models.CodeLanguage[source]

Bases: ABC

For code data objects, the programming language of the embedded code.

PYTHON = 'Python'
R = 'R'
class gofigr.models.Data(**kwargs)[source]

Bases: NestedMixin

Represents binary data (e.g. image data, serialized dataframes, etc.)

DATA_TYPE = None
FIELDS = ['api_id', 'name', 'type', 'metadata', 'data']
SPECIALIZED_TYPES = None
classmethod from_json(data)[source]

Parses a data object from JSON.

Parameters:

data – JSON object

Returns:

a specialized Data instance, e.g. ImageData

classmethod specialized_types()[source]

Lists all available Data subclasses, e.g. ImageData and CodeData

Returns:

map of data type to specialized class

to_json()[source]

Converts this data object to JSON. Data will be base-64 encoded.

Returns:

class gofigr.models.DataType[source]

Bases: ABC

Enum for different types of data we can store inside a FigureRevision.

CODE = 'code'
DATA_FRAME = 'dataframe'
IMAGE = 'image'
TEXT = 'text'
class gofigr.models.Field(name, parent=None, derived=False)[source]

Bases: object

Describes a dynamically created object field, i.e. figure name, revision etc.

clone()[source]

Creates a clone of this field.

Returns:

cloned field

to_internal_value(gf, data)[source]

Parses the value of this field from JSON primitives.

Parameters:
  • gf – GoFigr instance

  • data – parsed JSON primitives

Returns:

parsed value

to_representation(value)[source]

Converts the value of this field to a JSON-serializable primitive

class gofigr.models.ImageData(**kwargs)[source]

Bases: Data

Binary image data

DATA_TYPE = 'image'
format

Field which is embedded inside the JSON metadata

property image

Returns this image as a PIL.Image object.

Returns:

PIL.Image

property is_interactive

True if this figure is interactive, false otherwise

is_watermarked

Field which is embedded inside the JSON metadata

class gofigr.models.JSONField(name, parent=None, derived=False)[source]

Bases: Field

Represents a field that stores JSON primitives.

clone()[source]

Creates a clone of this field.

Returns:

cloned field

to_internal_value(gf, data)[source]

Parses the value of this field from JSON primitives.

Parameters:
  • gf – GoFigr instance

  • data – parsed JSON primitives

Returns:

parsed value

to_representation(value)[source]

Converts the value of this field to a JSON-serializable primitive

class gofigr.models.LinkSharingStatus(enabled)[source]

Bases: NestedMixin

Stores the status of link sharing for shareable objects.

classmethod from_json(data)[source]

Parses this object from JSON

to_json()[source]

Converts this object to JSON

class gofigr.models.LinkedEntityCollection(entities, read_only=False, backlink_property=None, backlink=None)[source]

Bases: object

Represents a collection of linked entities, i.e. figures inside an analysis

create(new_obj)[source]

Creates a new object and appends it to the collection.

Parameters:

new_obj – object to create

Returns:

created object

find(**kwargs)[source]

Returns the first object whose attributes match the query. E.g. find(name=’hello’, age=21) will return all objects where obj.name == “hello” and obj.age == 21.

Parameters:

kwargs – query

Returns:

first object that matches the query or None

find_or_create(default_obj=None, **kwargs)[source]

Finds an object that matches query parameters. If the object doesn’t exist, it will persist default_obj and return it instead.

Parameters:
  • default_obj – object to create/persist if no matches are found

  • kwargs – query parameters. See .find()

Returns:

found or created object.

class gofigr.models.LinkedEntityField(name, entity_type, lazy, many=False, read_only=False, backlink_property=None, parent=None, derived=False, sort_key=None, prefetched=False)[source]

Bases: Field

Represents a linked entity (or a collection of them), e.g. an Analysis inside a Workspace.

clone()[source]

Creates a clone of this field.

Returns:

cloned field

to_internal_value(gf, data)[source]

Parses the value of this field from JSON primitives.

Parameters:
  • gf – GoFigr instance

  • data – parsed JSON primitives

Returns:

parsed value

to_representation(value)[source]

Converts the value of this field to a JSON-serializable primitive

class gofigr.models.LogItem(username, timestamp, action, target_id, target_type, deleted_sentinel=None, deleted=False, thumbnail=None, target_name=None, analysis_id=None, analysis_name=None, api_id=None, gf=None, parent=None)[source]

Bases: NestedMixin

Represents an activity item, such as a figure being created or modified.

fetch()[source]

Fetches information about this log item from the server. API ID and parent have to be set.

classmethod from_json(data, gf=None, parent=None)[source]

Parses this object from JSON

to_json()[source]

Converts this object to JSON

class gofigr.models.LogsMixin[source]

Bases: object

Mixin for entities which support the /log/ endpoint.

get_logs()[source]

Retrieves the activity log.

Returns:

list of LogItem objects.

class gofigr.models.MetadataProxy(name, default=None)[source]

Bases: object

Field which is embedded inside the JSON metadata

class gofigr.models.ModelMixin(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ABC

Base class for GoFigr API entities: workspaces, analyses, figures, etc.

property client

Returns the underlying GoFigr instance

create(update=False)[source]

Creates this object on the server.

Parameters:

update – if True and the object already exists, its properties will be updated on the server. Otherwise

trying to create an object which already exists will throw an exception.

Returns:

self

delete(**kwargs)[source]

Deletes an object on the server. This cannot be undone.

Parameters:

kwargs – specify delete=True to actually delete the object.

Returns:

endpoint = None
fetch()[source]

Updates all fields from the server. Note that any unsaved local changes will be overwritten.

Returns:

self

fields = ['api_id']
classmethod list()[source]

Lists all objects from the server.

save(create=False, patch=False, silent=False)[source]

Saves this object to server

Parameters:
  • create – will create the object if it doesn’t aleady exist. Otherwise, saving a non-existing object will throw an exception.

  • patch – if True, will submit a partial update where some required properties may be missing. You will almost never use this: it’s only useful if for some reason you can’t/don’t want to fetch the full object before updating properties. However, the web app relies on this functionality so it’s available.

  • silent – if True, the server will not generate an activity for this update.

Returns:

self

to_json(include_derived=True, include_none=False)[source]

Serializes this model to JSON primitives.

Parameters:
  • include_derived – if True, derived fields will be included in the representation

  • include_none – if True, fields set to None will be included in the representation

Returns:

this object (and all nested/referenced fields) serialized to JSON primitives.

class gofigr.models.NestedEntityField(name, entity_type, many=False, read_only=False, derived=False, parent=None)[source]

Bases: Field

Represents a nested entity. Nested entities are embedded fully in the parent object’s JSON representation and cannot be manipulated on their own.

clone()[source]

Creates a clone of this field.

Returns:

cloned field

to_internal_value(gf, data)[source]

Parses the value of this field from JSON primitives.

Parameters:
  • gf – GoFigr instance

  • data – parsed JSON primitives

Returns:

parsed value

to_representation(value)[source]

Converts the value of this field to a JSON-serializable primitive

class gofigr.models.NestedMixin[source]

Bases: ABC

Nested objects: these are not standalone (cannot be manipulated based on API ID), but are directly embedded inside other objects.

classmethod from_json(data)[source]

Parses this object from JSON

to_json()[source]

Converts this object to JSON

class gofigr.models.Recents(analyses, figures)

Bases: tuple

analyses

Alias for field number 0

figures

Alias for field number 1

class gofigr.models.ShareableModelMixin(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ModelMixin

Mixins for things we can share: analyses, figures, revisions, etc.

Gets current status of link sharing

Returns:

true if link sharing is enabled, false otherwise.

get_sharing_users()[source]

Gets a list of all users with whom this object has been shared.

Returns:

list of SharingUserData objects.

Enabled or disables link sharing.

Parameters:

enabled – true to enable, false to disable.

Returns:

confirmation of link sharing status (true or false)

share(username)[source]

Shares this object with a specific user.

Parameters:

username – name of the user to share with.

Returns:

SharingUserData object

unshare(username)[source]

Unshares this object from a user.

Parameters:

username – username of a user from whom to remove access

Returns:

SharingUserData

class gofigr.models.SharingUserData(username, sharing_enabled)[source]

Bases: NestedMixin

Stores information about a user that an object has been shared with

classmethod from_json(data)[source]

Parses this object from JSON

to_json()[source]

Converts this object to JSON

class gofigr.models.TableData(dataframe=None, **kwargs)[source]

Bases: Data

Serialized data frame

DATA_TYPE = 'dataframe'
property dataframe

Parses the dataframe from the embedded stream of bytes.

Returns:

encoding

Field which is embedded inside the JSON metadata

format

Field which is embedded inside the JSON metadata

class gofigr.models.TextData(contents=None, **kwargs)[source]

Bases: Data

Serialized text data (even though it’s text, we store and transmit bytes)

DATA_TYPE = 'text'
property contents

Decoded text (a string)

encoding

Field which is embedded inside the JSON metadata

class gofigr.models.Timestamp(name, parent=None, derived=False)[source]

Bases: Field

Timestamp field

clone()[source]

Creates a clone of this field.

Returns:

cloned field

to_internal_value(gf, data)[source]

Parses the value of this field from JSON primitives.

Parameters:
  • gf – GoFigr instance

  • data – parsed JSON primitives

Returns:

parsed value

to_representation(value)[source]

Converts the value of this field to a JSON-serializable primitive

class gofigr.models.WorkspaceMember(username, membership_type)[source]

Bases: NestedMixin

Stores information about a member of a workspace

classmethod from_json(data)[source]

Parses this object from JSON

to_json()[source]

Converts this object to JSON

class gofigr.models.WorkspaceMembership[source]

Bases: ABC

Enum for levels of workspace membership: owner, viewer, etc.

ADMIN = 'admin'
ALL_LEVELS = ['owner', 'admin', 'creator', 'viewer']
CREATOR = 'creator'
OWNER = 'owner'
VIEWER = 'viewer'
class gofigr.models.WorkspaceType[source]

Bases: ABC

Enum for workspace type

PRIMARY = 'primary'
SECONDARY = 'secondary'
class gofigr.models.gf_Analysis(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ShareableModelMixin, LogsMixin

Represents an analysis

endpoint = 'analysis/'
fields = ['api_id', 'name', 'description', 'size_bytes', <gofigr.models.LinkedEntityField object>, <gofigr.models.LinkedEntityField object>, 'created_by', <gofigr.models.Timestamp object>, 'updated_by', <gofigr.models.Timestamp object>, 'child_updated_by', <gofigr.models.Timestamp object>]
get_figure(name, create=True, **kwargs)[source]

Finds a figure by name, optionally creating it.

Parameters:
  • name – name of the figure to find

  • create – True to create the figure if it doesn’t exist.

  • kwargs – parameters to Figure (e.g. description) if it needs to be created

Returns:

Figure instance

class gofigr.models.gf_Figure(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ShareableModelMixin

Represents a figure

endpoint = 'figure/'
fields = ['api_id', 'name', 'description', 'size_bytes', <gofigr.models.LinkedEntityField object>, <gofigr.models.LinkedEntityField object>, 'created_by', <gofigr.models.Timestamp object>, 'updated_by', <gofigr.models.Timestamp object>, 'child_updated_by', <gofigr.models.Timestamp object>]
class gofigr.models.gf_Revision(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ShareableModelMixin

Represents a figure revision

property code_data

Returns only code data (if any)

endpoint = 'revision/'
fields = ['api_id', 'revision_index', 'size_bytes', <gofigr.models.JSONField object>, <gofigr.models.LinkedEntityField object>, <gofigr.models.NestedEntityField object>, 'created_by', <gofigr.models.Timestamp object>, 'updated_by', <gofigr.models.Timestamp object>]
property image_data

Returns only image data (if any)

property revision_url

Returns the GoFigr URL for this revision

property table_data

Returns only DataFrame data (if any)

property text_data

Returns only text data (if any)

class gofigr.models.gf_Workspace(api_id=None, lazy=False, parse=False, **kwargs)[source]

Bases: ModelMixin, LogsMixin

Represents a workspace

add_member(username, membership_type)[source]

Adds a member to this workspace.

Parameters:
  • username – username of the person to add

  • membership_type – WorkspaceMembership value, e.g. WorkspaceMembership.CREATOR

Returns:

WorkspaceMember instance

change_membership(username, membership_type)[source]

Changes the membership level for a user.

Parameters:
  • username – username

  • membership_type – new membership type, e.g. WorkspaceMembership.CREATOR

Returns:

WorkspaceMember instance

endpoint = 'workspace/'
fields = ['api_id', 'name', 'description', 'workspace_type', 'size_bytes', <gofigr.models.LinkedEntityField object>, 'created_by', <gofigr.models.Timestamp object>, 'updated_by', <gofigr.models.Timestamp object>, 'child_updated_by', <gofigr.models.Timestamp object>]
get_analysis(name, create=True, **kwargs)[source]

Finds an analysis by name.

Parameters:
  • name – name of the analysis

  • create – whether to create an analysis if one doesn’t exist

  • kwargs – if an Analysis needs to be created, parameters of the Analysis object (such as description)

Returns:

Analysis instance.

get_members()[source]

Gets members of this workspace.

Returns:

list of WorkspaceMember objects

get_recents(limit=100)[source]

Gets the most recently created or modified analyses & figures.

Parameters:

limit – maximum number of elements to retrieve.

Returns:

Instance of the Recents object

remove_member(username)[source]

Removes a member from this workspace.

Parameters:

username – username

Returns:

WorkspaceMember instance

gofigr.watermarks module

Copyright (c) 2022, Flagstaff Solutions, LLC All rights reserved.

class gofigr.watermarks.DefaultWatermark(show_qr_code=True, margin_px=10, qr_background=(0, 0, 0, 0), qr_foreground=(0, 0, 0, 153), qr_scale=2, font=None)[source]

Bases: object

Draws QR codes + URL watermark on figures.

apply(image, revision)[source]

Adds a QR watermark to an image.

Parameters:
  • image – PIL.Image

  • revision – instance of FigureRevision

Returns:

PIL.Image containing the watermarked image

draw_identifier(text)[source]

Draws the GoFigr identifier text, returning it as a PIL image

get_watermark(revision)[source]

Generates just the watermark for a revision.

Parameters:

revision – FigureRevision

Returns:

PIL.Image

class gofigr.watermarks.Watermark[source]

Bases: object

Base class for drawing watermaks on figures.

apply(image, revision)[source]

Places a watermark on an image

Parameters:
  • image – PIL Image object

  • revision – GoFigr revision object

gofigr.watermarks.add_margins(img, margins)[source]

Adds margins to an image

gofigr.watermarks.stack_horizontally(*images, alignment='center')[source]

Stacks images horizontally. Thanks, Stack Overflow!

https://stackoverflow.com/questions/30227466/combine-several-images-horizontally-with-python

gofigr.watermarks.stack_vertically(*images, alignment='center')[source]

Stacks images vertically.

Module contents

Copyright (c) 2022, Flagstaff Solutions, LLC All rights reserved.

class gofigr.GoFigr(username, password, url='https://api.gofigr.io', authenticate=True)[source]

Bases: object

The GoFigr client. Handles all communication with the API: authentication, figure creation and manipulation, sharing, retrieval of user information, etc.

property api_url

Full URL to the API endpoint.

property app_url

Returns the URL to the GoFigr app

authenticate()[source]

Authenticates with the API.

Returns:

True

heartbeat(throw_exception=True)[source]

Checks whether we can communicate with the API. Currently, this works by polling /api/v1/info.

Parameters:

throw_exception – throw an exception if response code is not 200

Returns:

Response

property jwt_url

Full URL to the JWT endpoint (for authentication).

property primary_workspace

Returns the primary workspace for this user.

Returns:

Workspace instance

update_user_info(user_info, username=None)[source]

Updates user information for a user.

Parameters:
  • user_info – UserInfo instance

  • username – optional username. This is for testing only – you will get an error if attempting to update information for anybody other than yourself.

Returns:

refreshed UserInfo from server

user_info(username=None)[source]

Retrieves information about a user.

Parameters:

username – username. Set to None for self.

Returns:

UserInfo object.

property workspaces

Returns a list of all workspaces that the current user is a member of.

exception gofigr.UnauthorizedError[source]

Bases: RuntimeError

Thrown if user doesn’t have permissions to perform an action.

class gofigr.UserInfo(username, first_name, last_name, email, date_joined, is_active, avatar)[source]

Bases: object

Stores basic information about a user: username, email, etc.

static from_json(obj)[source]

Parses a UserInfo object from JSON

Parameters:

obj – JSON representation

Returns:

UserInfo instance

to_json()[source]

Converts this UserInfo object to json

gofigr.assert_one(elements, error_none=None, error_many=None)[source]

Asserts that a list/tuple contains only a single element (raising an exception if not), and returns that element.

Parameters:
  • elements – list/tuple

  • error_none – error message if input is empty

  • error_many – error message if multiple elements are present

Returns:

the single element in the input

gofigr.load_ipython_extension(ip)[source]

Loads the Jupyter extension. Present here so that we can do “%load_ext gofigr” without having to refer to a subpackage.

Parameters:

ip – IPython shell

Returns:

None