Skip to content

Commit

Permalink
refence this brazil-data-cube#14
Browse files Browse the repository at this point in the history
  • Loading branch information
fabianazioti committed Mar 16, 2020
1 parent 8473deb commit a419284
Show file tree
Hide file tree
Showing 7 changed files with 354 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lccs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#

"""Python Client Library for the LCCS Web Service."""

from .class_system import ClassSystem
from .classes import ClassSystemClass, ClassSystemClasses
from .lccs import lccs
from .link import Link
from .mappings import Mappings
from .utils import Utils
from .version import __version__

__all__ = ('__version__', )
__all__ = ('__version__', 'lccs', )
56 changes: 56 additions & 0 deletions lccs/class_system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#
# This file is part of Python Client Library for the LCCS Web Service.
# Copyright (C) 2019 INPE.
#
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python Client Library for the LCCS Web Service."""

from .classes import ClassSystemClass, ClassSystemClasses
from .link import Link
from .utils import Utils


class ClassSystem(dict):
"""Classification Systems."""

def __init__(self, data, validate=False):
"""Initialize instance with dictionary data.
:param data: Dict with class system metadata.
:param validate: true if the Class System should be validate using its jsonschema. Default is False.
"""
self._validate = validate
super(ClassSystem, self).__init__(data or {})

@property
def links(self):
""":return: a list of link in the class system."""
return [Link(link) for link in self['links']]

@property
def description(self):
""":return: description of class system."""
return self['description']

@property
def name(self):
""":return: name of class system."""
return self['name']

@property
def id(self):
""":return: id of class system."""
return self['id']

def classes(self, class_id=None, filter=None):
""":return: Classes from the class system."""
for link in self['links']:
if link['rel'] == 'classes':
if class_id is not None:
data = Utils._get('{}/{}'.format(link["href"], class_id))
return ClassSystemClass(data, self._validate)
data = Utils._get(link['href'], params=filter)
return ClassSystemClasses(data).get_class
return ClassSystemClasses({})
60 changes: 60 additions & 0 deletions lccs/classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#
# This file is part of Python Client Library for the LCCS Web Service.
# Copyright (C) 2019 INPE.
#
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python Client Library for the LCCS Web Service."""
from .utils import Utils


class ClassSystemClass(dict):
"""Class."""

def __init__(self, data, validate=False):
"""Initialize instance with dictionary data.
:param data: Dict with Class metadata.
:param validate: true if the Class should be validate using its jsonschema. Default is False.
"""
self._validate = validate
super(ClassSystemClass, self).__init__(data or {})

@property
def id(self):
""":return: the Class id."""
return self['id']

@property
def description(self):
""":return: the Class description."""
return self['description']

@property
def name(self):
""":return: the Class identifier (name)."""
return self['name']

@property
def code(self):
""":return: the Class code."""
return self['code']


class ClassSystemClasses(dict):
"""Classifications System Classes."""

def __init__(self, data, validate=False):
"""Initialize instance with dictionary data.
:param data: Dict with Classes metadata.
:param validate: true if the Classes should be validate using its jsonschema. Default is False.
"""
self._validate = validate
super(ClassSystemClasses, self).__init__(data or {})

@property
def get_class(self):
""":return: list of classes."""
return [ClassSystemClass(Utils._get(i['href'], self._validate), self._validate) for i in self['links'] if (i['rel'] == 'child')]
102 changes: 102 additions & 0 deletions lccs/lccs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#
# This file is part of Land Cover Classification System Web Service.
# Copyright (C) 2019 INPE.
#
# Land Cover Classification System Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python API client wrapper for LCCS-WS."""

from .class_system import ClassSystem
from .mappings import Mappings
from .utils import Utils


class lccs:
"""This class implements a Python API client wrapper for LCCS.
See https://github.com/brazil-data-cube/lccs-ws for more
information on LCCS.
:param url: The LCCS server URL.
:type url: str
"""

def __init__(self, url, validate=False):
"""Create a LCCS-WS client attached to the given host address (an URL)."""
self._url = url if url[-1] != '/' else url[0:-1]
self._class_systems = {}
self._validate = validate

@property
def get_classification_systems(self):
"""Return the Classification Systems avaliable in service."""
if len(self._class_systems) > 0:
return self._class_systems.keys()

url = '{}/classification_systems'.format(self._url)

for i in (ClassSystem(Utils._get(url), self._validate)).links:
if i.rel == 'child':
self._class_systems[i.href.split('/')[-1]] = None

