Nemo API

class flask_nemo.Nemo(name=None, app=None, base_url='/nemo', cache=None, resolver=None, plugins=None, template_folder=None, static_folder=None, static_url_path=None, urls=None, transform=None, chunker=None, css=None, js=None, templates=None, statics=None, prevent_plugin_clearing_assets=False, original_breadcrumb=True, default_lang='eng')[source]

Nemo is an extension for Flask python micro-framework which provides a User Interface to your app for dealing with CTS API.

Parameters:
  • app (Flask) – Flask application
  • resolver (MyCapytain.resolvers.prototypes.Resolver) – MyCapytain resolver
  • base_url (str) – Base URL to use when registering the endpoint
  • cache (flask_caching.Cache) – Flask-Caching instance or any object having a memoize decorator
  • plugins (list(flask_nemo.plugin.PluginPrototype)) – List of plugins to connect to the Nemo instance
  • template_folder (str) – Folder in which the full set of main namespace templates can be found
  • static_folder (str) – Folder in which statics file can be found
  • static_url_path (str) – Base url to use for assets
  • urls ([(str, str, [str])]) – Function and routes to register (See Nemo.ROUTES)
  • transform (bool|dict) – Dictionary of XSL filepath or transform function where default key is the default applied function
  • chunker ({str: function(str, function(int))}) – Dictionary of function to group responses of GetValidReff
  • css ([str]) – Path to additional stylesheets to load
  • js ([str]) – Path to additional javascripts to load
  • templates ({str: str}) – Register or override templates (Dictionary of namespace / directory containing template)
  • statics ([str]) – Path to additional statics such as picture to load
  • prevent_plugin_clearing_assets (bool) – Prevent plugins to clear the static folder route
  • original_breadcrumb (bool) – Use the default Breadcrumb plugin packaged with Nemo (Default: True)
  • default_lang (str) – Default lang to fall back to
Variables:
  • assets – Dictionary of assets loaded individually
  • plugins – List of loaded plugins
  • resolver – Resolver
  • cached – List of cached functions
  • cache – Cache Instance

Warning