return self._class_systems.keys()

def classification_systems(self):
""":return classification systems names available."""
if self.get_classification_systems:
pass
return self._class_systems.keys()

def classification_system(self, system_id):
"""Return the given classification_system.
:param system_id: A str for a given classification_systems_id.
:type system_id: str
:returns: A Classification System.
:rtype: dict
"""
if system_id in self._class_systems.keys() and self._class_systems[system_id] is not None:
return self._class_systems[system_id]
try:
data = Utils._get('{}/classification_systems/{}'.format(self._url, system_id))
self._class_systems[system_id] = ClassSystem(data, self._validate)
except Exception:
raise KeyError('Could not retrieve information for classification_system: {}'.format(system_id))
return self._class_systems[system_id]

def mappings(self, system_id_source, system_id_target):
"""Return the given classification_system.
:param system_id_source: A str for a given system_id_source.
:type system_id_source: str
:param system_id_target: A str for a given system_id_source.
:type system_id_target: str
:returns: Mappings of classification Systems.
:rtype: list
"""
result = list()
try:
data = Utils._get('{}/mappings/{}/{}'.format(self._url, system_id_source, system_id_target))
except Exception:
raise KeyError('Could not retrieve mappings for {} and {}'.format(system_id_source, system_id_target))

[result.append(Mappings(i, self._validate)) for i in data]

return result

@property
def url(self):
"""Return the LCSS server instance URL."""
return self._url

def __repr__(self):
"""Return the string representation of a lccs object."""
text = 'lccs("{}")'.format(self.url)
return text

def __str__(self):
"""Return the string representation of a lccs object."""
return '<LCCS [{}]>'.format(self.url)
39 changes: 39 additions & 0 deletions lccs/link.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#
# This file is part of Land Cover Classification System Web Service.
# Copyright (C) 2019 INPE.
#
# Land Cover Classification System Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python API client wrapper for LCCS-WS."""


class Link(dict):
"""Link object."""

def __init__(self, data):
"""Initialize instance with dictionary data.
:param data: Dict with Link metadata.
"""
super(Link, self).__init__(data or {})

@property
def rel(self):
""":return: the Link relation."""
return self['rel']

@property
def href(self):
""":return: the Link url."""
return self['href']

@property
def type(self):
""":return: the type of the Link object."""
return self['type']

@property
def title(self):
""":return: the title of the Link object."""
return self['title']
52 changes: 52 additions & 0 deletions lccs/mappings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#
# This file is part of Python Client Library for the LCCS Web Service.
# Copyright (C) 2019 INPE.
#
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python Client Library for the LCCS Web Service."""
from .class_system import ClassSystemClass
from .utils import Utils


class Mappings(dict):
"""Mappings."""

def __init__(self, data, validate=False):
"""Initialize instance with dictionary data.
:param data: Dict with Classes metadata.
:param validate: true if the Classes should be validate using its jsonschema. Default is False.
"""
self._validate = validate
super(Mappings, self).__init__(data or {})

@property
def degree_of_similarity(self):
""":return: the degree_of_similarity."""
return self['degree_of_similarity']

@property
def description(self):
""":return: the Class description."""
return self['description']

@property
def link(self):
""":return: the Class identifier (name)."""
return self['links']

@property
def source_class(self):
""":return: the Class code."""
for i in self['links']:
if i['rel'] == 'source_class':
return ClassSystemClass(Utils._get(i['href'], self._validate))

@property
def target_class(self):
""":return: the Class code."""
for i in self['links']:
if i['rel'] == 'target_class':
return ClassSystemClass(Utils._get(i['href'], self._validate))
38 changes: 38 additions & 0 deletions lccs/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#
# This file is part of Python Client Library for the LCCS Web Service.
# Copyright (C) 2019 INPE.
#
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Python Client Library for the LCCS Web Service."""
import requests


class Utils:
"""Utils class."""

@staticmethod
def _get(url, params=None):
"""Query the STAC service using HTTP GET verb and return the result as a JSON document.
:param url: The URL to query must be a valid STAC endpoint.
:type url: str
:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the underlying `Requests`.
:type params: dict
:rtype: dict
:raises ValueError: If the response body does not contain a valid json.
"""
response = requests.get(url, params=params)

response.raise_for_status()

content_type = response.headers.get('content-type')

if content_type not in ('application/json', 'application/geo+json'):
raise ValueError('HTTP response is not JSON: Content-Type: {}'.format(content_type))

return response.json()

0 comments on commit a419284

Please sign in to comment.