Until a C libxslt error is fixed ( https://bugzilla.gnome.org/show_bug.cgi?id=620102 ), it is not possible to use strip spaces in the xslt given to this application. See strip-spaces

Controller

Specific methods

Nemo.get_inventory()[source]

Request the api endpoint to retrieve information about the inventory

Returns:Main Collection
Return type:Collection
Nemo.get_collection(objectId)[source]

Retrieve a collection in the inventory

Parameters:objectId (str) – Collection Identifier
Returns:Requested collection
Return type:Collection
Nemo.get_siblings(objectId, subreference, passage)[source]

Get siblings of a browsed subreference

Note

Since 1.0.0c, there is no more prevnext dict. Nemo uses the list of original chunked references to retrieve next and previous, or simply relies on the resolver to get siblings when the subreference is not found in given original chunks.

Parameters:
  • objectId – Id of the object
  • subreference – Subreference of the object
  • passage – Current Passage
Returns:

Previous and next references

Return type:

(str, str)

Nemo.get_reffs(objectId, subreference=None, collection=None, export_collection=False)[source]

Retrieve and transform a list of references.

Returns the inventory collection object with its metadata and a callback function taking a level parameter and returning a list of strings.

Parameters:
  • objectId (str) – Collection Identifier
  • subreference (str) – Subreference from which to retrieve children
  • collection (Collection) – Collection object bearing metadata
  • export_collection (bool) – Return collection metadata
Returns:

Returns either the list of references, or the text collection object with its references as tuple

Return type:

(Collection, [str]) or [str]

Nemo.get_passage(objectId, subreference)[source]

Retrieve the passage identified by the parameters

Parameters:
  • objectId (str) – Collection Identifier
  • subreference (str) – Subreference of the passage
Returns:

An object bearing metadata and its text

Return type:

InteractiveTextualNode

Customization appliers

Nemo.chunk(text, reffs)[source]

Handle a list of references depending on the text identifier using the chunker dictionary.

Parameters:
  • text (MyCapytains.resources.texts.api.Text) – Text object from which comes the references
  • reffs (References) – List of references to transform
Returns:

Transformed list of references

Return type:

[str]

Nemo.transform(work, xml, objectId, subreference=None)[source]

Transform input according to potentially registered XSLT

Note

Since 1.0.0, transform takes an objectId parameter which represent the passage which is called

Note

Due to XSLT not being able to be used twice, we rexsltise the xml at every call of xslt

Warning

Until a C libxslt error is fixed ( https://bugzilla.gnome.org/show_bug.cgi?id=620102 ), it is not possible to use strip tags in the xslt given to this application

Parameters:
  • work (MyCapytains.resources.inventory.Text) – Work object containing metadata about the xml
  • xml (etree._Element) – XML to transform
  • objectId (str) – Object Identifier
  • subreference (str) – Subreference
Returns:

String representation of transformed resource

Return type:

str

Shared methods

Nemo.render(template, **kwargs)[source]

Render a route template and adds information to this route.

Parameters:
  • template (str) – Template name.
  • kwargs (dict) – dictionary of named arguments used to be passed to the template
Returns:

Http Response with rendered template

Return type:

flask.Response

Nemo.view_maker(name, instance=None)[source]

Create a view

Parameters:name (str) – Name of the route function to use for the view.
Returns:Route function which makes use of Nemo context (such as menu informations)
Return type:function
Nemo.route(fn, **kwargs)[source]

Route helper : apply fn function but keep the calling object, ie kwargs, for other functions

Parameters:
  • fn (function) – Function to run the route with
  • kwargs (dict) – Parsed url arguments
Returns:

HTTP Response with rendered template

Return type:

flask.Response

Routes

Nemo.r_index()[source]

Homepage route function

Returns:Template to use for Home page
Return type:{str: str}
Nemo.r_collection(objectId, lang=None)[source]

Collection content browsing route function

Parameters:
  • objectId (str) – Collection identifier
  • lang (str) – Lang in which to express main data
Returns:

Template and collections contained in given collection

Return type:

{str: Any}

Nemo.r_passage(objectId, subreference, lang=None)[source]

Retrieve the text of the passage

Parameters:
  • objectId (str) – Collection identifier
  • lang (str) – Lang in which to express main data
  • subreference (str) – Reference identifier
Returns:

Template, collections metadata and Markup object representing the text

Return type:

{str: Any}

Nemo.r_assets(filetype, asset)[source]

Route for specific assets.

Parameters:
  • filetype – Asset Type
  • asset – Filename of an asset
Returns:

Response

Statics

Filters

Filters follow a naming convention : they should always start with f_

filters.f_formatting_passage_reference(string)

Get the first part only of a two parts reference

Parameters:string (str) – A urn reference part
Returns:First part only of the two parts reference
Return type:str
filters.f_i18n_citation_type(string, lang='eng')

Take a string of form %citation_type|passage% and format it for human

Parameters:
  • string – String of formation %citation_type|passage%
  • lang – Language to translate to
Returns:

Human Readable string

Note

To Do : Use i18n tools and provide real i18n

filters.f_is_str(value)

Check if object is a string

Parameters:value – object to check against
Returns:Return if value is a string
filters.f_annotation_filter(annotations, type_uri, number)

Annotation filtering filter

Parameters:
  • annotations ([AnnotationResource]) – List of annotations
  • type_uri (str) – URI Type on which to filter
  • number (int) – Number of the annotation to return
Returns:

Annotation(s) matching the request

Return type:

[AnnotationResource] or AnnotationResource

Helpers

Chunkers

chunker.default_chunker(text, getreffs)

This is the default chunker which will resolve the reference giving a callback (getreffs) and a text object with its metadata

Parameters:
  • text (MyCapytains.resources.inventory.Text) – Text Object representing either an edition or a translation
  • getreffs (function) – callback function which retrieves a list of references
Returns:

List of urn references with their human readable version

Return type:

[(str, str)]

chunker.line_chunker(text, getreffs, lines=30)

Groups line reference together

Parameters:
  • text (MyCapytains.resources.text.api) – Text object
  • getreffs (function(level)) – Callback function to retrieve text
  • lines (int) – Number of lines to use by group
Returns:

List of grouped urn references with their human readable version

Return type:

[(str, str)]

chunker.scheme_chunker(text, getreffs)

This is the scheme chunker which will resolve the reference giving a callback (getreffs) and a text object with its metadata

Parameters:
  • text (MyCapytains.resources.inventory.Text) – Text Object representing either an edition or a translation
  • getreffs (function) – callback function which retrieves a list of references
Returns:

List of urn references with their human readable version

Return type:

[(str, str)]

chunker.level_grouper(text, getreffs, level=None, groupby=20)

Alternative to level_chunker: groups levels together at the latest level

Parameters:
  • text – Text object
  • getreffs – GetValidReff query callback
  • level – Level of citation to retrieve
  • groupby – Number of level to groupby
Returns:

Automatically curated references

chunker.level_chunker(text, getreffs, level=1)

Chunk a text at the passage level

Parameters:
  • text (MyCapytains.resources.text.api) – Text object
  • getreffs (function(level)) – Callback function to retrieve text
Returns:

List of urn references with their human readable version

Return type:

[(str, str)]

Plugin

class flask_nemo.plugin.PluginPrototype(name=None, namespacing=False, *args, **kwargs)[source]

Prototype for Nemo Plugins

Parameters:
  • name (str) – Name of the instance of the plugins. Defaults to the class name (Default : Plugin’s class name)
  • namespacing – Add namespace to route to avoid overwriting (Default : False)
Variables:
  • ROUTES – Routes represents the routes to be added to the Nemo instance. They take the form of a 3-tuple such as ("/read/<collection>", "r_collection", ["GET"])
  • TEMPLATES – Dictionaries of template namespaces and directory to retrieve templates in given namespace
  • FILTERS – List of filters to register. Naming convention is f_doSomething
  • HAS_AUGMENT_RENDER – Enables post-processing in view rendering function Nemo().render(template, **kwargs)
  • CLEAR_ROUTES – Removes original nemo routes
  • CLEAR_ASSETS – Removes original nemo secondary assets
  • STATIC_FOLDER – Overwrite Nemo default statics folder
  • CSS – List of CSS resources to link in and give access to if local
  • JS – List of JS resources to link in and give access to if local
  • STATIC – List of static resources (images for example) to give access to
  • CACHED – List of functions to cache
  • assets – Dictionary of assets, with each key (css, js and static) being list of resources
  • augment – If true, means that the plugin has a render method which needs to be called upon rendering the view
  • clear_routes – If true, means that the plugin requires Nemo original routes to be removed
  • clear_assets – If true, means that the plugin required Nemo original assets to be removed
  • name – Name of the plugin instance
  • static_folder – Path to the plugin own static_folder to be used instead of the Nemo default one
  • namespaced – Indicate if the plugin is namespaced or not
  • routes – List of routes where the first member is a flask URL template, the second a method name, and the third a list of accepted Methods
  • filters – List of filters method names to be registered in Nemo
  • templates – Dictionary of namespace and target directory to resolve templates name
  • nemo – Nemo instance
  • name – Name of the plugin instance
Example:
ROUTES = [
    # (Path like flask, Name of the function (convention is r_*), List of Http Methods)
    ("/read/<collection>/<textgroup>/<work>/<version>/<passage_identifier>/<visavis>", "r_double", ["GET"])
]
PluginPrototype.render(**kwargs)[source]

View Rendering function that gets triggered before nemo renders the resources and adds informations to pass to the templates

Parameters:kwargs – Dictionary of arguments to pass to the template
Returns:Dictionary of arguments to pass to the template

Default Plugins

class flask_nemo.plugins.default.Breadcrumb(name=None, namespacing=False, *args, **kwargs)[source]

The Breadcrumb plugin is enabled by default in Nemo. It can be overwritten or removed. It simply adds a breadcrumb

Breadcrumb.render(**kwargs)[source]

Make breadcrumbs for a route

Parameters:kwargs (dict) – dictionary of named arguments used to construct the view
Returns:List of dict items the view can use to construct the link.
Return type:{str: list({ “link”: str, “title”, str, “args”, dict})}

Common

flask_nemo.common.resource_qualifier(resource)[source]

Split a resource in (filename, directory) tuple with taking care of external resources

Parameters:resource – A file path or a URI
Returns:(Filename, Directory) for files, (URI, None) for URI

Query Interfaces and Annotations

Annotations

class flask_nemo.query.annotation.AnnotationResource(uri, target, type_uri, resolver, target_class=<class 'flask_nemo.query.annotation.Target'>, mimetype=None, slug=None, **kwargs)[source]

Object representing an annotation. It encapsulates both the body (through the .read() function) and the target (through the .target method)

Parameters:
  • uri (str) – URI identifier for the AnnotationResource
  • target (Target or str or URN or tuple) – the Target of the Annotation
  • type_uri (str) – the URI identifying the underlying datatype of the Annotation
  • resolver (AnnotationResolver) – Resolver providing access to the annotation
  • target_class (class) – Alias for the Target class to be used
  • mimetype (str) – MimeType of the Annotation object
  • slug (str) – Slug type of the object
Variables:
  • mimetype – Mimetype of the annotation object
  • sha – SHA identifying the object
  • uri – Original URI of the object
  • slug – Slug Type of the Annotation Object
  • type_uri – URI of the type
  • expandable – Indication of expandability of the object
  • target – Target object of the Annotation
AnnotationResource.read()[source]

Read the contents of the Annotation Resource

Returns:the contents of the resource
Return type:str or bytes or flask.response
AnnotationResource.expand()[source]

Expand the contents of the Annotation if it is expandable (i.e. if it references multiple resources)

Returns:the list of expanded resources
Return type:list(AnnotationResource)
class flask_nemo.query.annotation.Target(objectId, subreference=None, **kwargs)[source]

Object and prototype for representing target of annotation.

Note

Target default object are URN based because that’s what Nemo is about.

Parameters:urn (MyCapytain.common.reference.URN) – URN targeted by an Annotation
Variables:urn – Target urn
Target.to_json()[source]

Method to call to get a serializable object for json.dump or jsonify based on the target

Returns:dict

Query Interfaces

Prototype

class flask_nemo.query.proto.QueryPrototype(getreffs, **kwargs)[source]

Prototype for Nemo Query API Implementations

Parameters:
  • name (str) – The Name of this Query API
  • getreffs (function) – callback function to retrieve a list of references given URN
QueryPrototype.getAnnotations(targets, wildcard='.', include=None, exclude=None, limit=None, start=1, expand=False, **kwargs)[source]

Retrieve annotations from the query provider

Parameters:
  • targets ([MyCapytain.common.reference.URN], URN or None) – The CTS URN(s) to query as the target of annotations
  • wildcard (str) – Wildcard specifier for how to match the URN
  • include (list(str)) – URI(s) of Annotation types to include in the results
  • exclude (list(str)) – URI(s) of Annotation types to include in the results
  • limit (int) – The max number of results to return (Default is None for no limit)
  • start (int) – the starting record to return (Default is 1)
  • expand (bool) – Flag to state whether Annotations are expanded (Default is False)
Returns:

Tuple representing the query results. The first element The first element is the number of total Annotations found The second element is the list of Annotations

Return type:

(int, list(Annotation)

Note

Wildcard should be one of the following value

  • ‘.’ to match exact,
  • ‘.%’ to match exact plus lower in the hierarchy
  • ‘%.’ to match exact + higher in the hierarchy
  • ‘-‘ to match in the range
  • ‘%.%’ to match all
QueryPrototype.getResource(sha)[source]

Retrieve a single annotation resource by sha

Parameters:sha (str) – The sha of the resource
Returns:the requested annotation resource
Return type:AnnotationResource

Simple Query

class flask_nemo.query.interface.SimpleQuery(annotations, resolver=None)[source]

Query Interface for hardcoded annotations.

Parameters:
  • annotations ([(str, str, str) or AnnotationResource]) – List of tuple of (CTS URN Targeted, URI of the Annotation, Type of the annotation) or/and AnnotationResources
  • resolver (Resolver) – Resolver

This interface requires to be connected to Nemo upon instantiation to expand annotations :

>>> nemo = Nemo("/", endpoint="http://cts.perseids.org")
>>> query = SimpleQuery([...])
>>> query.process(nemo)
SimpleQuery.process(nemo)[source]

Register nemo and parses annotations

Note

Process parses the annotation and extends informations about the target URNs by retrieving resource in range

Parameters:nemo – Nemo

Resolver and Retrievers

class flask_nemo.query.resolve.UnresolvableURIError[source]

Error to be run when a URI is not resolvable

class flask_nemo.query.resolve.Resolver(*retrievers, **kwargs)[source]

Prototype for a Resolver :param retriever: Retriever(s) to use to resolve resources passed to this resolver :type retriever: Retriever instances

Resolver.resolve(uri)[source]

Resolve a Resource identified by URI :param uri: The URI of the resource to be resolved :type uri: str :return: the contents of the resource as a string :rtype: str

class flask_nemo.query.resolve.RetrieverPrototype[source]

Prototype for a Retriever

RetrieverPrototype.match(uri)[source]

Check to see if this URI is retrievable by this Retriever implementation :param uri: the URI of the resource to be retrieved :type uri: str :return: True if it can be, False if not :rtype: bool

RetrieverPrototype.read(uri)[source]

Retrieve the contents of the resource :param uri: the URI of the resource to be retrieved :type uri: str :return: the contents of the resource and it’s mime type in a tuple :rtype: str, str

class flask_nemo.query.resolve.HTTPRetriever[source]

Http retriever retrieves resources being remotely hosted in CTS

HTTPRetriever.match(uri)[source]

Check to see if this URI is retrievable by this Retriever implementation

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:True if it can be, False if not
Return type:bool
HTTPRetriever.read(uri)[source]

Retrieve the contents of the resource

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:the contents of the resource
Return type:str
class flask_nemo.query.resolve.LocalRetriever(path='./')[source]

Http retriever retrieves resources being remotely hosted in CTS

Note

Local Retriever needs to be instantiated

Variables:FORCE_MATCH – Force the local retriever to read a resource even if it does not match with the regular expression
LocalRetriever.match(uri)[source]

Check to see if this URI is retrievable by this Retriever implementation

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:True if it can be, False if not
Return type:bool
LocalRetriever.read(uri)[source]

Retrieve the contents of the resource

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:the contents of the resource
Return type:str
class flask_nemo.query.resolve.CTSRetriever(resolver)[source]

CTS retriever retrieves resources being remotely hosted in CTS

Note

Local Retriever needs to be instantiated

Parameters:resolver (MyCapytain.resolver.cts.*) – CTS5 Resolver
static CTSRetriever.match(uri)[source]

Check to see if this URI is retrievable by this Retriever implementation

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:True if it can be, False if not
Return type:bool
CTSRetriever.read(uri)[source]

Retrieve the contents of the resource

Parameters:uri (str) – the URI of the resource to be retrieved
Returns:the contents of the resource
Return type:str

Plugins

AnnotationApi

class flask_nemo.plugins.annotations_api.AnnotationsApiPlugin(queryinterface, *args, **kwargs)[source]

AnnotationsApiPlugin adds routes to Nemo from which annotations can be retrieved

This plugins contains two routes only registered at

  • /api/annotations/?target=<URN Target> which is the collection in which to search
  • /api/annotations/<SHA Identifier of the annotation> is the annotation object
  • /api/annotations/<SHA Identifier of the annotation>/body is the proxy for the annotation body

The response are conform to https://www.w3.org/TR/annotation-model/#annotation-collection

Parameters:queryinterface (QueryInterface) – QueryInterface to use to retrieve annotations
AnnotationsApiPlugin.r_annotations()[source]

Route to retrieve annotations by target

Parameters:target_urn (str) – The CTS URN for which to retrieve annotations
Returns:a JSON string containing count and list of resources
Return type:{str: Any}
AnnotationsApiPlugin.r_annotation(sha)[source]

Route to retrieve contents of an annotation resource

Parameters:uri (str) – The uri of the annotation resource
Returns:annotation contents
Return type:{str: Any}
AnnotationsApiPlugin.r_annotation_body(sha)[source]

Route to retrieve contents of an annotation resource

Parameters:uri (str) – The uri of the annotation resource
Returns:annotation contents
Return type:{str: Any}