code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
# restio **restio** is a Python ORM-like framework that manages relational data coming from remote REST APIs, in a similar way that is done for databases. Some of the advantages of using **restio** in comparison with raw REST Client APIs: - Clear decoupling between models and data access logic. - Client-side caching of models and queries. - Improved performance for nearly all operations with native use of `asyncio`. - Type-checking and data validation. - Model state management. - Rich relational models and dependency management. - Fully integrated with type-hinting. [Official documentation](https://restio.readthedocs.io/en/latest/) ## Installation ### Requirements - Python 3.7+ ### Pip You can install the latest pre-release version of **restio** as a dependency to your project with pip: ```bash pip install --pre restio ``` ## Practical Example A typical REST Client API implemented with **restio** looks like the following: ```python from __future__ import annotations from typing import Dict, Any, Optional import aiohttp import json from restio.dao import BaseDAO from restio.fields import ModelField, IntField, StrField from restio.model import BaseModel from restio.session import Session # Model definition - this is where the relational data schema is defined class Employee(BaseModel): key: IntField = IntField(pk=True, allow_none=True, frozen=FrozenType.ALWAYS) name: StrField = StrField() age: IntField = IntField() address: StrField = StrField(default="Company Address") boss: ModelField[Optional[Employee]] = ModelField("Employee", allow_none=True) # Data access object definition - teaches restio how to deal with # CRUD operations for a relational model class EmployeeDAO(BaseDAO[Employee]): client_session: aiohttp.ClientSession = aiohttp.ClientSession(raise_for_status=True) url = "http://remote-rest-api-url" async def get(self, *, key: int) -> Employee: employee_url = f"{self.url}/employees/{key}" result = await self.client_session.get(employee_url) employee_data = await result.json() # asks the current session to retrieve the boss from cache or # to reach to the remote server boss = await self.session.get(Employee, key=employee_data["boss"]) return self._map_from_dict(employee_data, boss) async def add(self, obj: Employee): employees_url = f"{self.url}/employees" payload = json.dumps(self._map_to_dict(obj)) response = await self.client_session.post(employees_url, data=payload.encode()) location = response.headers["Location"] key = location.split("/")[-1] # update the model with the key generated on the server obj.key = key @staticmethod def _map_from_dict(data: Dict[str, Any], boss: Employee) -> Employee: return Employee( key=int(data["key"]), name=str(data["name"]), age=int(data["age"]), address=str(data["address"]), boss=boss ) @staticmethod def _map_to_dict(model: Employee) -> Dict[str, Any]: return dict( name=model.name, age=model.age, address=model.address, boss=model.boss.key ) ``` Once `Models` and `Data Access Objects` (DAOs) are provided, you can use `Sessions` to operate the `Models`: ```python # instantiate the Session and register the DAOs EmployeeDAO # to deal with Employee models session = Session() session.register_dao(EmployeeDAO(Employee)) # initialize session context async with session: # retrieve John Doe's Employee model, that has a known primary key 1 john = await session.get(Employee, key=1) # Employee(key=1, name="John Doe", age=30, address="The Netherlands") # create new Employees in local memory jay = Employee(name="Jay Pritchett", age=65, address="California") manny = Employee(name="Manuel Delgado", age=22, address="Florida", boss=jay) # at the end of the context, `session.commit()` is called automatically # and changes are propagated to the server ``` ## Overview When consuming remote REST APIs, the data workflow used by applications normally differs from the one done with ORMs accessing relational databases. With databases, it is common to use transactions to guarantee atomicity when persisting data on these databases. Let's take a Django-based application example of a transaction (example is minimal, fictitious and adapted from https://docs.djangoproject.com/en/3.1/topics/db/transactions/): ```python from django.db import DatabaseError, transaction from mylocalproject.models import Person def people(): try: with transaction.atomic(): person1 = Person(name="John", age=1) person2 = Person(name="Jay", age=-1) # mistake! person1.friends.add(person2) person1.save() person2.save() except DatabaseError as err: # rollback is already done here, no garbage left on the database print(err) # Person can't have age smaller than 0 ``` For remote REST APIs, guaranteeing atomicity becomes a difficult job, as each call to the remote API should be atomic. If the same code above was to be called to a REST API client, you would typically see the following: ```python from restapiclient import ClientAPI, Person client = ClientAPI() def people(): person1: Person = client.create_person(name="John", age=1) # ok person2: Person = client.create_person(name="Jay", age=-1) # error, exit person1.friends.add(person2) client.update_person(person1) ``` In this case, not only the calls to the server are done synchronously, but the data validation of `person2` would be done too late (either by the client API or the server). Since `person1` was already added, now we have garbage left on the remote server. **restio** is designed to optimize this and other cases when interacting with REST APIs. It does it in a way that it is more intuitive for developers that are already familiar with ORMs and want to use a similar approach, with similar benefits. Please visit the [official documentation](https://restio.readthedocs.io/en/latest/) for more information.
/restio-1.0.0b5.tar.gz/restio-1.0.0b5/README.md
0.852368
0.887984
README.md
pypi
# RESTiro [![Build Status]( https://travis-ci.org/meyt/restiro.svg?branch=master )]( https://travis-ci.org/meyt/restiro ) [![Coverage Status]( https://coveralls.io/repos/github/meyt/restiro/badge.svg?branch=master )]( https://coveralls.io/github/meyt/restiro?branch=master ) RESTful API documentation generator (inline documentation + tests) ## Features - [x] Inline documentation parser - [x] Example recorder middleware - [x] Generate documentation in Markdown - [x] Generate documentation in HTML [[restiro-spa-material](https://github.com/meyt/restiro-spa-material)] ## Install ``` pip install restiro ``` ## Usage 1. Describe the request in comments, e.g: controller/shelf.py ```python class ShelfController: def post(self): """ @api {post} /shelf/:shelfId/book Add book into shelf @apiVersion 1 @apiGroup Book @apiPermission Noneres @apiParam {String} title @apiParam {String} author @apiParam {DateTime} [publishDate] @apiDescription Here is some description with full support of markdown. - watch this! - and this! - there is a list! """ return [11, 22, 33] ``` 2. Attach `restiro` middleware to your WSGI/HTTP verifier (currently `webtest` supported), e.g: Your project tests initializer: ```python from restiro.middlewares.webtest import TestApp from restiro import clean_examples_dir from my_project import wsgi_app clean_examples_dir() test_app = TestApp(wsgi_app) ``` 3. Define responses to capture, e.g: ```python def test_shelf(test_app): test_app.get('/shelf/100/book') test_app.delete('/shelf/121/book') test_app.doc = True test_app.post( '/shelf/100/book', json={ 'title': 'Harry Potter', 'author': 'JK. Rowling' } ) test_app.doc = True test_app.post( '/shelf/100/book', json={ 'title': 'Harry Potter2' }, status=400 ) ``` 4. Run tests 5. Build documentation ``` $ restiro a_library ``` Response will be something like: shelf-{shelf_id}-book-post.md ```markdown # Add book into shelf ## `POST` `/shelf/:shelfId/book` Here is some description with full support of markdown. - watch this! - and this! - there is a list! ## Parameters ### Form parameters Name | Type | Required | Default | Example | enum | Pattern | MinLength | MaxLength | Minimum | Maximum | Repeat | Description --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- title | String | `True` | | | | | | | | | `False` | author | String | `True` | | | | | | | | | `False` | publishDate | DateTime | `False` | | | | | | | | | `False` | ## Examples ### 200 OK #### Request: ``` POST /shelf/100/book Content-Type: application/x-www-form-urlencoded ``` ``` title=Harry Potter author=JK. Rowling ``` #### Response: ``` Content-Type: application/json ``` ``` [11, 22, 33] ``` ### 400 Bad Request, missed parameter `author` #### Request: ``` POST /shelf/100/book Content-Type: application/x-www-form-urlencoded ``` ``` title=Harry Potter2 ``` #### Response: ``` Content-Type: application/json ``` ``` {"message": "Missed parameter `author`"} ``` --- ``` ## CLI ``` usage: restiro [-h] [-t TITLE] [-o OUTPUT] [-b BASE_URI] [-g {markdown,json,spa_material,mock}] [-l LOCALES] [--build-gettext [BUILD_GETTEXT]] src Restiro Builder positional arguments: src Project module name optional arguments: -h, --help show this help message and exit -t TITLE, --title TITLE Project title -o OUTPUT, --output OUTPUT Output directory -b BASE_URI, --base-uri BASE_URI Base URI -g {markdown,json,spa_material,mock}, --generator {markdown,json,spa_material,mock} Generator, default: markdown -l LOCALES, --locales LOCALES Locales directory --build-gettext [BUILD_GETTEXT] Build .POT templates ```
/restiro-0.19.1.tar.gz/restiro-0.19.1/README.md
0.835618
0.830147
README.md
pypi
from restler import UnsupportedTypeError def unsupported(type_): """ Mark types for that aren't supported :param type_: Model type :return: a handler that raises and UnsupportedTypeError for that type """ def handler(obj): raise UnsupportedTypeError(type_) return handler def wrap_method(cls, method): """ Helper function to help wrap _restler* methods when more than on decorator is used on a model. :param method: method to wrap """ from copy import copy method_name = method.__func__.__name__ method_param = method if hasattr(cls, method_name): orig_cls_method = getattr(cls, method_name) @classmethod def wrap(cls_): setattr(cls, method_name, method_param) method = getattr(cls, method_name) aggregate = copy(orig_cls_method()) if isinstance(aggregate, list): # _restler_types() aggregate = set(aggregate) aggregate.update(method()) aggregate = list(aggregate) elif isinstance(aggregate, dict): # _restler_property_map aggregate.update(method()) elif isinstance(aggregate, str): # Developer shouldn't really do this, but we'll try # to do the correct thing and use the most recently defined name aggregate = method() # _restler_serialization_name return aggregate setattr(cls, method_name, wrap) else: setattr(cls, method_name, method) def create_type_map(cls, type_map=None): """ Helper function for creating type maps """ _type_map = None if type_map: if callable(type_map): _type_map = type_map(cls) else: _type_map = type_map.copy() else: _type_map = {} return _type_map def create_serialization_name(cls, serialization_name=None): """ Helper function for creating a serialization name """ _serialization_name = serialization_name if serialization_name: if callable(serialization_name): _serialization_name = serialization_name(cls) return _serialization_name def create_property_map(cls, property_map=None): """ Helper function for creating property maps """ _property_map = None if property_map: if callable(property_map): _property_map = property_map(cls) else: _property_map = property_map.copy() else: _property_map = {} return _property_map def ae_db_decorator_builder(type_map=None, serialization_name=None, property_map=None): """ Creates a decorator for google.appengine.ext.db.Model :param type_map: a map of types -> callable(value) or a callable(model) that returns a map. :param serialization_name: a (string) name used for the tag/key for serialization or a callable(model) that returns a name :param property_map: a map of (field) names (string) -> types or a callable(model) that returns a map. """ from google.appengine.ext import blobstore, db def wrap(cls): """ Restler serialization class decorator for google.appengine.ext.db.Model """ @classmethod def _restler_types(cls): """ A map of types types to callables that serialize those types. """ _type_map = create_type_map(type_map) from google.appengine.api import users from webapp2 import cached_property _type_map.update( { db.Query: lambda query: [obj for obj in query], db.GeoPt: lambda obj: "%s %s" % (obj.lat, obj.lon), db.IM: lambda obj: "%s %s" % (obj.protocol, obj.address), users.User: lambda obj: obj.user_id() or obj.email(), cached_property: lambda obj: cached_property, blobstore.BlobInfo: lambda obj: str(obj.key()) # TODO is this correct? }) return _type_map @classmethod def _restler_serialization_name(cls): """ The lowercase model classname """ _serialization_name = create_serialization_name(cls, serialization_name or cls.kind().lower()) return _serialization_name @classmethod def _restler_property_map(cls): """ List of model property names -> property types. The names are used in *include_all_fields=True* Property types must be from **google.appengine.ext.db.Property** """ _property_map = create_property_map(cls, property_map) _property_map.update(cls.properties()) return _property_map wrap_method(cls, _restler_types) wrap_method(cls, _restler_property_map) cls._restler_serialization_name = _restler_serialization_name return cls return wrap ae_db_serializer = ae_db_decorator_builder() def ae_ndb_decorator_builder(type_map=None, serialization_name=None, property_map=None): """ Restler serializationclass decorator for google.appengine.ext.ndb.Model """ from google.appengine.ext import ndb def wrap(cls): @classmethod def _restler_types(cls): """ A map of types types to callables that serialize those types. """ from google.appengine.api import users from webapp2 import cached_property _type_map = create_type_map(type_map) _type_map.update({ ndb.query.Query: lambda query: [obj for obj in query], ndb.ComputedProperty: unsupported(ndb.ComputedProperty), ndb.GenericProperty: unsupported(ndb.GenericProperty), ndb.GeoPt: lambda obj: "%s %s" % (obj.lat, obj.lon), ndb.PickleProperty: unsupported(ndb.PickleProperty), users.User: lambda obj: obj.user_id() or obj.email(), cached_property: lambda obj: cached_property, }) return _type_map @classmethod def _restler_serialization_name(cls): """ The lowercase model classname """ _serialization_name = create_serialization_name(cls, serialization_name or cls.__name__.lower()) return _serialization_name @classmethod def _restler_property_map(cls): """ List of model property names if *include_all_fields=True* Property must be from **google.appengine.ext.ndb.Property** """ _property_map = create_property_map(cls, property_map) _property_map.update(dict((name, prop.__class__) for name, prop in cls._properties.items())) return _property_map wrap_method(cls, _restler_types) wrap_method(cls, _restler_property_map) cls._restler_serialization_name = _restler_serialization_name return cls return wrap ae_ndb_serializer = ae_ndb_decorator_builder() def django_decorator_builder(type_map=None, serialization_name=None, property_map=None): """ Creates a decorator for django.db.Models :param type_map: a map of types -> callable(value) or a callable(model) that returns a map. :param serialization_name: a (string) name used for the tag/key for serialization or a callable(model) that returns a name :param property_map: a map of (field) names (string) -> types or a callable(model) that returns a map. """ def wrap(cls): """ Restler serialization class decorator for django.db.models """ @classmethod def _restler_types(cls): """ A map of types types to callables that serialize those types. """ from django.db.models.query import QuerySet from django.db.models import CommaSeparatedIntegerField, FileField, FilePathField, ImageField import json _type_map = create_type_map(type_map) _type_map.update({ QuerySet: lambda query: list(query), CommaSeparatedIntegerField: lambda value: json.loads(value), ImageField: unsupported(ImageField), FileField: unsupported(FileField), FilePathField: unsupported(FilePathField) }) return _type_map @classmethod def _restler_serialization_name(cls): """ The lowercase model classname """ _serialization_name = create_serialization_name(cls, serialization_name or cls.__name__.lower()) return _serialization_name @classmethod def _restler_property_map(cls): """ List of model property names -> property types. The names are used in *include_all_fields=True* Property must be from **django.models.fields** """ from django.db.models.fields.related import ForeignKey, ManyToManyField, OneToOneField, RelatedObject # Relation fields (and their related objects) need to be handled specifically as there is no single way to # handle them -- they should be handled explicity through callables. excluded_types = {ForeignKey, ManyToManyField, OneToOneField, RelatedObject} name_map = cls._meta._name_map all_field_names = cls._meta.get_all_field_names() _property_map = create_property_map(cls, property_map) new_property_map = dict([(name, name_map[name][0].__class__) for name in all_field_names if name_map[name][0].__class__ not in excluded_types]) _property_map.update(new_property_map) return _property_map wrap_method(cls, _restler_types) wrap_method(cls, _restler_property_map) cls._restler_serialization_name = _restler_serialization_name return cls return wrap django_serializer = django_decorator_builder() def sqlalchemy_decorator_builder(type_map=None, serialization_name=None, property_map=None): """ Creates a decorator for sqlalchemy models :param type_map: a map of types -> callable(value) or a callable(model) that returns a map. :param serialization_name: a (string) name used for the tag/key for serialization or a callable(model) that returns a name :param property_map: a map of (field) names (string) -> types or a callable(model) that returns a map. """ def wrap(cls): """ Restler serialization class decorator for SqlAlchemy models """ @classmethod def _restler_types(cls): """ A map of types types to callables that serialize those types. """ from sqlalchemy.types import Binary, Interval, LargeBinary, PickleType from sqlalchemy.orm.query import Query _type_map = create_type_map(type_map) _type_map.update({ Query: lambda query: list(query), Binary: unsupported(Binary), Interval: unsupported(Interval), LargeBinary: unsupported(LargeBinary), PickleType: unsupported(PickleType) }) return _type_map @classmethod def _restler_serialization_name(cls): """ The lowercase model classname """ _serialization_name = create_serialization_name(cls, serialization_name or cls.__name__.lower()) return _serialization_name @classmethod def _restler_property_map(cls): """ List of model property names -> property types. The names are used in *include_all_fields=True* Property must be from **sqlalchemy.types** """ _property_map = create_property_map(cls, property_map) columns = cls.__table__.columns column_map = dict([(name, columns.get(name).type.__class__) for name in columns.keys()]) _property_map.update(column_map) return _property_map wrap_method(cls, _restler_types) wrap_method(cls, _restler_property_map) cls._restler_serialization_name = _restler_serialization_name return cls return wrap sqlalchemy_serializer = sqlalchemy_decorator_builder()
/restler-serialization-0.4.1.tar.gz/restler-serialization-0.4.1/restler/decorators.py
0.704058
0.164684
decorators.py
pypi
from datetime import date as real_date, datetime as real_datetime import re import time class date(real_date): def strftime(self, fmt): return strftime(self, fmt) class datetime(real_datetime): def strftime(self, fmt): return strftime(self, fmt) def combine(self, date, time): return datetime(date.year, date.month, date.day, time.hour, time.minute, time.microsecond, time.tzinfo) def date(self): return date(self.year, self.month, self.day) def new_date(d): "Generate a safe date from a datetime.date object." return date(d.year, d.month, d.day) def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw) # This library does not support strftime's "%s" or "%y" format strings. # Allowed if there's an even number of "%"s because they are escaped. _illegal_formatting = re.compile(r"((^|[^%])(%%)*%[sy])") def _findall(text, substr): # Also finds overlaps sites = [] i = 0 while 1: j = text.find(substr, i) if j == -1: break sites.append(j) i=j+1 return sites def strftime(dt, fmt): if dt.year >= 1900: return super(type(dt), dt).strftime(fmt) illegal_formatting = _illegal_formatting.search(fmt) if illegal_formatting: raise TypeError("strftime of dates before 1900 does not handle" + illegal_formatting.group(0)) year = dt.year # For every non-leap year century, advance by # 6 years to get into the 28-year repeat cycle delta = 2000 - year off = 6 * (delta // 100 + delta // 400) year = year + off # Move to around the year 2000 year = year + ((2000 - year) // 28) * 28 timetuple = dt.timetuple() s1 = time.strftime(fmt, (year,) + timetuple[1:]) sites1 = _findall(s1, str(year)) s2 = time.strftime(fmt, (year+28,) + timetuple[1:]) sites2 = _findall(s2, str(year+28)) sites = [] for site in sites1: if site in sites2: sites.append(site) s = s1 syear = "%04d" % (dt.year,) for site in sites: s = s[:site] + syear + s[site+4:] return s
/restler-serialization-0.4.1.tar.gz/restler-serialization-0.4.1/restler/datetime_safe.py
0.642657
0.187114
datetime_safe.py
pypi
class TransientModel(object): """A helper class that can be used to transform external services into restler services. Any subclass can be used with a ModelStrategy. Override the required_fields and optional_fields and instantiate using init parameters. e.g. MyTransientModel(field1=val1, field2=val2...) """ @classmethod def _restler_serialization_name(cls): """ :return: name to use in the serialized output for this object """ return cls.__name__ @classmethod def required_fields(cls): """ :return: A tuple of (str) names of attributes that are required. """ return tuple() @classmethod def optional_fields(cls): """ :return: A tuple of (str) names of attributes that are option. """ return tuple() @classmethod def _restler_property_map(cls): """ :return: fields that can be serialized. Also used with `include_all_fields` """ return dict([(name, name.__class__) for name in cls.required_fields() + cls.optional_fields()]) @classmethod def fields(cls): return cls.required_fields() + cls.optional_fields() @classmethod def _restler_types(cls): """ :return: a map of types -> callables, for any types that can't be serialized automatically to JSON. The callable should transform an instance into a value e.g. string, number, list that can be serialized by a JSON encoder. The format e.g. is {MyType: lambda instance_of_type: str(instance_of_type, ...} """ return {} def __init__(self, **kwargs): for prop in self._restler_property_map().keys(): setattr(self, prop, kwargs.get(prop)) if prop in self.required_fields() and getattr(self, prop) is None: raise AttributeError('The property: %s is required.' % prop) def properties(self): """ :return: a dictionary of key/value pairs for fields in this model """ return dict([(prop, getattr(self, prop)) for prop in self.fields()])
/restler-serialization-0.4.1.tar.gz/restler-serialization-0.4.1/restler/models.py
0.880957
0.552238
models.py
pypi
import json import yaml from restless import Handler from datetime import datetime from collections import Hashable from inspect import _empty from restless.parameters import BinaryParameter from restless.security import Security from typing import List, Union from restless.util import snake_to_camel from enum import Enum class Formats(Enum): yaml = 'yaml' json = 'json' OPENAPI = "3.0.0" TYPE_MAPPING = { str: "string", bool: "boolean", bytes: "file", datetime: "string", set: "array", int: "integer", float: "number", list: "array", dict: "object" } def make_security(security: List[Union[List[str], str]], spec: dict): for sec in security or []: if isinstance(sec, str): assert sec in spec['components']['securitySchemes'], spec['components']['securitySchemes'] else: for s in sec: assert s in spec['components']['securitySchemes'] return [ {sec: []} if isinstance(sec, str) else {s: [] for s in sec} for sec in security ] def get_handlers(handlers): if isinstance(handlers, dict): for v in handlers.values(): for found in get_handlers(v): yield found else: yield handlers def make_spec( title, description, version, api_handler: Handler, file_name='spec.yaml', servers=None, security: List[Security] = None, default_security: List[Union[List[str], str]] = None, data_format: Formats = None ): spec = { 'openapi': OPENAPI, 'tags': [], 'info': { 'title': title, 'description': description, 'version': version }, 'paths': {}, 'servers': servers or [], 'components': { 'securitySchemes': { sec.name: dict(sec) for sec in (security or []) }, 'schemas': { 'Error': { 'properties': { 'error': { 'type': 'string' }, 'details': { 'type': 'object' } }, 'required': [ 'error' ] } } } } if default_security: spec['security'] = make_security(default_security, spec) for sec in default_security or []: if isinstance(sec, str): assert sec in spec['components']['securitySchemes'], spec['components']['securitySchemes'] else: for s in sec: assert s in spec['components']['securitySchemes'] for handler in get_handlers(api_handler.handlers): if handler.path not in spec['paths']: spec['paths'][handler.path] = {} target = spec['paths'][handler.path] if handler.http_method not in target: target[handler.http_method] = {} target = target[handler.http_method] if handler.security is None: # default = None # Uses the default security pass elif handler.security: # uses specific security target['security'] = make_security(handler.security, spec) else: # security=False # unsecured target['security'] = [] target['description'] = handler.method.__doc__ or handler.method.__name__ target['responses'] = { code: { 'description': description, 'content': { 'application/json': { 'schema': { '$ref': '#/components/schemas/Error' } } } } for code, description in [ ('400', 'Bad Request'), ('401', 'Unauthorized'), ('403', 'Forbidden'), ('404', 'Not Found') ] } target['parameters'] = [] if handler.tags: target['tags'] = handler.tags else: tokens = handler.path.split('/') if len(tokens) > 1: target['tags'] = [tokens[1]] else: target['tags'] = ['default'] returns = handler.sig.return_annotation if isinstance(handler.sig.return_annotation, dict) else {} for code, model in returns.items(): if isinstance(model, list): schema = { "type": "array", "items": {} } t = schema['items'] model = model[0] else: schema = {} t = schema if isinstance(model, Hashable) and model in TYPE_MAPPING: t['type'] = TYPE_MAPPING[model] elif hasattr(model, 'schema'): t['$ref'] = '#/components/schemas/' + model.__name__ spec['components']['schemas'][model.__name__] = model.schema() if api_handler.use_camel_case: spec['components']['schemas'][model.__name__] = snake_to_camel( spec['components']['schemas'][model.__name__] ) target['responses'][str(code)] = { 'description': description, 'content': { 'application/json': { 'schema': schema } } } for param, model in handler.parameters.items(): if getattr(model, "LOCATION", "body") not in ['body', 'formData']: param_spec = { 'name': snake_to_camel(param) if api_handler.use_camel_case else param, 'in': getattr(model, "LOCATION", "body"), 'required': handler.sig.parameters[param].default == _empty, 'description': model.__doc__ or param, 'schema': { 'type': 'string' } } if getattr(model, 'ENUM', None): param_spec['schema']['enum'] = model.enum_keys() target['parameters'].append(param_spec) else: if 'requestBody' not in target: target['requestBody'] = {"content": {}} if hasattr(model, 'schema'): spec['components']['schemas'][model.__name__] = model.schema() if api_handler.use_camel_case: spec['components']['schemas'][model.__name__] = snake_to_camel( spec['components']['schemas'][model.__name__] ) target['requestBody']['content']['application/json'] = { 'schema': { '$ref': '#/components/schemas/' + model.__name__ } } elif issubclass(model, BinaryParameter): target['requestBody']['content']['application/octet-stream'] = { 'schema': { 'type': 'string', 'format': 'binary' } } elif getattr(model, "LOCATION", "body") == "formData": if 'multipart/form-data' not in target['requestBody']['content']: target['requestBody']['content']['multipart/form-data'] = { 'schema': { 'type': 'object', 'properties': {} } } if issubclass(model, str): target['requestBody']['content']['multipart/form-data']['schema']['properties'][param] = { 'type': 'string' } else: target['requestBody']['content']['multipart/form-data']['schema']['properties'][param] = { 'type': 'string', 'format': 'binary' } data_format = data_format or Formats.__getitem__(file_name.split('.')[1]) if data_format == Formats.yaml: data = yaml.dump(spec) elif data_format == Formats.json: data = json.dumps(spec) else: raise Exception("Bad Format") if file_name: with open(file_name, 'w') as dst: dst.write(data) else: return data
/restless_cloud-0.1.1-py3-none-any.whl/restless/openapi.py
0.614163
0.245158
openapi.py
pypi
import re from collections import defaultdict from typing import Callable, ClassVar, Iterable, List from inspect import signature from restless.interfaces import BaseRequest from restless.util import FormData from restless.parameters import BinaryParameter, BodyParameter, AuthorizerParameter from restless.errors import Forbidden, Unauthorized, Missing, BadRequest from pydantic.error_wrappers import ValidationError from restless.security import Security from pydantic import BaseModel class PathHandler: def __init__(self, path, path_regex, method, http_method, tags=None, security=list): self.path = path.replace('<', '{').replace('>', '}') self.path_regex = path_regex self.method = method self.http_method = http_method self.tags = tags or [] self.security = security self.sig = signature(method) self.parameters = {k: v.annotation or type(v.default) for k, v in self.sig.parameters.items()} def process_request(self, req: BaseRequest): params = {} method_params = {} match = self.path_regex.search(req.path) if match: params.update(match.groupdict().items()) if req.headers: params.update(req.headers) if req.query: params.update(req.query) if isinstance(req.body, bytes): try: params.update( FormData(req.body) ) except AttributeError: params["body"] = req.body for param, value in params.items(): if param not in self.parameters: continue else: if getattr(self.parameters[param], 'ENUM', None): if not re.match(r'[a-zA-Z_].*', value): value = "_" + value if value in self.parameters[param].ENUM.__members__: method_params[param] = self.parameters[param].ENUM.__members__[value] else: raise BadRequest( f"The value for {param} must be one of {self.parameters[param].enum_keys()}" ) else: method_params[param] = value if isinstance(value, FormData.File) else self.parameters[param]( value) for param, type_ in self.parameters.items(): if type_ == BinaryParameter: method_params[param] = params.get('body') elif issubclass(type_, BodyParameter): method_params[param] = type_(**req.body) elif issubclass(type_, AuthorizerParameter): method_params[param] = req.authorizer result = self.method(**method_params) if isinstance(result, tuple): if len(result) == 2: body, status, headers = result[0], result[1], {} else: body, status, headers = result else: body, status, headers = result, 200, {} expected_type = self.sig.return_annotation[status] if isinstance(body, Iterable) and not isinstance(body, (dict, str, BaseModel, bytes)): body = list(body) assert all( isinstance(rec, expected_type[0]) for rec in body ), f"All records should be of type '{expected_type.__name__e}'" else: assert isinstance(body, expected_type), f"The body should be of type '{expected_type.__name__}'" return body, status, headers class Handler: REGEX = re.compile(r'(<[^/]+?>)') def __init__(self, request: ClassVar, response: ClassVar, use_camel_case=False): self.handlers = defaultdict(dict) self.Request = request self.Response = response self.use_camel_case = use_camel_case def handle(self, method: str, path: str, tags=None, security=None) -> Callable: tokens = path.split('/')[1:] path_expressions = [] target = self.handlers[len(tokens)] for token in tokens: if self.REGEX.search(token): path_expressions.append( self.REGEX.sub('(?P\\1[^/]+)', token) ) token = '' else: path_expressions.append(token) if token not in target: target[token] = {} target = target[token] def wrapped(f: Callable): path_regex = re.compile('/'.join(path_expressions) + '$') assert method.upper() not in target, f"'{path}' already has the '{method}' method" target[method.upper()] = PathHandler( path=path, path_regex=path_regex, method=f, http_method=method, tags=tags, security=security ) return f return wrapped def select_handler(self, req: BaseRequest): tokens = req.path.split('/')[1:] target = self.handlers[len(tokens)] for token in tokens: if token in target: target = target[token] elif '' in target: target = target[''] try: return target[req.method.upper()] except KeyError: raise Missing(f"Missing '{req.method}' on '{req.path}'") def __call__(self, event): req = self.Request(event, use_camel_case=self.use_camel_case) try: path_handler = self.select_handler(req) body, status, headers = path_handler.process_request(req) return self.Response( body=body, status_code=status, headers=headers, use_camel_case=self.use_camel_case ) except (TypeError, AssertionError) as e: if e.args and 'missing' in e.args[0]: return self.Response( {"error": str(e)}, status_code=400, use_camel_case=self.use_camel_case ) raise e except ValidationError as e: return self.Response( {"error": "Validation Error", "details": e.errors()}, status_code=400, use_camel_case=self.use_camel_case ) except Unauthorized as e: return self.Response( {"error": e.args[0]}, status_code=401, use_camel_case=self.use_camel_case ) except Forbidden as e: return self.Response( {"error": e.args[0]}, status_code=403, use_camel_case=self.use_camel_case ) except Missing as e: return self.Response( {"error": e.args[0]}, status_code=404, use_camel_case=self.use_camel_case ) except BadRequest as e: return self.Response( {"error": e.args[0]}, status_code=400, use_camel_case=self.use_camel_case )
/restless_cloud-0.1.1-py3-none-any.whl/restless/__init__.py
0.674587
0.190988
__init__.py
pypi
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from restless.exceptions import UnprocessableEntity, NotFound class ModelResourceMixin: """ Provides a Resource.get_queryset and Resource.get_object like in Django class based views. Also provides a Resource.process_form helper to process forms and return standard/consistent errors. """ model = None queryset = None def process_form(self, form_class, error_class=UnprocessableEntity, **kwargs): """ Process a form based on the passed config """ form = form_class(self.data, **kwargs) if not form.is_valid(): try: msg = form.errors["__all__"][0] except (KeyError, IndexError): msg = "Validation failed, Check errors for details" errors = {k: v for k, v in form.errors.items() if k != "__all__"} raise error_class( {"errNo": error_class.status, "errMsg": msg, "errors": errors} ) return form.save() def get_queryset(self): """ Returns the objects for the list API and for consideration by the Resource.get_object() helper. """ if self.queryset is None: if self.model: return self.model._default_manager.all() raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % {"cls": self.__class__.__name__} ) return self.queryset.all() def get_object(self, pk): """ Return the object used in the detail, update and delete APIs. """ try: return self.get_queryset().get(pk=pk) except (ObjectDoesNotExist, ValueError): raise NotFound( { "errNo": 404, "errDev": "Object with that id does not exist", "errMsg": "The object you specified does not exist", } ) def order_queryset(self, qs, fields, default=None): """ Helper method to order a queryset based on user provided options """ ordering = self.request.GET.get("ordering", default) if ordering is not None: order_by = [] for field in ordering.lower().split(","): try: field, order = field.split(":") except ValueError: continue if order in ("asc", "desc") and field in fields.keys(): order = "-" if order == "desc" else "" order_by.append(f"{order}{fields[field]}") if len(order_by) > 0: qs = qs.order_by(*order_by) return qs
/restless_dj_utils-0.2b3.tar.gz/restless_dj_utils-0.2b3/restless_dj_utils/resources/model.py
0.567577
0.161982
model.py
pypi
# Resto_client: a client to access resto servers [![PyPI license](https://img.shields.io/pypi/l/resto_client.svg)](https://www.apache.org/licenses/LICENSE-2.0) [![Python versions](https://img.shields.io/pypi/pyversions/resto_client.svg)](https://pypi.org/project/resto_client/) [![PyPI version shields.io](https://img.shields.io/pypi/v/resto_client.svg)](https://pypi.org/project/resto_client/) [![PyPI - Format](https://img.shields.io/pypi/format/resto_client)](https://pypi.org/project/resto_client/#files) [![PyPI - Downloads](https://img.shields.io/pypi/dm/resto_client)](https://pypistats.org/packages/resto-client) [![GitHub contributors](https://img.shields.io/github/contributors/CNES/resto_client)](https://github.com/CNES/resto_client/graphs/contributors) **resto_client** is a python package which gives you access to several remote sensing image servers which are based on the [resto](https://github.com/jjrom/resto/tree/2.x) open source server. Once you have installed it, **resto_client** offers the possibility to interact with these servers by issuing commands from a simple terminal. Currently implemented commands allow to: - define and manage a list of well known servers, - select one of them and browse its collections and their characteristics, - **search** a collection by criteria for retrieving features (images for instance) and display their characteristics, - **show** : retrieve and display feature metadata when you know its identifier, - **download** files composing the feature: the product itself, but also its quicklook, thumbnail or annexes, - authentication is supported to provide access to restricted features or sign product licenses when necessary. ### Well known resto servers **resto_client** comes with a list of well known servers already configured, which can be accessed out of the box: * [kalideos : CNES Kalideos platform](https://www.kalideos.fr) * [ro : CEOS Recovery Observatory](https://www.recovery-observatory.org) * [pleiades : CNES pleiades platform](https://www.pleiades-cnes.fr) * [peps : The French Sentinel Data Processing center](https://peps.cnes.fr) * [theia : The French Space Agency, THEIA land data center](https://theia.cnes.fr) * [creodias : Copernicus DIAS CREODIAS](https://www.creodias.eu) * [cop_nci : Sentinel Australasia regional Access](https://copernicus.nci.org.au) This list is augmented regularly, but you can of course add your own server by providing its configuration through **resto_client**. ### Supported environment **resto_client** runs on the following configurations: - Python 3.6, 3.7 or 3.8 - Any Operating System supporting the above versions of Python (Windows, Linux, MacOS, etc.) **resto_client** tests are done on Windows and Linux using the supported python versions. ### Resto_client installation The recommended way of installing `resto_client` is to simply use [`pip`](https://pypi.org/project/pip/) which will install the package from the [Python Package Index](https://pypi.org/project/resto_client/) in your python environment: ```console $ pip install resto_client ``` Once **resto_client** package is installed you can test it by issuing the following command in a terminal: ```console $ resto_client --help ``` ### Resto_client configuration **resto_client** configuration is managed through the `set`, `unset` and `configure_server` commands (see help for each of them), except for the networking configuration which is parameterized by environment variables. For network access we use the popular [requests](https://requests.readthedocs.io/en/master/) python package which directly takes into account several environment variables describing your networking configuration. Namely you might need to set the following environment variables: - `HTTP_PROXY` and `HTTPS_PROXY` if your machine is behind a proxy: have a look at [requests Proxies configuration](https://requests.readthedocs.io/en/master/user/advanced/#proxies). - `REQUESTS_CA_BUNDLE` because default policy is to enforce SSL certificates verification and your corporate policy might differ from this baseline: refer to [requests SSL certificates verification](https://requests.readthedocs.io/en/master/user/advanced/#ssl-cert-verification) in that case. The values to provide in these variables depends on the networking configuration of the machine where you are installing **resto_client**. Please refer to your system administrator for defining how to set them in your case. ### How to use resto_client? Firstly you can select the server to be used for all subsequent commands. This selection is not mandatory and you may prefer to specify the server in each command. But it is more convenient if you are using the same server for a long time. You can use a well known server: ```console $ resto_client set server kalideos ``` Or configure a new one and set it: ```console $ resto_client configure_server create new_kalideos https://www.kalideos.fr/resto2 dotcloud https://www.kalideos.fr/resto2 default $ resto_client set server new_kalideos ``` You can then show the server synthetic characteristics: ```console $ resto_client show server Server URL: https://www.kalideos.fr/resto2/ +-----------------+--------+---------------------+------------+--------------+ | Collection name | Status | Model | License Id | License name | +-----------------+--------+---------------------+------------+--------------+ | KALCNES | public | RestoModel_dotcloud | unlicensed | No license | | KALHAITI | public | RestoModel_dotcloud | unlicensed | No license | +-----------------+--------+---------------------+------------+--------------+ ``` This shows you the server URL as well as its collections and their main characteristics. If you want the details of a collection, you can type in: ```console $ resto_client show collection KALCNES +----------------------------------------------------------------------------+ | Collection's Characteristics | +-----------------+--------+---------------------+------------+--------------+ | Collection name | Status | Model | License Id | License name | +-----------------+--------+---------------------+------------+--------------+ | KALCNES | public | RestoModel_dotcloud | unlicensed | No license | +-----------------+--------+---------------------+------------+--------------+ STATISTICS for KALCNES +------------+-------------+ | collection | Nb products | +------------+-------------+ | KALCNES | 2599 | | Total | 2599 | +------------+-------------+ +---------------+-------------+ | continent | Nb products | +---------------+-------------+ | Europe | 2594 | | North America | 1 | | Total | 2595 | +---------------+-------------+ . ``` In fact the collection description contains much more statistics, but we have truncated the result for brevity. You can search the collection for the features it contains, either by identifiers or by criteria. For instance: ```console $ resto_client search --criteria platform:"PLEIADES 1A" resolution:[0,1.5] startDate:2018-01-01 completionDate:2018-01-31 --collection=KALCNES ['1926127184714545', '6589984032241814', '1926091543104317', '1926059176484529'] 4 results shown on a total of 4 results beginning at index 1 ``` And you can get the details of some feature by specifying its identifier: ```console $ resto_client show feature 1926127184714545 Metadata available for product 1926127184714545 +--------------------+-------------------------------------------------------------------------------------------+ | Property | Value | +--------------------+-------------------------------------------------------------------------------------------+ | collection | KALCNES | | productIdentifier | 1926127184714545 | | parentIdentifier | None | | title | PLEIADES 1A PAN L1A 2018-01-23 10:37:39Z | | description | L1A PAN image acquired by PLEIADES 1A on[...] | . ``` Here we have also truncated the result but there are much more metadata available for each feature. Finally you may want to download some file associated to that feature : product, quicklook, thumbnail or annexes. The following example is for the quicklook of a feature: ```console $ resto_client download quicklook 1926127184714545 downloading file: c:\Users\xxxxxxx\Downloads\1926127184714545_ql.jpg Downloading: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 128k/128k [00:09<00:00, 13.3kB/s] ``` Obviously you can also download the product, provided that you have the right credentials to access it if it is protected ```console $ resto_client download product 1926127184714545 --username=known_user Please enter your password for kalideos server:*********** ... ``` Every command has several options and there are also more commands to set different **resto_client** parameters or to define servers. You can discover their function and syntax by exploring the help on **resto_client** and on its subcommands : ```console $ resto_client --help usage: resto_client [-h] {set,unset,show,download,search,configure_server} ... A commmand line client to interact with resto servers. optional arguments: -h, --help show this help message and exit subcommands: For more help: resto_client <sub_command> -h {set,unset,show,download,search,configure_server} set set application parameters: server, account, collection, download_dir, region, verbosity unset unset application parameters: server, account, collection, download_dir, region, verbosity show show resto_client entities: settings, server, collection, feature download download features files: product, quicklook, thumbnail or annexes search search feature(s) in collection configure_server configure servers known by resto_client: create, edit, delete. $ resto_client show --help usage: resto_client show [-h] {settings,server,collection,feature} ... Show different resto_client entities. optional arguments: -h, --help show this help message and exit subcommands: For more help: resto_client show <entity> -h {settings,server,collection,feature} settings Show application settings server Show the server details collection Show the details of a collection feature Show feature details ``` ### Documentation More documentation available soon.
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/README.md
0.572603
0.896024
README.md
pypi
from abc import ABC, abstractmethod from typing import Optional, Tuple, TYPE_CHECKING # @NoMove import requests if TYPE_CHECKING: from resto_client.services.authentication_service import AuthenticationService # @UnusedImport from resto_client.services.authentication_account import AuthorizationDataType # @UnusedImport class Authenticator(ABC): """ Base class for all requests managing the request Authentication """ @property @abstractmethod def authentication_type(self) -> str: """ :returns: the authentication type of this request (NEVER or ALWAYS or OPPORTUNITY) """ @property def _authentication_required(self) -> bool: """ :returns: a flag telling if the request requires authentication or not. """ return self.authentication_type == 'ALWAYS' @property def _anonymous_request(self) -> bool: """ :returns: a flag telling if the request does not require authentication. """ return self.authentication_type == 'NEVER' def __init__(self, service: 'AuthenticationService') -> None: """ Constructor :param service: authentication service """ self.auth_service = service def update_authorization_headers(self, request_header: dict) -> None: """ :param request_header: the request headers to update with the authorization part """ try_asking_token = (self.authentication_type == 'OPPORTUNITY' and (self.auth_service.account_defined or self.auth_service.token_is_available)) if self._authentication_required or try_asking_token: authorization_header = self.auth_service.get_authorization_header() request_header.update(authorization_header) return def _get_authentication_arguments(self, request_headers: dict) -> \ Tuple[Optional[requests.auth.HTTPBasicAuth], Optional['AuthorizationDataType']]: """ This create and execute a POST request and store the response content """ if 'Authorization' in request_headers: return None, None return self.http_basic_auth, self.authorization_data @property def http_basic_auth(self) -> Optional[requests.auth.HTTPBasicAuth]: """ :returns: the basic HTTP authorization for the request """ return self.auth_service.http_basic_auth if self._authentication_required else None @property def authorization_data(self) -> Optional['AuthorizationDataType']: """ :returns: the authorization data for the request """ return self.auth_service.authorization_data if self._authentication_required else None
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/requests/authenticator.py
0.894752
0.17075
authenticator.py
pypi
from typing import Any, List # @UnusedImport @NoMove import json from pathlib import Path from shapely.geometry import shape from shapely.geometry.base import BaseGeometry from shapely.ops import unary_union from resto_client.base_exceptions import RestoClientUserError HERE = Path(__file__).parent PATH_AOI = HERE.parent / 'zones' class LowerList(list): """ Class representing a less restrictive list """ def __contains__(self, other: object) -> bool: """ other is in my class if this lower is in it :param other: object whose str representation is to be tested for being in the list. :returns: boolean response of : is the other.lower in self ? """ return super(LowerList, self).__contains__(str(other).lower()) def list_all_geojson() -> List[str]: """ List all geojson file in the proper path for aoi :returns: list of file in lower_case """ list_file = [f.name for f in PATH_AOI.iterdir() if f.suffix == '.geojson'] # prepare test by lower all name list_file = [element.lower() for element in list_file] return list_file def search_file_from_key(key: str) -> Path: """ Translate a key to this proper geojson file :param key: the geojson file :returns: geojson file associated """ return PATH_AOI / key def find_region_choice() -> LowerList: """ Cut all .geojson extension in the list geojson file :returns: the list of region choices file without .geojson extension """ list_to_cut = list_all_geojson() cut_list = [f[0:-8] for f in list_to_cut if f.endswith('.geojson')] return LowerList(cut_list) def geojson_zone_to_bbox(geojson_path: Path) -> BaseGeometry: """ Translate a geojson file to a bbox geometry :param geojson_path: the path to the geojson file :returns: the bbox geometry of the kml """ # will contain all shape of the geojson shapes = geojson_to_shape(geojson_path) # translate it for resto into bbox bounds return shapes_to_bbox(shapes) def find_sensitive_file(geojson_path: Path) -> Path: """ Find the proper file name if the given has not a good sensitive case :param geojson_path: the geojson file path :returns: correct path with case taking into account :raises RestoClientUserError: when the region file is not found. """ file_name = geojson_path.name directory = geojson_path.parent for name_in_dir in directory.iterdir(): if file_name.lower() == str(name_in_dir.name).lower(): improved_path = directory / name_in_dir return improved_path raise RestoClientUserError('No region file found with name {}'.format(geojson_path)) def geojson_to_shape(geojson_file: Path) -> List[BaseGeometry]: """ Translate a geojson file to a shape of shapely :param geojson_file: the path of the geojson file :returns: list of shape """ if not geojson_file.exists(): geojson_file = find_sensitive_file(geojson_file) with open(geojson_file, 'r') as file: data = json.load(file) shapes = [] for feature in data['features']: shapes.append(shape(feature['geometry'])) return shapes def shapes_to_bbox(shapes: List[BaseGeometry]) -> BaseGeometry: """ Translate shapes to a bbox envelope :param shapes: list of shapely shape :returns: bbox of the shapes, rectangular boundaries """ # convert to a single shape, union of all union_mono_shape = unary_union(shapes) # returns the smallest rectangular polygon convex_envelope = union_mono_shape.convex_hull return convex_envelope
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/functions/aoi_utils.py
0.922473
0.46478
aoi_utils.py
pypi
from typing import List # @UnusedImport from resto_client.base_exceptions import UnsupportedErrorCode from .resto_json_response import RestoJsonResponseSimple class DownloadErrorResponse(RestoJsonResponseSimple): """ Response received during Download*Request when download cannot be done for some reason. """ needed_fields = ['ErrorMessage', 'ErrorCode', 'feature', 'collection', 'license_id', 'license', 'user_id'] optional_fields: List[str] = [] def identify_response(self) -> None: """ Verify that the response is a valid json response when download request are submitted. :raises UnsupportedErrorCode: if the dictionary does not contain a valid Resto response. """ # Firstly verify that the needed fields are present and build standard normalized response. super(DownloadErrorResponse, self).identify_response() # Secondly verify that no code different from those we understand are present. if self._original_response['ErrorCode'] not in [3002, 3006]: msg = 'Received a DownloadErrorResponse with unsupported error code: {}.' raise UnsupportedErrorCode(msg.format(self._original_response['ErrorCode'])) @property def download_need_license_signature(self) -> bool: """ :returns: True if the user needs to sign the license specified in this error """ return self._normalized_response['ErrorCode'] == 3002 @property def license_to_sign(self) -> str: """ :returns: the license_id of the license which must be signed by the user. """ return self._normalized_response['license_id'] @property def download_forbidden(self) -> bool: """ :returns: True if the user has no right to request this product download. """ return self._normalized_response['ErrorCode'] == 3006 @property def requested_feature(self) -> str: """ :returns: The feature id whose download has been requested. """ return self._normalized_response['feature'] def as_resto_object(self) -> 'DownloadErrorResponse': """ :returns: the response expressed as a Resto object """ return self
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/responses/download_error_response.py
0.859133
0.244617
download_error_response.py
pypi
import copy from typing import Optional from resto_client.base_exceptions import (InconsistentResponse, IncomprehensibleResponse) from resto_client.entities.resto_collection import RestoCollection from resto_client.entities.resto_collections import RestoCollections from .resto_json_response import RestoJsonResponse OSDESCRIPTION_KEYS = ['ShortName', 'LongName', 'Description' 'Tags', 'Developer', 'Contact', 'Query', 'Attribution'] def rebuild_os_description(opensearch_description: dict) -> Optional[dict]: """ Rebuild a normalized osDescription from an existing one or create a sensible one. If osDescription is multi-lingual, retain only one language, preferably english :param opensearch_description: the osDescription field to process :returns: osDescription english fields """ normalized_osdescription = None if isinstance(opensearch_description, dict): if any([os_key in opensearch_description for os_key in OSDESCRIPTION_KEYS]): normalized_osdescription = copy.deepcopy(opensearch_description) elif 'en' in opensearch_description: normalized_osdescription = copy.deepcopy(opensearch_description['en']) elif 'fr' in opensearch_description: normalized_osdescription = copy.deepcopy(opensearch_description['fr']) return normalized_osdescription def counting_stats(response_stat_collection: dict) -> int: """ Count a correct total of features in all collections :param response_stat_collection: the collection field'd in response's statistics :returns: count of all features """ count = 0 for stat_collection in response_stat_collection.values(): count += stat_collection return count class CollectionsDescription(RestoJsonResponse): """ Response received from DescribeRequest and GetCollectionsRequest. """ def identify_response(self) -> None: """ Verify that the response is a valid resto response for this class and set the resto type :raises InconsistentResponse: if the dictionary does not contain a valid Resto response. """ detected_protocol = None # Find which kind of Resto server we could have if 'collections' in self._original_response: if 'statistics' in self._original_response: statistics_desc = self._original_response['statistics'] if 'facets' in statistics_desc and 'count' in statistics_desc: detected_protocol = 'peps_version' else: detected_protocol = 'dotcloud' elif 'synthesis' in self._original_response: if 'statistics' in self._original_response['synthesis']: statistics_desc = self._original_response['synthesis']['statistics'] if 'facets' in statistics_desc and 'count' in statistics_desc: detected_protocol = 'theia_version' self.detected_protocol = detected_protocol if detected_protocol is None: raise IncomprehensibleResponse('Dictionary does not contain a valid Resto response') if self._parent_request.get_protocol() != detected_protocol: msg_fmt = 'Detected a {} response while waiting for a {} response.' msg = msg_fmt.format(detected_protocol, self._parent_request.get_protocol()) raise InconsistentResponse(msg) def normalize_response(self) -> None: """ Normalize the original response in a response whose structure does not depend on the server. """ result = None if self.detected_protocol == 'theia_version': result = copy.deepcopy(self._original_response) elif self.detected_protocol == 'peps_version': result = {'collections': self._original_response['collections'], 'synthesis': {'name': '*', 'osDescription': None, 'statistics': self._original_response['statistics']} } else: result = {'collections': self._original_response['collections'], 'synthesis': {'name': '*', 'osDescription': None, 'statistics': {'count': 0, 'facets': self._original_response['statistics']}} } # Update synthesis fields # Correct synthesis statistics count count = 0 if 'collection' in result['synthesis']['statistics']['facets']: count = counting_stats(result['synthesis']['statistics']['facets']['collection']) result['synthesis']['statistics']['count'] = count # rebuild an osDescription for synthesis os_description = rebuild_os_description(result['synthesis']['osDescription']) result['synthesis']['osDescription'] = os_description # rebuild osDescription for each collection for collection in result['collections']: collection['osDescription'] = rebuild_os_description(collection['osDescription']) self._normalized_response = result def as_resto_object(self) -> RestoCollections: """ :returns: the received set of collections """ synthesis = RestoCollection(self._normalized_response['synthesis']) collections = RestoCollections() collections.synthesis = synthesis for collection_desc in self._normalized_response['collections']: collections.add(RestoCollection(collection_desc)) return collections
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/responses/collections_description.py
0.817246
0.23677
collections_description.py
pypi
from abc import abstractmethod import copy from typing import Dict, List, Any, Optional, TYPE_CHECKING # @UnusedImport import warnings from resto_client.base_exceptions import InvalidResponse from .resto_response import RestoResponse if TYPE_CHECKING: from resto_client.requests.base_request import BaseRequest # @UnusedImport class RestoJsonResponse(RestoResponse): """ Json responses received from Resto. """ def __init__(self, request: 'BaseRequest', response: dict) -> None: """ Constructor :param request: the parent request of this response :param response: the response received from the server and structured as a dict. """ super(RestoJsonResponse, self).__init__(request) self._original_response = response self._normalized_response: Dict[Any, Any] = {} self.identify_response() self.normalize_response() @abstractmethod def identify_response(self) -> None: """ Verify that the response is a valid resto response for this class. :raises InvalidResponse: if the dictionary does not contain a valid Resto response. """ def normalize_response(self) -> None: """ Returns a normalized response whose structure does not depend on the server. This method should be overidden by client classes. Default is to copy the original response. """ self._normalized_response = copy.deepcopy(self._original_response) @abstractmethod def as_resto_object(self) -> Any: """ :returns: the response expressed as a Resto object """ class RestoJsonResponseSimple(RestoJsonResponse): """ Simple responses received from Resto, containing only 'flat' fields. """ @property @abstractmethod def needed_fields(self) -> List[str]: """ :returns: the field names that the response must contain """ @property @abstractmethod def optional_fields(self) -> List[str]: """ :returns: the field names that the response contains optionally """ def identify_response(self) -> None: """ Verify that the response is a valid resto response for this class. :raises InvalidResponse: if the dictionary does not contain a valid Resto response. """ # First verify that all needed fields are present. Raise an exception when some are missing for field in self.needed_fields: if field not in self._original_response: msg = 'Response to {} does not contain a "{}" field. Available fields: {}' raise InvalidResponse(msg.format(self.request_name, field, self._original_response.keys())) # Then check that no other entries than those defined as needed or optional # are contained in the response. Issue a warning if not when in debug mode. response = copy.deepcopy(self._original_response) for field in self.needed_fields: response.pop(field) for field in self.optional_fields: response.pop(field, None) if response.keys() and self._parent_request.debug: # type: ignore msg = '{} response contains unknown entries: {}.' warnings.warn(msg.format(self.request_name, response))
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/responses/resto_json_response.py
0.894112
0.152505
resto_json_response.py
pypi
from typing import List # @UnusedImport from resto_client.base_exceptions import AccessDeniedError from .resto_json_response import RestoJsonResponseSimple class GetTokenResponse(RestoJsonResponseSimple): """ Response received from GetTokenRequest. The normalized response for a GetToken request is defined by the following fields: - 'success': boolean True means that a token was retrieved successfully. - 'token': contains the token string. Exists only when 'success' is True. - 'message': contains the error reason when 'success' is False. Not available for all servers. """ needed_fields: List[str] = [] optional_fields = ['success', 'token', 'message'] def normalize_response(self) -> None: """ Returns a normalized response whose structure does not depend on the server. """ # First copy the fields present in the original response. self._normalized_response = {} if 'success' in self._original_response: self._normalized_response['success'] = self._original_response['success'] if 'token' in self._original_response: self._normalized_response['token'] = self._original_response['token'] if 'message' in self._original_response: self._normalized_response['message'] = self._original_response['message'] # Create a 'success' field if it was missing in the original response. if 'success' not in self._normalized_response: # Some servers signal failure by returning an empty token string. # It is also a failure to have no returned token field. self._normalized_response['success'] = self._normalized_response.get('token', '') != '' @property def token_value(self) -> str: """ :returns: the token included in the response :raises AccessDeniedError: when the GetToken request was rejected for incorrect credentials. """ if self._normalized_response['success']: return self._normalized_response['token'] # response reported a failure. If a message is available use it otherwise create one. if 'message' in self._normalized_response: msg_excp = self._normalized_response['message'] else: msg_excp = 'Invalid username/password' raise AccessDeniedError(msg_excp) def as_resto_object(self) -> 'GetTokenResponse': """ :returns: the response expressed as a Resto response """ return self class CheckTokenResponse(RestoJsonResponseSimple): """ Response received from CheckTokenRequest. """ needed_fields = ['status', 'message'] optional_fields: List[str] = [] @property def is_valid(self) -> bool: """ :returns: the token's validity """ return self._normalized_response['status'] == 'success' @property def validation_message(self) -> bool: """ :returns: the token's validation message """ return self._normalized_response['message'] def as_resto_object(self) -> 'CheckTokenResponse': """ :returns: the response expressed as a Resto response """ return self class RevokeTokenResponse(RestoJsonResponseSimple): """ Response received from RevokeTokenRequest. """ needed_fields: List[str] = [] optional_fields: List[str] = [] def as_resto_object(self) -> 'RevokeTokenResponse': """ :returns: the response expressed as a Resto response """ return self
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/responses/authentication_responses.py
0.902115
0.175185
authentication_responses.py
pypi
from typing import Sequence, Optional # @NoMove from datetime import datetime from urllib.parse import urlparse from shapely import wkt from shapely.errors import WKTReadingError from resto_client.base_exceptions import RestoClientDesignError class DateYMD(): # pylint: disable=too-few-public-methods """ A class to test input Date in order to have a proper YYYY-MM-DD format """ def __init__(self, date_text: str) -> None: """ Test the input in order to have a proper %Y-%m-%d format :param date_text: date in str format to test """ datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d') class DateYMDInterval(): # pylint: disable=too-few-public-methods """ A class to test input Date Interval in order to have a proper format """ def __init__(self, date_interval_text: str) -> None: """ Test the input in order to have a proper %Y-%m-%d:%Y-%m-%d format :param date_interval_text: date interval in str format to test :raises ValueError: when argument does not have 2 components or when one of them is not a DateYMD. """ interval = date_interval_text.split(':') # Test that two numbers are given if len(interval) != 2: msg_error = '{} has a wrong format, expected : Date1:Date2' raise ValueError(msg_error.format(date_interval_text)) for date_unic in interval: try: DateYMD(date_unic) except ValueError: msg = '{} in interval {} has an unexpected type, should be DateYMD' raise ValueError(msg.format(date_unic, date_interval_text)) date1 = datetime.strptime(interval[0], "%Y-%m-%d") date2 = datetime.strptime(interval[1], "%Y-%m-%d") if date1 > date2: msg_error = 'First date must be anterior to Second one in interval, Here :{}>{}' raise ValueError(msg_error.format(date1, date2)) class GeometryWKT(): # pylint: disable=too-few-public-methods """ A class to test input geometry in order to have a proper WKT format """ def __init__(self, geometry_input: str) -> None: """ Test the input in order to have a proper %Y-%m-%d format :param geometry_input: geometry in str format to test :raises WKTReadingError: geometry has not a wkt format """ try: wkt.loads(geometry_input) except WKTReadingError: msg = 'Geometry criterion accept WKT geometry, this criterion does not fit : {}' raise WKTReadingError(msg.format(geometry_input)) class SquareInterval(): # pylint: disable=too-few-public-methods """ A class to test input Interval in order to have a proper format surounded by square backet ex : [n1,n2[ """ def __init__(self, str_interval: str) -> None: """ Constructor :param str_interval: interval in str format to test :raises ValueError: if format not respected """ accpt_car = ('[', ']') # Test beginning and end for interval if not str_interval.startswith(accpt_car) or not str_interval.endswith(accpt_car): raise ValueError('{} has a wrong format, expected : [n1,n2['.format(str_interval)) interval = str_interval[1:-1].split(',') # Test that two numbers are given if len(interval) != 2: raise ValueError('{} has a wrong format, expected : [n1,n2['.format(str_interval)) for number in interval: try: float(number) except ValueError: msg = '{} in interval {} has an unexpected type, should be convertible in float' raise ValueError(msg.format(number, str_interval)) class TestList(): # pylint: disable=too-few-public-methods """ A class to test input exist in tuple """ def __init__(self, str_input: str, accepted: Sequence[str]) -> None: """ Constructor :param str_input: input to test :param accepted: accepted values for input :raises ValueError: if format not respected """ if str_input not in accepted: raise ValueError('{} has a wrong value, expected in {}'.format(str_input, accepted)) class AscOrDesc(TestList): # pylint: disable=too-few-public-methods """ A class to test input is 'ascending' or 'descending' """ def __init__(self, str_input: str) -> None: """ Constructor :param str_input: input to test """ accpt_tuple = ('ascending', 'descending') super(AscOrDesc, self).__init__(str_input=str_input, accepted=accpt_tuple) class Polarisation(TestList): # pylint: disable=too-few-public-methods """ A class to test input has a accepted polarisation type """ def __init__(self, str_input: str) -> None: """ Constructor :param str str_input: input to test """ accpt_tuple = ('HH', 'VV', 'HH HV', 'VV VH') super(Polarisation, self).__init__(str_input=str_input, accepted=accpt_tuple) class URLType(): # pylint: disable=too-few-public-methods """ A class to make sure input is an url """ def __init__(self, url: str, url_purpose: Optional[str]="Unknown") -> None: """ Test the input in order to have a proper URL :param url: URL in str format to test :param url_purpose: purpose of the URL :raises RestoClientDesignError: if url is not a proper URL """ try: result = urlparse(url) if not all([result.scheme, result.netloc]): raise ValueError() except ValueError: error_msg = 'Given url for {} is not a valid URL: {}.' raise RestoClientDesignError(error_msg.format(url_purpose, url))
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/generic/basic_types.py
0.910625
0.390447
basic_types.py
pypi
import functools from typing import Callable, Optional def managed_getter(default: Optional[object]=None) -> Callable: """ This function is a decorator which decorates another function, that is intended to be used as the true decorator. This trick is mandatory to allow passing parameters when used in conjunction with property decorators. :param object default: the default value to return when the property is None or does not exist. :returns: the decorator """ def managed_getter_decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(instance: object) -> object: properties_storage = get_properties_storage(instance) key = get_internal_prop_name(instance, func) stored_value = properties_storage.get(key) if stored_value is not None: return stored_value if default is not None: properties_storage[key] = default return default return wrapper return managed_getter_decorator def managed_setter(pre_set_func: Optional[Callable]=None) -> Callable: """ This function is a decorator which decorates another function, that is intended to be used as the true decorator. This trick is mandatory to allow passing parameters when used in conjunction with property decorators. :param function pre_set_func: a function or method to normalize and check the provided value. :raises TypeError: if pre_set_func is not callable. :returns: a decorator """ if pre_set_func is not None: if not isinstance(pre_set_func, str) and not callable(pre_set_func): msg = 'managed_setter pre_set_func argument must be a callable or the name of'\ ' an instance method attribute.' raise TypeError(msg) def managed_setter_decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(instance: object, value: object) -> None: # Manage call to check function when defined if value is not None and pre_set_func is not None: if isinstance(pre_set_func, str): real_pre_func = getattr(instance, pre_set_func) else: real_pre_func = pre_set_func value = real_pre_func(value) # Retrieve storage information properties_storage = get_properties_storage(instance) key = get_internal_prop_name(instance, func) # Set value in storage previous_value = properties_storage.get(key) if value is None and key in properties_storage: del properties_storage[key] if value is not None: properties_storage[key] = value # If value has changed call the post_set function if value != previous_value: # Call the true setter to finalize value change. func(instance, value) return wrapper return managed_setter_decorator def get_internal_prop_name(instance: object, func: Callable) -> str: """ Build the name to use for storing the value of a property of an object. The internal property name is based on the function name (i.e. the decorated property name). If the object has an instance or class attribute named 'properties_name_prefix', the value of this attribute is extended by an underscore, and used as a prefix of the function name. :param instance: the instance of some class in which the property is living. :param function func: the function wrapping the property :returns: the property internal name """ property_name = func.__name__ prefix_attr_name = 'properties_name_prefix' try: prefix = getattr(instance, prefix_attr_name) + '_' except AttributeError: prefix = '' return '{}{}'.format(prefix, property_name) def get_properties_storage(instance: object) -> dict: """ Returns the dictionary into which the managed properties are recorded. If the object has an instance or class attribute named 'properties_storage', the value of this attribute is used as the storage for managed properties, provided that it is a dict. Otherwise an instance attribute with that name is created with an empty dictionary as its value. :param instance: the instance of some class in which the property is living. :returns: the properties storage dictionary """ storage_attr_name = 'properties_storage' try: storage = getattr(instance, storage_attr_name) except AttributeError: setattr(instance, storage_attr_name, {}) storage = getattr(instance, storage_attr_name) return storage
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/generic/property_decoration.py
0.863708
0.410756
property_decoration.py
pypi
from typing import Optional, Dict, Callable # @UnusedImport @NoMove from abc import ABC, abstractmethod from base64 import b64encode from getpass import getpass from requests.auth import HTTPBasicAuth from resto_client.base_exceptions import RestoClientDesignError AuthorizationDataType = Dict[str, Optional[str]] class AuthenticationAccount(ABC): """ Class implementing the account for a connection: username, password. """ asking_input: Dict[str, Callable] = {'shown': input, 'hidden': getpass} def __init__(self, server_name: str) -> None: """ Constructor """ self._username: Optional[str] = None self._password: Optional[str] = None self.server_name = server_name def _set_account(self, username: Optional[str]=None, password: Optional[str]=None) -> bool: """ Set or reset the username and the password. If username is not None, it is set to the provided value if it is different from the already stored one and the password is stored whatever its value. If username is None and password is not, then only the password is updated with the provided value. Otherwise username and password are both reset. :param username: the username to register :param password: the account password :returns: True if username and or password has been changed, False otherwise :raises RestoClientDesignError: when an unconsistent set of arguments is provided """ change_username = True change_password = password != self._password if self._username is None and self._password is None: if username is None and password is not None: msg = 'Cannot set password because no username has been defined yet.' raise RestoClientDesignError(msg) change_username = username is not None if self._username is not None: if username is None: change_username = password is None else: change_username = username.lower() != self._username if change_username: self._username = username if change_password: self._password = password return change_username or change_password def _reset_account(self) -> None: """ Reset the account unconditionally. """ self._username = None self._password = None @property def username(self) -> Optional[str]: """ :returns: the username """ return self._username @property def password(self) -> Optional[str]: """ :returns: the password """ return self._password @property def account_defined(self) -> bool: """ :returns: True if username and password are defined, but not necessarily valid. """ return self.username is not None and self.password is not None @property def username_b64(self) -> str: """ :returns: the username encoded as base64, suitable to insert in URLs :raises RestoClientDesignError: when trying to get base64 username while it is undefined. """ if self.username is None: msg = 'Unable to provide base64 username when username undefined' raise RestoClientDesignError(msg) return b64encode(self.username.encode('UTF-8')).decode('UTF-8') def _ensure_account(self) -> None: """ Verify that both username and password are defined, and request their values if it is not the case """ if self.username is None: msg = f'Please enter your username for {self.server_name} server: ' new_username = AuthenticationAccount.asking_input['shown'](msg) self.set_credentials(username=new_username) if self.password is None: msg = f'Please enter your password for {self.server_name} server: ' new_password = AuthenticationAccount.asking_input['hidden'](msg) self.set_credentials(password=new_password) # We have to define set_credentials as abstract because we need it to propagate # token reinitialization when defining new account via _ensure_account @abstractmethod def set_credentials(self, username: Optional[str]=None, password: Optional[str]=None, token_value: Optional[str]=None) -> None: """ Set or reset the username, the password and the token. If username is not None, it is set to the provided value if it is different from the already stored one and the password is stored whatever its value. If username is None and password is not, then only the password is updated with the provided value. Otherwise username and password are both reset. :param username: the username to register :param password: the account password :param token_value: a token associated to these credentials :raises RestoClientDesignError: when an unconsistent set of arguments is provided """ @property def authorization_data(self) -> AuthorizationDataType: """ :returns: the authorization data for the service """ self._ensure_account() return {'ident': self.username, 'pass': self.password} @property def http_basic_auth(self) -> HTTPBasicAuth: """ :returns: the basic HTTP authorization for the service :raises RestoClientDesignError: when trying to build authentication while username or password is undefined. """ self._ensure_account() if self.password is None: msg = 'Unable to provide http_basic_auth when password undefined' raise RestoClientDesignError(msg) if self.username is None: msg = 'Unable to provide http_basic_auth when username undefined' raise RestoClientDesignError(msg) return HTTPBasicAuth(self.username.encode('utf-8'), self.password.encode('utf-8')) def __str__(self) -> str: return f'username: {self.username} / password: {self.password}'
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/services/authentication_account.py
0.860604
0.174235
authentication_account.py
pypi
from pathlib import Path from typing import Optional, TypeVar, List, Union, Dict, Any from resto_client.entities.resto_collection import RestoCollection from resto_client.entities.resto_feature import RestoFeature from resto_client.entities.resto_feature_collection import RestoFeatureCollection from resto_client.settings.servers_database import DB_SERVERS from .authentication_service import AuthenticationService from .resto_service import RestoService RestoServerType = TypeVar('RestoServerType', bound='RestoServer') class RestoServer(): """ A Resto Server, i.e. a valid resto accessible server or an empty one """ def __init__(self, server_name: str, current_collection: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, token: Optional[str] = None, debug_server: bool = False) -> None: """ Build a new RestoServer instance from arguments and database. :param server_name: the name of the server to use in the database :param current_collection: name of the collection to use :param username: account to use on this server :param password: account password on the server :param token: an existing token associated to this account (will be checked prior its use) :param debug_server: When True debugging information on server and requests is printed out. """ self.debug_server = debug_server # initialize the services self._server_name = DB_SERVERS.check_server_name(server_name) server_description = DB_SERVERS.get_server(self._server_name) self._authentication_service = AuthenticationService(server_description.auth_access, self) self._resto_service = RestoService(server_description.resto_access, self._authentication_service, self) # set services parameters self.current_collection = current_collection self.set_credentials(username=username, password=password, token_value=token) def set_credentials(self, username: Optional[str]=None, password: Optional[str]=None, token_value: Optional[str]=None) -> None: """ Set the credentials to be used by the authentication service. :param username: name of the account on the server :param password: account password :param token_value: a token associated to these credentials """ self._authentication_service.set_credentials(username=username, password=password, token_value=token_value) def reset_credentials(self) -> None: """ Reset the credentials used by the authentication service. """ self._authentication_service.reset_credentials() # +++++++++++++++++++++++ server properties section ++++++++++++++++++++++++++++++++++++ @property def current_collection(self) -> Optional[str]: """ :returns: the current collection """ return self._resto_service.current_collection @current_collection.setter def current_collection(self, collection_name: Optional[str]) -> None: self._resto_service.current_collection = collection_name # +++++++++++ read only properties +++++++++++ @property def server_name(self) -> str: """ :returns: the name of the server """ return self._server_name @property def username(self) -> Optional[str]: """ :returns: the username to use with this server """ return self._authentication_service.username # +++++++++++++++++++++++ proxy to resto_service functions ++++++++++++++++++++++++++++++++++++ def search_by_criteria(self, criteria: Dict[str, Any], collection_name: Optional[str] = None) -> RestoFeatureCollection: """ Search a collection using search criteria :param criteria: searching criteria :param collection_name: name of the collection to use. Default to the current collection. :returns: a collection of resto features """ return self._resto_service.search_by_criteria(criteria, collection_name) def get_features_from_ids(self, features_ids: Union[str, List[str]], collection_name: Optional[str] = None) -> List[RestoFeature]: """ Get a list of resto features retrieved by their identifiers :param features_ids: Feature(s) identifier(s) :param collection_name: name of the collection to use. Default to the current collection. :returns: a list of Resto features """ features_list = [] if not isinstance(features_ids, list): features_ids = [features_ids] for feature_id in features_ids: feature = self._resto_service.get_feature_by_id(feature_id, collection_name) features_list.append(feature) return features_list def download_feature_file(self, feature: RestoFeature, file_type: str, download_dir: Path) -> None: """ Download different files of a feature :param feature: a resto feature :param download_dir: the path to the directory where download must be done. :param file_type: type of file to download: product, quicklook, thumbnail or annexes """ self._resto_service.download_feature_file(feature, file_type, self.ensure_server_directory(download_dir)) def download_features_file_from_ids(self, features_ids: Union[str, List[str]], file_type: str, download_dir: Path) -> None: """ Download different file types from feature id(s) :param features_ids: id(s) of the feature(s) which as a file to download :param download_dir: the path to the directory where download must be done. :param file_type: type of file to download: product, quicklook, thumbnail or annexes """ # Issue a search request into the collection to retrieve features. features = self.get_features_from_ids(features_ids) for feature in features: # Do download self.download_feature_file(feature, file_type, download_dir) def ensure_server_directory(self, data_dir: Path) -> Path: """ Build the server data directory path by appending the server name to the provided argument. Creates also that directory if it does not exist yet. :param data_dir: the directory where the data directory for this server must be located. :returns: the path to the server data directory :raises RestoClientDesignError: when called while this server parameters are undefined. """ real_data_dir = data_dir / self.server_name real_data_dir.mkdir(parents=True, exist_ok=True) return real_data_dir def show_server(self, with_stats: bool=True) -> str: """ :param with_stats: if True the collections statistics are shown. :returns: The server description as a tabulated listing """ return self._resto_service.show(with_stats=with_stats) def get_collection(self, collection: Optional[str]=None) -> RestoCollection: """ Get a collection description from the resto service. :param collection: the name of the collection to retrieve :returns: the requested collection or the current one. """ return self._resto_service.get_collection(collection=collection) def __str__(self) -> str: msg_fmt = 'server_name: {} \n{}{}' return msg_fmt.format(self._server_name, str(self._resto_service), str(self._authentication_service))
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/services/resto_server.py
0.887437
0.211274
resto_server.py
pypi
from typing import Type, Dict, Optional # @NoMove from shapely.errors import WKTReadingError from resto_client.base_exceptions import RestoClientUserError from resto_client.generic.basic_types import (SquareInterval, DateYMD, GeometryWKT, AscOrDesc, Polarisation, DateYMDInterval) CriteriaDictType = Dict[str, dict] COVER_TEXT = ' expressed as a percentage and using brackets. e.g. [n1,n2[ ' INTERVAL_TXT = '{} of the time slice of {}. Format should follow RFC-3339' LATLON_TXT = 'expressed in decimal degrees (EPSG:4326) - must be used with' COMMON_CRITERIA_KEYS: CriteriaDictType COMMON_CRITERIA_KEYS = {'box': {'type': str, 'help': "Defined by 'west, south, east, north' meridians and parallels" " in that order, in decimal degrees (EPSG:4326)"}, 'identifier': {'type': str, 'help': 'Valid ID or UUID according to RFC 4122'}, 'lang': {'type': str, 'help': 'Two letters language code according to ISO 639-1'}, 'parentIdentifier': {'type': str, 'help': 'deprecated'}, 'q': {'type': str, 'help': 'Free text search / Keywords'}, 'platform': {'type': 'list', 'sub_type': str, 'help': 'Acquisition platform'}, 'instrument': {'type': 'list', 'sub_type': str, 'help': 'Satellite Instrument'}, 'processingLevel': {'type': 'list', 'sub_type': str, 'help': 'e.g. L1A, ORTHO'}, 'productType': {'type': 'list', 'sub_type': str, 'help': 'e.g. changes, landuse, etc'}, 'sensorMode': {'type': 'list', 'sub_type': str, 'help': 'Acquisition mode of the instrument'}, 'organisationName': {'type': 'list', 'sub_type': str, 'help': 'e.g. CNES'}, 'index': {'type': int, 'help': 'Results page will begin at this index'}, 'maxRecords': {'type': int, 'help': 'Number of results returned per page (default 50)'}, 'orbitNumber': {'type': int, 'help': 'Orbit Number (for satellite)'}, 'page': {'type': int, 'help': 'Number of the page to display'}, 'geometry': {'type': GeometryWKT, 'help': "Defined in Well Known Text standard (WKT) with " "coordinates in decimal degrees (EPSG:4326)"}, 'startDate': {'type': DateYMD, 'help': INTERVAL_TXT.format('Beginning', 'the search query')}, 'completionDate': {'type': DateYMD, 'help': INTERVAL_TXT.format('End', 'the search query')}, 'updated': {'type': DateYMDInterval, 'help': 'Time slice of last update of the data updatedFrom:updatedTo'}, 'resolution': {'type': SquareInterval, 'help': "Spatial resolution expressed in meter and using brackets." " e.g. [n1,n2["}, 'cloudCover': {'type': SquareInterval, 'help': 'Cloud cover' + COVER_TEXT}, 'snowCover': {'type': SquareInterval, 'help': 'Snow cover' + COVER_TEXT}, 'cultivatedCover': {'type': SquareInterval, 'help': 'Cultivated area' + COVER_TEXT}, 'desertCover': {'type': SquareInterval, 'help': 'Desert area' + COVER_TEXT}, 'floodedCover': {'type': SquareInterval, 'help': 'Flooded area' + COVER_TEXT}, 'forestCover': {'type': SquareInterval, 'help': 'Forest area' + COVER_TEXT}, 'herbaceousCover': {'type': SquareInterval, 'help': 'Herbaceous area' + COVER_TEXT}, 'iceCover': {'type': SquareInterval, 'help': 'Ice area' + COVER_TEXT}, 'urbanCover': {'type': SquareInterval, 'help': 'Urban area' + COVER_TEXT}, 'waterCover': {'type': SquareInterval, 'help': 'Water area' + COVER_TEXT}, 'geomPoint': {'type': 'group', 'lat': {'type': float, 'help': 'Latitude ' + LATLON_TXT + ' lon'}, 'lon': {'type': float, 'help': 'Longitude ' + LATLON_TXT + ' lat'} }, 'geomSurface': {'type': 'group', 'lat': {'type': float, 'help': None}, 'lon': {'type': float, 'help': None}, 'radius': {'type': float, 'help': "Expressed in meter - " "should be used with lon and lat"} }, 'region': {'type': 'region', 'help': 'Shortname of .shp file from zones folder'}, } DOTCLOUD_KEYS: CriteriaDictType DOTCLOUD_KEYS = { 'identifiers': {'type': str, 'help': 'Accept multiple identifiers i1,i2,etc.'}, 'producerProductId': {'type': str, 'help': 'Producer product identifier'}, 'location': {'type': str, 'help': 'Location string e.g. Paris, France'}, 'metadataVisibility': {'type': str, 'help': 'Hiden access of product'}, 'productMode': {'type': 'list', 'sub_type': str, 'help': 'Product production mode'}, 'license': {'type': 'list', 'sub_type': str, 'help': 'Identifier of applied license'}, 'dotcloudType': {'type': 'list', 'sub_type': str, 'help': 'Dotcloud Product Type e.g. eo_image'}, 'dotcloudSubType': {'type': 'list', 'sub_type': str, 'help': 'Dotcloud Product Sub-type e.g. optical'}, 'publishedFrom': {'type': DateYMD, 'help': INTERVAL_TXT.format('Beginning', "the product's publication")}, 'publishedTo': {'type': DateYMD, 'help': INTERVAL_TXT.format('End', "the product's publication")}, 'updatedFrom': {'type': DateYMD, 'help': INTERVAL_TXT.format('Beginning', "the product's update")}, 'updatedTo': {'type': DateYMD, 'help': INTERVAL_TXT.format('End', "the product's update")}, 'incidenceAngle': {'type': SquareInterval, 'help': 'Satellite incidence angle [n1,n2['}, 'onlyDownloadableProduct': {'type': bool, 'help': "True or False : show only downlodable products for " "the current account"}, } PEPS_VERSION_KEYS: CriteriaDictType PEPS_VERSION_KEYS = {'latitudeBand': {'type': str, 'help': ''}, 'mgrsGSquare': {'type': str, 'help': ''}, 'realtime': {'type': str, 'help': ''}, 's2TakeId': {'type': str, 'help': ''}, 'isNrt': {'type': str, 'help': ''}, 'location': {'type': str, 'help': 'Location string e.g. Paris, France'}, # resolution overwritten but not available on peps 'resolution': {'type': str, 'help': 'not available on peps'}, 'relativeOrbitNumber': {'type': int, 'help': 'Should be an integer'}, 'orbitDirection': {'type': AscOrDesc, 'help': 'ascending or descending'}, 'polarisation': {'type': Polarisation, 'help': "For Radar : 'HH', 'VV', 'HH HV' or 'VV VH'"}, 'publishedBegin': {'type': DateYMD, 'help': INTERVAL_TXT.format('Beginning', "the product's publication")}, 'publishedEnd': {'type': DateYMD, 'help': INTERVAL_TXT.format('End', "the product's publication")}, } THEIA_VERSION_KEYS: CriteriaDictType THEIA_VERSION_KEYS = {'location': {'type': str, 'help': 'Location string e.g. Paris, France'}, 'locationVECTOR': {'type': str, 'help': ''}, 'locationRASTER': {'type': str, 'help': ''}, 'typeOSO': {'type': str, 'help': ''}, 'OSOsite': {'type': str, 'help': ''}, 'OSOcountry': {'type': str, 'help': ''}, 'country': {'type': str, 'help': ''}, 'name': {'type': str, 'help': ''}, 'state': {'type': str, 'help': ''}, 'tileId': {'type': str, 'help': "e.g. T31TCJ"}, 'zonegeo': {'type': str, 'help': ''}, 'relativeOrbitNumber': {'type': int, 'help': ''}, 'year': {'type': int, 'help': ''}, 'nbColInterpolationErrorMax': {'type': int, 'help': ''}, 'percentSaturatedPixelsMax': {'type': int, 'help': ''}, 'percentNoDataPixelsMax': {'type': int, 'help': ''}, 'percentGroundUsefulPixels': {'type': int, 'help': ''}, 'percentUsefulPixelsMin': {'type': int, 'help': ''}, } CREODIAS_VERSION_KEYS: CriteriaDictType CREODIAS_VERSION_KEYS = {'bands': {'type': str, 'help': ''}, 'cycle': {'type': str, 'help': ''}, 'missionTakeId': {'type': str, 'help': ''}, 'productIdentifier': {'type': str, 'help': ''}, 'product_id': {'type': str, 'help': ''}, 'phase': {'type': str, 'help': ''}, 'swath': {'type': str, 'help': ''}, 'sortParam': {'type': str, 'help': ''}, 'status': {'type': str, 'help': ''}, 'row': {'type': str, 'help': ''}, 'path': {'type': str, 'help': ''}, 'version': {'type': str, 'help': ''}, 'name': {'type': str, 'help': ''}, 'dataset': {'type': int, 'help': ''}, 'sortOrder': {'type': AscOrDesc, 'help': 'ascending or descending'}, 'publishedAfter': {'type': DateYMD, 'help': INTERVAL_TXT.format('Beginning', "the product's publication")}, 'publishedBefore': {'type': DateYMD, 'help': INTERVAL_TXT.format('End', "the product's publication")}, } SPECIFIC_CRITERIA_KEYS: Dict[str, CriteriaDictType] SPECIFIC_CRITERIA_KEYS = {'dotcloud': DOTCLOUD_KEYS, 'peps_version': PEPS_VERSION_KEYS, 'theia_version': THEIA_VERSION_KEYS, 'creodias_version': CREODIAS_VERSION_KEYS } def get_criteria_for_protocol(protocol_name: Optional[str]) -> CriteriaDictType: """ :param protocol_name: the protocol name or None if only common criteria are requested. :returns: the criteria definition associated to a resto protocol, or the common criteria only if the resto protocol name is None. """ protocol_criteria: CriteriaDictType = {} protocol_criteria.update(COMMON_CRITERIA_KEYS) if protocol_name is not None: protocol_criteria.update(SPECIFIC_CRITERIA_KEYS[protocol_name]) return protocol_criteria def test_criterion(key: str, value: object, auth_key_type: Type) -> None: """ A function to test criterion and return the value to store if acceptable :param value: value to store as criterion :param auth_key_type: authorized type for the associated key :param key: name of the criterion :raises RestoClientUserError: when a criterion has a wrong type """ try: str_value = str(value) auth_key_type(str_value) except (ValueError, WKTReadingError): msg = 'Criterion {} has an unexpected type : {}, expected : {}' raise RestoClientUserError(msg.format(key, type(value).__name__, auth_key_type.__name__))
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/entities/resto_criteria_definition.py
0.894881
0.176175
resto_criteria_definition.py
pypi
from typing import Dict, List, Optional # @NoMove from prettytable import PrettyTable from resto_client.base_exceptions import RestoClientUserError from .resto_collection import RestoCollection class RestoCollections(): """ Class containing the description of a set of collections as well as their synthesis. This class has no knowledge of the current collection concept. See :class:`~resto_client.services.resto_collections_manager.RestoCollectionsManager` for this topic. """ def __init__(self) -> None: """ Constructor """ self._synthesis: Optional[RestoCollection] = None self._collections: Dict[str, RestoCollection] = {} def add(self, collection: RestoCollection) -> None: """ Add a new collection in this collections set. :param collection: a collection to add in this set of collections. :raises TypeError: if collection is not of the right type. :raises IndexError: if a collection with same name already exists in the set of collections. :raises NotImplementedError: when a collection already exists with same lowercased name. """ if not isinstance(collection, RestoCollection): msg_err = 'collection argument must be of RestoCollection type. Found {} instead.' raise TypeError(msg_err.format(type(collection))) # FIXME: use self.normalize_name if collection.name in self._collections: raise IndexError('A collection with name {} already exists.'.format(collection.name)) if collection.name is None: raise IndexError('Cannot add a collection without knowing its name.') if collection.name.lower() in self._lowercase_names: msg_err = 'Cannot add a collection {} with already existing name when lowercased!! : {}' raise NotImplementedError(msg_err.format(collection.name, self.names)) self._collections[collection.name] = collection def get_collections(self) -> Dict[str, RestoCollection]: """ :returns: the collections defined in this set of collections. """ return self._collections @property def synthesis(self) -> Optional[RestoCollection]: """ :returns: the synthesis of this set of collections. """ return self._synthesis @synthesis.setter def synthesis(self, synthesis: Optional[RestoCollection]) -> None: """ :param synthesis: the synthesis of this set of collections. :raises TypeError: if synthesis is not of the right type. """ if not isinstance(synthesis, (RestoCollection, type(None))): msg_err = 'synthesis must be None or of RestoCollection type. Found {} instead.' raise TypeError(msg_err.format(type(synthesis))) self._synthesis = synthesis @property def names(self) -> List[str]: """ :returns: the names of the collections available in this collections set. """ return list(self._collections.keys()) @property def _lowercase_names(self) -> List[str]: """ :returns: the lowercase names of the collections available in this collections set. """ return [name.lower() for name in self.names] def normalize_name(self, collection_name: str) -> str: """ Returns the collection name with case adapted to fit an existing collection. :param collection_name: the name of the collection whose name must be normalized. :raises RestoClientUserError: if the collection is not found in the set of collections. :returns: the collection name translated with the right case to fit an existing collection. """ lowercase_collection_name = collection_name.lower() if lowercase_collection_name not in self._lowercase_names: raise RestoClientUserError('No collection found with name {}'.format(collection_name)) normalized_name_index = self._lowercase_names.index(lowercase_collection_name) return self.names[normalized_name_index] @property def default_collection(self) -> Optional[str]: """ :returns: the name of the default collection (None if not exactly 1 collection) """ return None if len(self.names) != 1 else self.names[0] def str_statistics(self) -> str: """ :returns: the statistics of each collections and of the collections set. """ out_str = '' for collection in self._collections.values(): out_str += '\n' + str(collection.statistics) if self.synthesis is not None: out_str += str(self.synthesis.statistics) else: out_str += 'No synthesis statistics./n' return out_str def str_collection_table(self, annotate: Optional[str]=None, suffix: str='') -> str: """ :param annotate: name of a collection which must be annotated with the provided suffix. :param suffix: suffix to put at the end of the specified annotated collection name. :returns: a table listing all the collections with one of them possibly annotated :raises ValueError: when annotate does not correspond to a known collection name. """ if annotate is not None and annotate not in self.names: msg_err = 'Unknown collection to annotate: {}. Known collections: {}' raise ValueError(msg_err.format(annotate, self.names)) collections_table = PrettyTable() collections_table.field_names = RestoCollection.table_field_names for collection in self._collections.values(): collection_fields = collection.get_table_row() if collection_fields[0] == annotate: if collection_fields[0] is not None: collection_fields[0] += suffix collections_table.add_row(collection_fields) return collections_table.get_string()
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/entities/resto_collections.py
0.805785
0.280635
resto_collections.py
pypi
from typing import List, Optional # @NoMove import json from pathlib import Path import geojson from prettytable import PrettyTable from .resto_feature import RestoFeature class RestoFeatureCollection(geojson.FeatureCollection): """ Class representing a Resto feature collection. """ def __init__(self, feature_coll_descr: dict) -> None: """ Constructor :param feature_coll_descr: Feature collection description :raises TypeError: When type in descriptor is different from 'FeatureCollection' """ if feature_coll_descr['type'] != 'FeatureCollection': msg = 'Cannot create a feature collection whose type is not FeatureCollection' raise TypeError(msg) self.resto_features = [RestoFeature(desc) for desc in feature_coll_descr['features']] super(RestoFeatureCollection, self).__init__(properties=feature_coll_descr['properties'], features=self.resto_features) @property def identifier(self) -> str: """ :returns: the feature collection's unique id """ return self.properties['id'] @property def query(self) -> str: """ :returns: the query which created this feature collection """ return self.properties['query'] @property def total_results(self) -> Optional[int]: """ :returns: the total number of results corresponding to the query (but not to this Feature Collection) """ return self.properties['totalResults'] @property def start_index(self) -> int: """ :returns: the index of the first feature in this feature collection within the whole query result. """ return self.properties['startIndex'] @property def all_id(self) -> List[str]: """ :returns: the identifiers of all features in this feature collection """ return [feature.product_identifier for feature in self.features] def get_feature(self, feature_id: str) -> RestoFeature: """ Get the feature from this features collection with the requested id :param feature_id: identifier of the feature to retrieve :returns: a resto feature :raises KeyError: when no feature with the specified identifier can be found. """ result = [feat for feat in self.resto_features if feat.product_identifier == feature_id] if len(result) != 1: raise KeyError(f'No feature found with id: {feature_id}') return result[0] def write_json(self, dir_path: Path) -> Path: """ Save the current entity in a json file :param dir_path: Path where to write the json :returns: Path of the saved json file """ json_name = 'request_{}.json'.format(self.identifier) with open(dir_path / json_name, 'w') as stream: json.dump(self, stream, indent=2) return dir_path / json_name def __str__(self) -> str: if self.properties is not None: result = '\nProperties available for the FeatureCollection\n' feat_table = PrettyTable() feat_table.field_names = ['Property', 'Value'] feat_table.align['Value'] = 'l' feat_table.align['Property'] = 'l' for product_property in self.properties: show_param = str(self.properties[product_property]) feat_table.add_row([product_property, show_param]) feat_table.add_row(["all_id", str(self.all_id)]) result += feat_table.get_string() result += '\n' return result
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/entities/resto_feature_collection.py
0.889457
0.340636
resto_feature_collection.py
pypi
from prettytable import PrettyTable class RestoLicense(dict): """ Class representing a license as given by Resto, either on a collection or on a feature """ def __init__(self, item_description: dict) -> None: """ Constructor. :param item_description: feature properties or collection item into which license information can be found. """ super(RestoLicense, self).__init__() license_entry = item_description.get('license') license_info = item_description.get('license_info') self._license_infos: dict if license_entry is None or license_info is not None: self._license_infos = {'description': {'shortName': 'No license'}, 'grantedCountries': None, 'grantedFlags': None, 'grantedOrganizationCountries': None, 'hasToBeSigned': 'never', 'licenseId': 'unlicensed', 'signatureQuota': -1, 'viewService': 'public'} if license_info is not None: for key, value in license_info.items(): self._license_infos['description'][key] = value if 'en' in license_info: self._license_infos['description']['shortName'] = \ license_info['en']['short_name'] elif 'fr' in license_info: self._license_infos['description']['shortName'] = \ license_info['fr']['short_name'] else: self._license_infos['description']['shortName'] = 'Undefined' self._license_infos['licenseId'] = license_entry else: self._license_infos = license_entry # Remove license information from item_description RestoLicense._clean_license_in_item(item_description) self.update(self._license_infos) @staticmethod def _clean_license_in_item(item_description: dict) -> None: """ Remove license information from item_description :param item_description: feature properties or collection item into which license information is stored. """ if 'license' in item_description: del item_description['license'] if 'license_info' in item_description: del item_description['license_info'] @property def short_name(self) -> str: """ :returns: the license short name, in english """ return self._license_infos['description']['shortName'] @property def identifier(self) -> str: """ :returns: the license identifier """ return self._license_infos['licenseId'] def __str__(self) -> str: license_table = PrettyTable() if isinstance(self, RestoCollectionLicense): license_table.title = 'Collection license' else: license_table.title = 'Feature license' license_table.field_names = ['License field', 'Value'] license_table.align['Value'] = 'l' license_table.align['License field'] = 'l' for key1, value1 in self._license_infos.items(): property_field1 = str(key1) if isinstance(value1, dict): for key2, value2 in value1.items(): property_field2 = (property_field1 + ' : {}').format(key2) if isinstance(value2, dict): for key3, value3 in value2.items(): property_field3 = (property_field2 + ' : {}').format(key3) license_table.add_row([property_field3, value3]) else: license_table.add_row([property_field2, value2]) else: license_table.add_row([property_field1, value1]) return license_table.get_string() class RestoCollectionLicense(RestoLicense): """ Class representing a license associated to a collection. """ class RestoFeatureLicense(RestoLicense): """ Class representing a license associated to a feature """
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/entities/resto_license.py
0.784443
0.168994
resto_license.py
pypi
import json from typing import Optional, Dict # @NoMove from pathlib import Path import geojson from prettytable import PrettyTable from resto_client.base_exceptions import RestoClientUserError, RestoClientDesignError from .resto_license import RestoFeatureLicense KNOWN_FILES_TYPES = ['product', 'quicklook', 'thumbnail', 'annexes'] class RestoFeature(geojson.Feature): """ Class representing a Resto feature. """ def __init__(self, feature_descr: dict) -> None: """ Constructor. :param feature_descr: Feature description :raises TypeError: When Feature type in descriptor is different from 'Feature' """ if feature_descr['type'] != 'Feature': raise TypeError('Cannot create a feature whose type is not Feature') super(RestoFeature, self).__init__(id=feature_descr['id'], geometry=feature_descr['geometry'], properties=feature_descr['properties']) self.license = RestoFeatureLicense(feature_descr['properties']) self.downloaded_files_paths: Dict[str, Path] self.downloaded_files_paths = {} def get_download_url(self, file_type: str) -> str: """ Return the URL for downloading a file type associated to the feature. :param file_type: code of the file type: must belong to KNOWN_FILES_TYPES :returns: the URL for downloading this file type, as defined in the feature properties :raises RestoClientDesignError: when file_type is unsupported :raises RestoClientUserError: when no URL defined in the feature properties for the requested file type. """ if file_type not in KNOWN_FILES_TYPES: msg = 'Unsupported file type: {}. Must be one of: {}.' raise RestoClientDesignError(msg.format(file_type, KNOWN_FILES_TYPES)) url_to_download = None if file_type == 'quicklook': url_to_download = self.download_quicklook_url if file_type == 'thumbnail': url_to_download = self.download_thumbnail_url if file_type == 'product': url_to_download = self.download_product_url if file_type == 'annexes': url_to_download = self.download_annexes_url if url_to_download is None: msg = 'There is no {} to download for product {}.' raise RestoClientUserError(msg.format(file_type, self.product_identifier)) return url_to_download @property def title(self) -> str: """ :returns: the title """ return self.properties['title'] @property def description(self) -> str: """ :returns: the description """ return self.properties['description'] @property def organisationName(self) -> str: """ :returns: the organisationName """ return self.properties['organisationName'] @property def lang(self) -> str: """ :returns: the associated language """ return self.properties['lang'] @property def parent_identifier(self) -> str: """ :returns: the parentIdentifier """ return self.properties['parentIdentifier'] @property def platform(self) -> str: """ :returns: the platform """ return self.properties['platform'] @property def instrument(self) -> str: """ :returns: the instrument """ return self.properties['instrument'] @property def processing_level(self) -> str: """ :returns: the processingLevel """ return self.properties['processingLevel'] @property def sensor_mode(self) -> str: """ :returns: the sensorMode """ return self.properties['sensorMode'] @property def start_date(self) -> str: """ :returns: the startDate """ return self.properties['startDate'] @property def completion_date(self) -> str: """ :returns: the completionDate """ return self.properties['completionDate'] @property def updated(self) -> str: """ :returns: the updated """ return self.properties['updated'] @property def resolution(self) -> str: """ :returns: the resolution """ return self.properties['resolution'] @property def orbitNumber(self) -> str: """ :returns: the orbitNumber """ return self.properties['orbitNumber'] @property def download_quicklook_url(self) -> str: """ :returns: the quicklook URL """ return self.properties['quicklook'] @property def download_thumbnail_url(self) -> str: """ :returns: the thumbnail url """ return self.properties['thumbnail'] @property def download_annexes_service(self) -> dict: """ :returns: the entire annexes service which was stored in json """ annexes_existence = self.properties.get('annexes') is not None return json.loads(self.properties['annexes'])[0] if annexes_existence else None @property def download_annexes_name(self) -> Optional[str]: """ :returns: the annexes service name """ if self.download_annexes_service is not None: return self.download_annexes_service['name'] return None @property def download_annexes_url(self) -> Optional[str]: """ :returns: the annexes URL. """ if self.download_annexes_service is not None: return self.download_annexes_service['url'] return None @property def product_crs(self) -> Optional[str]: """ :returns: the prudct_crs without dictionary """ if self.properties['productCrs'] is not None: return json.loads(self.properties['productCrs'])['crs']['properties']['name'] return None @property def download_product_service(self) -> dict: """ :returns: the entire download service """ return self.properties['services']['download'] @property def download_product_url(self) -> str: """ :returns: the product URL. """ return self.download_product_service['url'] @property def product_mimetype(self) -> Optional[str]: """ :returns: the product mimetype. """ return self.download_product_service.get('mimeType') @property def product_size(self) -> Optional[int]: """ :returns: the product size in bytes or None if unavailable. """ prod_size = self.download_product_service.get('size') if prod_size is not None: prod_size = int(prod_size) return prod_size @property def product_checksum(self) -> Optional[str]: """ :returns: the product checksum. """ return self.download_product_service.get('checksum') @property def product_identifier(self) -> str: """ :returns: the feature productIdentifier. """ return self.properties['productIdentifier'] @property def product_type(self) -> str: """ :returns: the feature productType. """ return self.properties['productType'] @property def storage(self) -> Optional[str]: """ :returns: the product storage. """ if self.properties.get('storage') is not None: return self.properties.get('storage').get('mode') return None def __str__(self) -> str: if self.properties is not None: result = '\nMetadata available for product {}\n'.format(self.product_identifier) exclude_entities = ['links', 'keywords', 'annexes'] second_entities = ['services'] feat_table = PrettyTable() feat_table.field_names = ['Property', 'Value'] feat_table.align['Value'] = 'l' feat_table.align['Property'] = 'l' # Print global property directly seen for product_property in self.properties: if product_property not in exclude_entities + second_entities: show_param: Optional[str] = str(self.properties[product_property]) if product_property == 'description': show_param = str(show_param)[:40] + '[...]' if product_property == 'productCrs': show_param = self.product_crs feat_table.add_row([product_property, show_param]) result += feat_table.get_string() result += '\n' # Print additional property englobed in a dictionnary for product_property in second_entities: result += self._build_second_table(product_property) result += '\n' # Print annexes property because annexes are stocked in an str if self.download_annexes_service is not None: annexe_table = PrettyTable() annexe_table.field_names = ['Annexes', 'Value'] annexe_table.add_row(['name', self.download_annexes_name]) annexe_table.add_row(['url', self.download_annexes_url]) annexe_table.align['Value'] = 'l' annexe_table.align['Annexes'] = 'l' result += annexe_table.get_string() result += '\n' result += str(self.license) else: result = 'No metadata available for {}'.format(self.product_identifier) return result def _build_second_table(self, product_property: str) -> str: """ Print the service of the feature """ second_table = PrettyTable() second_table.field_names = [product_property, 'Value'] second_table.align['Value'] = 'l' second_table.align[product_property] = 'l' for key_head in self.properties[product_property].keys(): for key, value in self.properties[product_property][key_head].items(): property_field = '{} : {}'.format(key_head, key) if isinstance(value, dict): for key_int, value_int in value.items(): property_field = '{} : {} : {}'.format(key_head, key, key_int) second_table.add_row([property_field, value_int]) else: second_table.add_row([property_field, value]) return second_table.get_string()
/resto_client-0.5.0.tar.gz/resto_client-0.5.0/resto_client/entities/resto_feature.py
0.831177
0.225417
resto_feature.py
pypi
import math from typing import Union from ..exceptions import LoginException, SessionException from ..filters import SellMethod, ListingDuration from .core import ClientCore from ..product import SIZES_IDS, Product class Client(ClientCore): def __init__(self, proxy: Union[dict, list] = None) -> None: """ Initializes a Restocks.net client with the option to log into your personal account. Args: proxy: a single or multiple proxies to use for the requests. Proxies will rotate at each request for methods which do not require a log in. A random static proxy will be used for all the requests after you log in. """ super().__init__(proxy) def login(self, email: str, password: str): """ Logs into your Restocks.net account. Args: email: your Restocks.net account email. password: your Restocks.net account password. """ self._set_locale_request() login_page = self._login_page_request() csrf_token = self._csrf_token_parsing(login_page) if not csrf_token: raise LoginException("csrf-token not found") res = self._login_with_token_request(csrf_token, email, password) if "loginForm" in res: raise LoginException("invalid login credentials") main_page = self._main_page_request() session_token = self._csrf_token_parsing(main_page) if not csrf_token: raise LoginException("session token not found") self._session_token = session_token def get_sales_history(self, query: str = None, page: int = 1) -> list[Product]: """ Gets the account product sales history. Args: query: query to base the search on. Defaults to None. page: the page number. One page contains 48 products. Defaults to 1. Raises: SessionException: if no sales were found. Returns: List containing the history all the account sold products. """ res = self._sales_history_request(query or "", page) src = res["products"] if "no__listings__notice" in src: raise SessionException("no sales found") sales = self._sales_history_parsing(src) return [Product._from_json(s) for s in sales] def get_listings_history(self, query: str = None, page: int = 1, sell_method: SellMethod = SellMethod.Resell) -> list[Product]: """ Gets the account listings history. Args: query: a query to base the search on. Defaults to None. page: the page number. One page contains 48 products. Defaults to 1. Raises: SessionException: if no listings were found. Returns: A list containing all the account listed products. """ res = self._listings_history_request( query or "", page, "consignment" if sell_method == SellMethod.Consign else sell_method) src = res["products"] if "no__listings__notice" in src: raise SessionException("no listings found") listings = self._listings_history_parsing(src) return [Product._from_json(l) for l in listings] def search_products(self, query: str, page: int = 1) -> list[Product]: """ Searches for products based on a provided query. Args: query: query to base the search on. page: the page number. One page contains 48 products. Defaults to 1. Returns: List containing the found products and his data. """ res = self._search_product_request(query, page) if not res["data"]: page = math.ceil(res["total"] / 48) res = self._search_product_request(query, page) return [Product._from_json(p) for p in res["data"]] def get_product(self, sku_or_query: str) -> Product: """ Gets the full data of a product. Args: sku_or_query: either the SKU code of the sneaker or a name to base the search on. Returns: The product data """ res = self._search_product_request(sku_or_query, 1) product = res["data"][0] p = Product._from_json(product) src = self._product_request(p.slug) variants = self._product_parsing(src) product["variants"] = variants return Product._from_json(res["data"][0]) def get_size_lowest_price(self, product_id: int, size: str) -> int: """ Gets the lowest price for a product size. Args: product_id: the product id. size: the product size. Returns: The size lowest price. """ size_id = SIZES_IDS.get(size) if not size: raise SessionException("invalid size") res = self._size_lowest_price_request(product_id, size_id) return int(res) def list_product(self, product: Union[Product, str], store_price: int, size: str, sell_method: SellMethod, duration: ListingDuration) -> bool: """ Lists a product for sale. Args: product: either the `Product` object or the product sku. store_price: the price for the listing. size: the product size you are willing to sell. sell_method: the selling method. duration: the listing duration. Returns: A boolean that indicates if the product was listed successfuly. """ if not isinstance(product, Product): product = self.get_product(product) price = self._get_sell_profit(store_price, sell_method) size_id = SIZES_IDS.get(size) if not size: raise SessionException("invalid size") res = self._create_listing_request( product_id=product.id, sell_method=sell_method, size_id=size_id, store_price=store_price, price=price, duration=duration ) return "success" in res["redirectUrl"] def edit_listing(self, listing_id: int, new_price: int) -> bool: """ Edit the price of a current listing. Args: listing_id: the listing id. new_price: the new price. Returns: A boolean that indicates if the listing was edited successfuly. """ res = self._edit_listing_request(listing_id, new_price) return res.get("success", False) def delete_listing(self, listing_id: int) -> bool: """ Delete a current listed product. Args: listing_id: the listing id. Returns: A boolean that indicates if the listing was deleted successfuly. """ res = self._delete_listing_request(listing_id) return res.get("success", False)
/restocks_client-0.1.3-py3-none-any.whl/restocks/client/client.py
0.866782
0.296966
client.py
pypi
# Rest-o-matic Automatic JSON-based API generator, including a SQL Query Compositor and WSGI Endpoint Router [![CircleCI](https://circleci.com/gh/dtulga/restomatic/tree/master.svg?style=svg)](https://circleci.com/gh/dtulga/restomatic/tree/master) [![codecov](https://codecov.io/gh/dtulga/restomatic/branch/master/graph/badge.svg)](https://codecov.io/gh/dtulga/restomatic) ## Warning: This software is in alpha, and API or function signatures may change before full release. ## Usage This package includes three primary components: ### Rest-o-matic Endpoints / API Description This system generates JSON endpoints automatically for tables utilizing the included SQL Query Compositor and WSGI Endpoint router Create a new set of endpoints with the command: ``` from restomatic.json_sql_compositor import SQLiteDB from restomatic.wsgi_endpoint_router import EndpointRouter from restomatic.endpoint import register_restomatic_endpoint table_mappers = { 'table_name': ['column1', 'column2', ...], ... } db = SQLiteDB(database_filename, table_mappers) router = EndpointRouter() register_restomatic_endpoint(router, db, 'table_name', ['GET', 'PUT', 'POST', 'PATCH', 'DELETE']) ... ``` Any set of methods is valid to allow. Methods not provided will return 405 Method Not Allowed errors if disallow_other_methods is set to True. ### GET (returns 200 if found, 404 if no match) ``` GET one: /table/1 ``` Returns: The requested row as a JSON object (dictionary) ### POST (returns 201 for create, 200 for search, on success) This endpoint creates a new row (or multiple new rows) Also supports a get-like search (but without the limits on uri size/format) ``` POST one: /table body: {...} or POST many: /table body: [{...}, {...}] or POST-based search: /table/search (returns 200 if found, 404 if no matches) body: {'where': [...search criteria...]} Optionally, can also include in addition to the where clause: 'limit': 1, 'offset': 2, 'order_by': ['column_1', {'column': 'column_2', 'direction': 'ASC'}] ``` The IDs of the created instances are returned as well. ### PUT (returns 200 on success) This endpoint can create or update the given rows ``` PUT one: /table body: {...} (if ID specified, update, otherwise create) or PUT many: /table body: [{...}, {...}] (if ID specified, update, otherwise create) ``` ### PATCH (returns 200 on success) This endpoint updates the given row or based on the given where condition ``` PATCH one: /table/1 body: {...} or PATCH many: /table/where body: {'where': [...search criteria...], 'set': {...}} ``` ### DELETE (returns 200 on success) This endpoint deletes the given row or based on the given where condition ``` DELETE one: /table/1 or DELETE many: /table/where body: {'where': [...search criteria...]} ``` ### Search Criteria Format The search criteria is a list which contains two or three elements, the column, an operator to compare, and a value (unless the operator does not need a value.) In addition, search criteria can be combined with 'and' or 'or' by adding all desired comparison statements (two or three element lists) into a list with a dictionary with either 'and' or 'or' as the key. (See example below) Search Criteria Examples: ``` ['id', 'isnotnull'] ['id', 'eq', 1] ['value', 'lt', 1.3] ['id', 'gte', 2] ['description', 'like', '%ABC%'] ['value', 'isnull'] ['description', 'in', ['test 1', 'test 5']] ['description', 'not_in', ['test 1', 'test 2', 'test 3']] ``` Operators should be one of: ``` 'eq', '=', '==' 'lt', '<' 'gt', '>' 'lte', '<=' 'gte', '>=' 'in' 'notin', 'not_in' 'like' 'isnull', 'is_null' 'isnotnull', 'is_not_null' ``` (Operators in each row are equivalent) Example Search: ``` POST /test/search {'where': ['id', 'lte', 3]} ``` With an AND statement: ``` POST /test/search { 'where': { 'and': [ ['id', 'lte', 3], ['id', '>', 1] ] } } ``` ### SQL Query Compositor / SQLite DB Interface This provides a convenient and secure way of interacting with a local SQLite DB, allowing one to construct SQL queries through python functions, rather than by string manipulation. It also supports parameter binding, to prevent the most common kind of SQL injection attacks. To utilize the query compositor, first create a database reference: ``` db = SQLiteDB('test.db', table_mappers) ``` This will create the database file (but not the tables) if it does not exist. You can also provide ':memory:' for an in-memory-only sqlite database. Then one can perform select, update, insert, and delete statements as such: ``` db.select_all('test').where({'and': [['id', 'gte', 2], ['id', 'lt', 3]]}).one() == (2, 'test 2', 1.5) db.select_all('test').where(['id', 'isnotnull']).all_mapped() == [{'id': 1, 'description': 'test 1', 'value': 0.5}] db.select_all('test').count().scalar() == 2 db.select_all('test').where(['id', 'gte', 3]).one_or_none_mapped() is None db.insert('test', ('description', 'value')).values(('test 2', 1.5)) db.insert_mapped('test', ({'description': 'test 3', 'value': 3.0}, {'description': 'test 4', 'value': 4.4})) db.delete('test').where(('id', 'eq', 4)).run() db.update_mapped('test', {'value': 2.0}).where(('id', 'eq', 1)).run() db.commit() # Required for persisting any transactional changes. ``` Note that generally the _mapped() forms will return a JSON-like dict, the plain forms will return tuples in either the table order (for select_all) or the columns provided order (if columns are specified). In addition, scalar() will return a the first value only, such as for count queries. In addition, all() functions return lists of results, while one() returns only one (and will raise an error if not found), and one_or_none() returns either one result or None if not found. Also note that the format used by the filter functions (such as where and order_by) is the same as the API format described above and utilized by the restomatic endpoints. See the test file for a full treatment on all possible usages and return values/formats. ### WSGI Endpoint Router This provides a lightweight and convenient way of routing multiple endpoints based on request method (GET, PUT, POST, PATCH, DELETE) and the requested uri (such as /index or /table). It also supports both exact-match and prefix-match for uris, and auto-parses/returns formats of plain text, JSON, and form-input, html-output. It can be instantiated with: ``` from restomatic.wsgi_endpoint_router import EndpointRouter router = EndpointRouter(default_in_format='plain', default_out_format='plain') ``` Optionally specifying the server default formats. Endpoints are then registered as: ``` router.register_endpoint(endpt_index, exact='/', method='GET') router.register_endpoint(endpt_get_json, prefix='/get_json', method='GET', out_format='json') router.register_endpoint(endpt_patch_json, exact='/patch_json', method='PATCH', in_format='json', out_format='json') ``` With each endpoint definition specifying first the function to handle the endpoint call, and allowed to specify either an exact or prefix match, an HTTP method to handle, and in and out format to automatically handle. Endpoint functions have this signature: ``` def endpoint_index(request): ...create data... return data ``` The return value can be either of: ``` response_data response_data, status_code response_data, status_code, additional_headers ``` Where additional headers can either be in the format: ``` {'X-Example': 'Header-Value'} ``` or ``` [('Content-Type', 'text/plain')] ``` If the content-type header is provided, it can be used to override the default based on the endpoint definition. See the test file for a full treatment on all possible usages and return values/formats. ### Advanced Usage (Pre-/post-processing, etc.) In addition, you can add pre- and post- processors, to perform validation of data inputs, and also for custom type handling. These can be added at database connection time, for example: ``` db = SQLiteDB('file.db', table_mappers, preprocessors={ 'table_name': { 'description': description_validator, 'value': value_preprocessor, }, }, postprocessors={ 'table_name': { 'value': value_postprocessor, } }) ``` Preprocessors can raise exceptions to indicate invalid data, which will then abort the current SQL query or request. Postprocessors can format the data in other ways (different than the internal data format), and along with matching preprocessors can be used to effectively create custom data types. ### Foreign Key Support Sqlite by default does not enforce foreign keys, to enable support, simply set the flag at database connection time: ``` db = SQLiteDB('example.db', table_mappers, enable_foreign_key_constraints=True) ``` This will then throw a sqlite3.IntegrityError if a foreign key constraint is not satisfied. ## Install Requires Python 3.6+ with no other external dependencies. However, a WSGI server will be required, such as uWSGI. To use uWSGI, you can install it as such: ``` pip3 install uwsgi ``` You may need dependent packages (depending upon the system) such as python3-dev and build-essential to install uWSGI, for full instructions see: https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html In addition, to run the unit tests, pytest is required, and pytest-cov recommended. ## Planned Features * Greater database support, including PostgreSQL / MySQL * Support for more types, such as enums and booleans * Automatic table creation, plus check constraints (for ranges/positive/etc.) * Support for pre- and post- processing data for better validation and structure * Ability to use decorators, authorization, and logging for better security and customization * Support for JOINs and possibly foreign key relationship loading * Support for Flask (option to be used instead of the provided WSGI router)
/restomatic-0.2.1.tar.gz/restomatic-0.2.1/README.md
0.445771
0.886125
README.md
pypi
# restoreEpics A simple package that gives wrapped caput and writeMatrix functions for writing EPICS channels which save previous values and a restoreEpics function can be used later to restore all values in case of error, interrupt, or as a final restore. ## Usage ### Restoring channels ```python from restoreEpics import restoreEpics, caput, caget try: # do some work that uses caget or caput as usual except BaseException: # Handle error cases finally: restoreEpics() # Will restore all changes to previous values ``` ### Writing to matrices with form basename_ii_jj_suffix ```python from restoreEpics import restoreEpics, writeMatrix try: writeMatrix(basename, mat, suffix=suffix, tramp=10) except BaseException: # Handle error cases finally: restoreEpics() # Will restore all changes to previous values ``` ### Writing multiple channels with option of ramping together ```python from restoreEpics import restoreEpics, writeChannels try: chanInfo = {'channels': {'C1:FIRST_CH': {'value': 5}, 'C1:SECON_CH': {'value': 10}}, 'tramp': 4} writeChannels(chanInfo) except BaseException: # Handle error cases finally: restoreEpics() # Will restore all changes to previous values ``` ### Make your own restoring methods ```python from restoreEpics import restoreEpics, backUpVals, restoreMethods from awg import Sine def exciteSine(ch, freq, ampl, duration=10, ramptime=1, bak=backUpVals): exc = Sine(ch, freq, ampl, duration=duration) exc.start(ramptime=ramptime) if ch in bak: bak[ch] = {'type': 'excSine', # Store the exc object wth a type defined. 'name': ch, # Values 'exc': exc, # Values 'sno': len(bak)} # Assign a serial number like this def restoreExc(bakVal): bakVal['exc'].stop() # Restoring method for excitation. # Add the restoring method to restoreMethods dictionary with type defined above as key restoreMethods['excSine'] = restoreExc try: exciteSine('blah', 0.5, 10) except BaseException: # Handle error cases finally: restoreEpics() # Will restore all changes to previous values ``` ## Command line tools The readMatrix and writeMatrix functions are available as command line tools on installation through pip. Usage: ```bash $ readMatrix -h usage: readMatrix [-h] [--firstRow FIRSTROW] [--firstCol FIRSTCOL] [-s SUFFIX] basename inMatFile rows cols This reads matrix coefficients from EPICS channels to a text file to. Note that all indices start from 1 by convention for EPICS channels. positional arguments: basename Matrix EPICS base name inMatFile Input Matrix file name rows Number of rows to read. Default None(all) cols Number of columns to read. Default None(all) optional arguments: -h, --help show this help message and exit --firstRow FIRSTROW First index of output. Default 1 --firstCol FIRSTCOL First index of input. Default 1 -s SUFFIX, --suffix SUFFIX Any suffix after the matrix indices in channel names. Default is None. ``` ```bash $ writeMatrix -h usage: writeMatrix [-h] [-r ROWS] [-c COLS] [--firstRow FIRSTROW] [--firstCol FIRSTCOL] [--fileRowInd FILEROWIND] [--fileColInd FILECOLIND] [-t TRAMP] [-s SUFFIX] inMatFile basename This writes matrix coefficients from a text file to EPICS channels. Note that all indices start from 1 by convention for EPICS channels. positional arguments: inMatFile Input Matrix file name basename Matrix EPICS base name optional arguments: -h, --help show this help message and exit -r ROWS, --rows ROWS Number of rows to write. Default None(all) -c COLS, --cols COLS Number of columns to write. Default None(all) --firstRow FIRSTROW First index of output. Default 1 --firstCol FIRSTCOL First index of input. Default 1 --fileRowInd FILEROWIND First row index in file. Default 1 --fileColInd FILECOLIND First col index in file. Default 1 -t TRAMP, --tramp TRAMP Ramping time when chaning values. Default 3 -s SUFFIX, --suffix SUFFIX Any suffix after the matrix indices in channel names. Default is None. ``` ```bash $ caputt -h usage: caputt [-h] [-t TRAMP] [-w] [-o TIMEOUT] [chanInfo [chanInfo ...]] This script is a version of nominal caput command with added functionality of setting a tramp and reading a set of channels from yaml files if they need to be set all together or ramped all together to new values. positional arguments: chanInfo Channel name and value pairs sepaated by space or name of the yaml file containing them. optional arguments: -h, --help show this help message and exit -t TRAMP, --tramp TRAMP Global ramping time in seconds. -w, --wait Whether to wait until the processing has completed. Global and would override any other value from paramter file. -o TIMEOUT, --timeout TIMEOUT how long to wait (in seconds) for put to complete before giving up. Global and would override any other value from paramter file. Example use: caputt C1:FIRST_CH 8.0 caputt C1:FIRST_CH 8.0 -t 5 caputt C1:FIRST_CH 8.0 C1:SECOND_CH 5.6 -t 6 -w -o 60 caputt channelsFile.yml ``` Example of channelsFile.yml ```yaml channels: C1:FIRST_CH: value: 10 C1:SECOND_CH: value: 20 C1:THIRD_CH: value: 30 tramp: 5 # Individual tramp, will get overridden by global tramp if present. C1:FOURTH_CH: value: 40 timeout: 60 # Time after which the process will call it failed attempt. wait: True # Will wait for the process to end tramp: 5 # GLobal tramp, overrides individual tramp ```
/restoreEpics-0.3.2.1.tar.gz/restoreEpics-0.3.2.1/README.md
0.520009
0.824179
README.md
pypi
****** |logo| ****** ``restoreio`` is a Python package to **Restore** **I**\ ncomplete **O**\ ceanographic dataset, with specific focus on ocean surface velocity data. This package can also generate data ensembles and perform statistical analysis, which allows uncertainty qualification of such datasets. Links ===== * `Online Gateway <https://restoreio.org>`_ * `Documentation <https://ameli.github.io/restoreio>`_ * `PyPI <https://pypi.org/project/restoreio/>`_ * `Anaconda Cloud <https://anaconda.org/s-ameli/restoreio>`_ * `Github <https://github.com/ameli/restoreio>`_ Install ======= Install with ``pip`` -------------------- |pypi| :: pip install restoreio Install with ``conda`` ---------------------- |conda-version| :: conda install -c s-ameli restoreio Supported Platforms =================== Successful installation and tests performed on the following operating systems and Python versions: .. |y| unicode:: U+2714 .. |n| unicode:: U+2716 +----------+--------+-------+-------+-------+-------+-------+-----------------+ | Platform | Arch | Python Version | Continuous | + | +-------+-------+-------+-------+-------+ Integration + | | | 3.7 | 3.8 | 3.9 | 3.10 | 3.11 | | +==========+========+=======+=======+=======+=======+=======+=================+ | Linux | X86-64 | |y| | |y| | |y| | |y| | |y| | |build-linux| | +----------+--------+-------+-------+-------+-------+-------+-----------------+ | macOS | X86-64 | |y| | |y| | |y| | |y| | |y| | |build-macos| | +----------+--------+-------+-------+-------+-------+-------+-----------------+ | Windows | X86-64 | |n| | |y| | |y| | |y| | |y| | |build-windows| | +----------+--------+-------+-------+-------+-------+-------+-----------------+ .. |build-linux| image:: https://img.shields.io/github/actions/workflow/status/ameli/restoreio/build-linux.yml :target: https://github.com/ameli/restoreio/actions?query=workflow%3Abuild-linux .. |build-macos| image:: https://img.shields.io/github/actions/workflow/status/ameli/restoreio/build-macos.yml :target: https://github.com/ameli/restoreio/actions?query=workflow%3Abuild-macos .. |build-windows| image:: https://img.shields.io/github/actions/workflow/status/ameli/restoreio/build-windows.yml :target: https://github.com/ameli/restoreio/actions?query=workflow%3Abuild-windows Documentation ============= |deploy-docs| See `documentation <https://ameli.github.io/restoreio/index.html>`__, including: * `Installation Guide <https://ameli.github.io/restoreio/install.html>`__ * `User Guide <https://ameli.github.io/restoreio/user_guide/user_guide.html>`__ * `API Reference <https://ameli.github.io/restoreio/api.html>`__ * `Examples <https://ameli.github.io/restoreio/examples.html>`__ * `Publications <https://ameli.github.io/restoreio/cite.html>`__ Usage ===== An installation of ``restoreio`` offers two interfaces: a Python interface and a command-line interface. 1. Python Interface ------------------- You can import ``restoreio`` in python by ``import restoreio``. This package offers the following functions: * `restoreio.restore <https://ameli.github.io/restoreio/generated/restoreio.restore.html#restoreio.restore>`__: This is the main function of the package which reconstructs incomplete velocity data, generates data ensembles, and performs statistical analysis. You can import this function by :: from restoreio import restore * `restoreio.scan <https://ameli.github.io/restoreio/generated/restoreio.scan.html#restoreio.scan>`__: This function performs a pre-scan of your NetCDF dataset and ensures your dataset is compatible as an input to ``restoreio.restore`` function. The scan also provides you basic information about the dataset such as the time span, spatial extent of the data. These information could be useful to configure the settings for ``restoreio.restore`` function. You can import this function by :: from restoreio import scan 2. Command-Line Interface ------------------------- Alternatively, you may use ``restoreio`` as a standalone application which can be executed in command line. When ``restoreio`` is installed, the following executables are available: * `restore <https://ameli.github.io/restoreio/cli_restore.html>`__: This executable is equivalent to ``restoreio.restore`` function in the Python interface. * `restore-scan <https://ameli.github.io/restoreio/cli_scan.html>`__: This executable is equivalent to ``restoreio.scan`` function in the Python interface. To use these executables, make sure the ``/bin`` directory of your Python installation is set on your ``PATH`` environment variable. For instance, if your Python is installed on ``/opt/minicinda3/``, add this path ``/opt/miniconda3/bin`` directory to ``PATH`` by :: export PATH=/opt/minicinda/bin:$PATH You may place the above line in ``~/.bashrc`` to make the above change permanently. Online Web-Based Interface ========================== Alongside ``restoreio`` python package, we also offer an online service as a web-based interface for this software. This platform is available at: `https://restoreio.org <https://restoreio.org>`__. This online gateway allows users to efficiently process both local and remote datasets. The computational tasks are executed on the server side, leveraging the parallel processing capabilities of a high-performance computing cluster. Moreover, the web-based interface seamlessly integrates an interactive globe map, empowering sophisticated visualization of the results within the online platform. How to Contribute ================= We welcome contributions via `GitHub's pull request <https://github.com/ameli/restoreio/pulls>`_. If you do not feel comfortable modifying the code, we also welcome feature requests and bug reports as `GitHub issues <https://github.com/ameli/restoreio/issues>`_. How to Cite =========== If you publish work that uses ``restoreio``, please consider citing the manuscripts available `here <https://ameli.github.io/restoreio/cite.html>`_. License ======= |license| This project uses a `BSD 3-clause license <https://github.com/ameli/restoreio/blob/main/LICENSE.txt>`_, in hopes that it will be accessible to most projects. If you require a different license, please raise an `issue <https://github.com/ameli/restoreio/issues>`_ and we will consider a dual license. .. |logo| image:: https://raw.githubusercontent.com/ameli/restoreio/main/docs/source/_static/images/icons/logo-restoreio-light.svg :width: 200 .. |license| image:: https://img.shields.io/github/license/ameli/restoreio :target: https://opensource.org/licenses/BSD-3-Clause .. |deploy-docs| image:: https://img.shields.io/github/actions/workflow/status/ameli/restoreio/deploy-docs.yml?label=docs :target: https://github.com/ameli/restoreio/actions?query=workflow%3Adeploy-docs .. |binder| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/ameli/restoreio/HEAD?filepath=notebooks%2Fquick_start.ipynb .. |codecov-devel| image:: https://img.shields.io/codecov/c/github/ameli/restoreio :target: https://codecov.io/gh/ameli/restoreio .. |pypi| image:: https://img.shields.io/pypi/v/restoreio :target: https://pypi.org/project/restoreio/ .. |conda-version| image:: https://img.shields.io/conda/v/s-ameli/restoreio :target: https://anaconda.org/s-ameli/restoreio
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/README.rst
0.811303
0.770745
README.rst
pypi
# ======= # Imports # ======= import os import fnmatch __all__ = ['recursive_glob'] # ======================= # split all parts of path # ======================= def _split_all_parts_of_path(path): """ Splits all parts of a path. For example, the path '../build/lib.linux-x86_64-3.8/Module/Submodule/lib.so' will be split to the list ['..','build','lib.linux-x86_64','Module','Submodule','lib.so'] :param path: A file or directory path :type path: string :return: The list of strings of split path. :rtype: list(string) """ all_parts = [] # Recursion while True: # Split last part parts = os.path.split(path) if parts[0] == path: all_parts.insert(0, parts[0]) break elif parts[1] == path: all_parts.insert(0, parts[1]) break else: path = parts[0] all_parts.insert(0, parts[1]) return all_parts # ========================= # remove duplicates in list # ========================= def _remove_duplicates_in_list(list): """ Removes duplicate elements in a list. :param list: A list with possibly duplicate elements. :type list: list :return: A list which elements are not duplicate. :rtype: list """ shrinked_list = [] for element in list: if element not in shrinked_list: shrinked_list.append(element) return shrinked_list # ============== # recursive glob # ============== def recursive_glob(directory, patterns): """ Recursively searches all subdirectories of a given directory and looks for a list of patterns. If in a subdirectory, one of the patterns is found, the name of the first immediate subdirectory (after Directory) is returned in a list. For example, is the pattern is '*.so', Directory | |-- SubDirectory-1 | | | |--File-1.so | |-- SubDirectory-2 | | | |--SubSubDirectory-2 | | | |--File-2.so | |-- SubDirectory-3 | | | |--File-3.a This code outputs ['SubDirectory-1','SubDirectory-2']. Note that the `SubSubDirectory-2` is not in the output, since it is part of the `SubDirectory-2'. That is, this code only outputs the first children subdirectory if within that subdirectory a match of pattern is found. .. note:: In python 3, this function ``glob(dir,recursive=True)`` can be simply used. However, the recursive glob is not supproted in python 2 version of ``glob``, hence this function is written. :param directory: The path of a directory. :type directory: string :param patterns: A list of string as regex pattern, such as ['*.so','*.dylib','*.dll'] :type patterns: list(string) :return: List of first-depth subdirectories that within them a match of pattern is found. :rtype: list(string) """ # Find how many directory levels are in the input Directory path directory_depth = len(_split_all_parts_of_path(directory)) subdirectories = [] for root, dirname, filenames in os.walk(directory): for pattern in patterns: for filename in fnmatch.filter(filenames, pattern): subdirectories.append( _split_all_parts_of_path(root)[directory_depth]) return _remove_duplicates_in_list(subdirectories)
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/recursive_glob.py
0.648466
0.24987
recursive_glob.py
pypi
.. _examples: Examples ******** The following set of instructions is a step-by-step guide to reproduce the result in :ref:`[2] <ref2>`, which is an example of using |project|. Dataset ======= The paper uses the HF radar dataset from the Monterey Bay region in California, USA. The HF radar can be accessed publicly through the `national HF radar network gateway <http://cordc.ucsd.edu/projects/mapping/>`__ maintained by the Coastal Observing Research and Development Center. Please follow these steps to obtain the data file. **Dataset Webpage:** The studied data is available through its `OpenDap page <https://hfrnet-tds.ucsd.edu/thredds/dodsC/HFR/USWC/2km/hourly/RTV/HFRADAR_US_West_Coast_2km_Resolution_Hourly_RTV_best.ncd.html>`__. In particular, the **OpenDap URL** of this dataset is .. code-block:: bash http://hfrnet-tds.ucsd.edu/thredds/dodsC/HFR/USWC/2km/hourly/RTV/HFRADAR_US_West_Coast_2km_Resolution_Hourly_RTV_best.ncd **Navigate to Dataset Webpage:** To navigate to the above webpage, visit `CORDC THREDDS Serever <https://hfrnet-tds.ucsd.edu/thredds/catalog.html>`__. From there, click on `HF RADAR, US West Coast <https://hfrnet-tds.ucsd.edu/thredds/HFRADAR_USWC.html>`__, and select `HFRADAR US West Coast 2km Resolution Hourly RTV <https://hfrnet-tds.ucsd.edu/thredds/catalog/HFR/USWC/2km/hourly/RTV/catalog.html>`__ and choose `Best Time Series <https://hfrnet-tds.ucsd.edu/thredds/catalog/HFR/USWC/2km/hourly/RTV/catalog.html?dataset=HFR/USWC/2km/hourly/RTV/HFRADAR_US_West_Coast_2km_Resolution_Hourly_RTV_best.ncd>`__. **Subseting Data:** The above dataset contains the HF radar covering the west coast of the US from 2012 to the present date with 2km resolution and hourly updates. In the examples below, we focus on a spatial subset of this dataset within the Monterey Bay region for January 2017. Reproducing Results =================== The scripts to reproduce the results can be found in the source code of |project| under the directory |script_dir|_. Reproducing Figure 1 -------------------- .. prompt:: bash python plot_gdop_coverage.py .. figure:: _static/images/plots/gdop_coverage.png :align: left :figwidth: 100% :class: custom-dark **Figure 1:** *Panels (a) and (b) display the east and north GDOP values, respectively, calculated along the northern California coast using the radar configurations indicated by the red dots and their corresponding code names. Panel (c) shows the total GDOP, which is a measure of the overall quality of the estimation of the velocity vector. Panel (d) represents the average HF radar data availability for January 2017, indicating the locations with missing data that generally correspond to high total GDOP values.* Reproducing Figure 2 to Figure 9 -------------------------------- .. prompt:: bash python restoreio_mwe.py The above python script executes the following lines of code, which is given in **Listing 1** of the manuscript. Users may change the settings in the function arguments below. For further details, refer to the API reference documentation of the function :func:`restoreio.restore` function. .. code-block:: python >>> # Install restoreio with: pip install restoreio >>> from restoreio import restore >>> # OpenDap URL of the remote netCDF data >>> url = 'http://hfrnet-tds.ucsd.edu/thredds/' + \ ... 'dodsC/HFR/USWC/2km/hourly/RTV/HFRAD' + \ ... 'AR_US_West_Coast_2km_Resolution_Hou' + \ ... 'rly_RTV_best.ncd' >>> # Generate ensembles and reconstruct gaps >>> restore(input=url, output='output.nc', ... min_lon=-122.344, max_lon=-121.781, ... min_lat=36.507, max_lat=36.992, ... time='2017-01-25T03:00:00', ... uncertainty_quant=True, plot=True, ... num_ensembles=2000, ratio_num_modes=1, ... kernel_width=5, scale_error=0.08, ... detect_land=True, fill_coast=True, ... write_ensembles=True, verbose=True) The above script generates the output file ``output.nc`` that contains all generated ensembles. Moreover, it creates a subdirectory called ``output_results`` and stores **Figure 2** to **Figure 9** of the manuscript. These plots are shown below. .. figure:: _static/images/plots/orig_vel_and_error.png :align: left :figwidth: 100% :class: custom-dark **Figure 2:** *Panels (a) and (b) show the east and north components of the ocean’s current velocity in the upper 0.3 m th to 2.5 m range, as measured by HF radars in Monterey Bay on January 25 , 2017, at 3:00 UTC. The data has been averaged hourly and mapped to a 2 km resolution Cartesian grid using unweighted least squares. The regions inside the solid black curves represent missing data that was filtered out due to high GDOP values from the original measurement. Panels (c) and (d) respectively show the east and north components of the velocity error computed for the locations where velocity data is available in Panels (a) and (b).* .. figure:: _static/images/plots/rbf_kernel_2d.png :align: left :figwidth: 100% :width: 90% :class: custom-dark **Figure 3:** *The red fields represent the calculated spatial autocorrelation α for the east (a) and north (b) velocity data. The elliptical contour curves are the best fit of the exponential kernel ρ to the autocorrelation. The direction of the principal radii of ellipses is determined by the eigenvectors of M, representing the principal direction of correlation. The radii values are proportional to the eigenvalues of M, representing the correlation length scale. The axes are in the unit of data points spaced 2 km apart.* .. figure:: _static/images/plots/cor_cov.png :align: left :figwidth: 100% :width: 90% :class: custom-dark **Figure 4:** *Correlation (first column) and covariance matrices (second column) of the east (first row) and north (second row) datasets are shown. The size of matrices are n = 485.* .. figure:: _static/images/plots/kl_eigenvectors.png :align: left :figwidth: 100% :class: custom-dark **Figure 5:** *The first 12 spatial eigenfunctions φi for the east velocity dataset (first and second rows) and north velocity dataset (third and fourth rows) are shown in the domain Ω in the Monterey Bay. The black curves is indicate the boundary of the missing domain Ω◦. We note that the oblique pattern in the east eigenfunctions is attributed to the anisotropy of the east velocity data, as illustrated in Figure 3a.* .. figure:: _static/images/plots/ensembles.png :align: left :figwidth: 100% :class: custom-dark **Figure 6:** *The reconstructed central ensemble (first column), mean of reconstructed ensembles (second column), and the standard deviation of reconstructed ensembles (third column) are shown in both Ω and Ω◦. The boundary of Ω◦ is shown by the solid black curve. The first and second rows correspond to the east and north velocity data, respectively.* .. figure:: _static/images/plots/deviation.png :align: left :figwidth: 100% :class: custom-dark **Figure 7:** *The left to right columns show the plots of deviations d1(x), d2(x), d3(x), and d4(x), displayed in both domains Ω and Ω◦ with the first and second rows representing the east and north datasets, respectively. The solid black curve shows the boundary of Ω◦. The absolute values smaller than 10−8 are rendered as transparent and expose the ocean background, which includes the domain Ω for the first three deviations.* .. figure:: _static/images/plots/ensembles_js_distance.png :align: left :figwidth: 100% :width: 90% :class: custom-dark **Figure 8:** *The JS distance between the expected distribution q(x, ξ) and the observed distribution p(x, ξ) is shown. The absolute values smaller than 10−8 are rendered as transparent and expose the ocean background, which includes the domain Ω where the JS distance between p(x, ξ) and q(x, ξ) is zero.* .. figure:: _static/images/plots/kl_eigenvalues.png :align: left :figwidth: 100% :width: 70% :class: custom-dark **Figure 9:** *The eigenvalues λi, i = 1, . . . , n (green curves using left ordinate) and the energy ratio γm, m = 1, . . . , n (blue curves using right ordinate) are shown for the east and north velocity data. The horizontal dashed lines correspond to the 60% and 90% energy ratio levels, respectively, which equate to utilizing nearly 10 and 100 eigenmodes.* Reproducing Figure 10 --------------------- * First, run ``plot_js_divergence.sh`` script: .. prompt:: bash bash plot_js_divergence.sh The above script creates a directory called ``output_js_divergence`` and stores the output files ``output-001.nc`` to ``output-200.nc``. * Next, run ``plot_js_divergence.py`` script: .. prompt:: bash python plot_js_divergence.py .. figure:: _static/images/plots/js_distance.png :align: left :figwidth: 100% :width: 70% :class: custom-dark **Figure 10:** *The JS distance between the probability distributions pm(x, ξ) and pn(x, ξ) is shown as a function of m = 0, . . . , n. These two distributions correspond to the ensembles generated by the m-term (truncated) and n-term (complete) KL expansions, respectively. We note that the abscissa of the figure is displayed as the percentage of the ratio m/n where n = 485.* .. |script_dir| replace:: ``/examples/uncertainty_quant`` .. _script_dir: https://github.com/ameli/restoreio/blob/main/examples/uncertainty_quant/
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/examples.rst
0.972375
0.7169
examples.rst
pypi
.. _input-data: Input Data ********** This section offers comprehensive guidance on preparing your datasets to ensure their compatibility as input for |project|. .. contents:: :depth: 2 Preparing Input Data ==================== .. _file-format: File Format ----------- The input dataset can consist of **one or multiple files**, which should adhere to the following formats: * **NetCDF** file format with file extensions ``.nc``, ``.nc4``, ``.ncd``, or ``.nc.gz``. * **NcML** file format with file extensions ``.ncml`` or ``.ncml.gz``. For more information on NcML files, see :ref:`Single Dataset Stored Across Multiple Files <multi-file-single-data-sec>`. Note that it is also acceptable to provide a NetCDF file without a file extension. .. _best-practice-sec: Best Practice for NetCDF Files ------------------------------ It is highly recommended to save your data file in **NetCDF4** format instead of **NetCDF3**. For more information, refer to `NetCDF4 Package documentation <https://unidata.github.io/netcdf4-python/>`__ in Python or `NetCDF Files <https://www.mathworks.com/help/matlab/network-common-data-form.html>`__ in MATLAB. Also, you may follow the best practice of preparing a NetCDF file, which involves passing the **CF 1.8 compliance** test using `online CF-convention compliance checker <https://compliance.ioos.us/index.html>`__. In particular, this involves adding the ``standard_name`` attribute to your variables (see :ref:`Required NetCDF Variables <req-var-sec>` section below). For reference, you can consult the comprehensive list of `CF compliance standard names <http://cfconventions.org/Data/cf-standard-names/43/build/cf-standard-name-table.html>`__. . .. _req-var-sec: Required NetCDF Variables ------------------------- An input NetCDF file to |project| should include all the variables listed in the table below. To ensure proper detection of these variables by |project|, each variable should include at least one of the attributes: ``standard_name``, ``name``, or both, as listed in the table. Note that checking the (standard) name is done in a case-insensitive manner. .. |br| raw:: html <br> .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ .. | Variable | Acceptable Standard Names | Acceptable Names | .. +================================+========================================================================================+==================================+ .. | Time | ``time`` | ``t``, ``time``, ``datetime`` | .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ .. | Longitude | ``longitude`` | ``lon``, ``long``, ``longitude`` | .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ .. | Latitude | ``latitude`` | ``lat``, ``latitude`` | .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ .. | Ocean's Surface East Velocity | ``surface_eastward_sea_water_velocity`` | ``east_vel`` | .. | | ``eastward_sea_water_velocity`` | ``eastward_vel`` | .. | | ``surface_geostrophic_eastward_sea_water_velocity`` | ``u`` | .. | | ``surface_geostrophic_sea_water_x_velocity`` | ``ugos`` | .. | | ``surface_geostrophic_eastward_sea_water_velocity_assuming_sea_level_for_geoid`` | ``east_velocity`` | .. | | ``surface_eastward_geostrophic_sea_water_velocity_assuming_sea_level_for_geoid`` | ``eastward_velocity`` | .. | | ``surface_geostrophic_sea_water_x_velocity_assuming_mean_sea_level_for_geoid`` | ``u-velocity`` | .. | | ``surface_geostrophic_sea_water_x_velocity_assuming_sea_level_for_geoid`` | | .. | | ``surface_geostrophic_eastward_sea_water_velocity_assuming_mean_sea_level_for_geoid`` | | .. | | ``sea_water_x_velocity`` | | .. | | ``x_sea_water_velocity`` | | .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ .. | Ocean's Surface North Velocity | ``surface_northward_sea_water_velocity`` | ``north_vel`` | .. | | ``northward_sea_water_velocity`` | ``northward_vel`` | .. | | ``surface_geostrophic_northward_sea_water_velocity`` | ``v`` | .. | | ``surface_geostrophic_sea_water_y_velocity`` | ``vgos`` | .. | | ``surface_geostrophic_northward_sea_water_velocity_assuming_sea_level_for_geoid`` | ``north_velocity`` | .. | | ``surface_northward_geostrophic_sea_water_velocity_assuming_sea_level_for_geoid`` | ``northward_velocity`` | .. | | ``surface_geostrophic_sea_water_y_velocity_assuming_mean_sea_level_for_geoid`` | ``v-velocity`` | .. | | ``surface_geostrophic_sea_water_y_velocity_assuming_sea_level_for_geoid`` | | .. | | ``surface_geostrophic_northward_sea_water_velocity_assuming_mean_sea_level_for_geoid`` | | .. | | ``sea_water_y_velocity`` | | .. | | ``y_sea_water_velocity`` | | .. +--------------------------------+----------------------------------------------------------------------------------------+----------------------------------+ +--------------------------------+-----------------------+-----------------------------------------------------------------+ | Variable | Acceptable Names and Standard Names | +================================+=======================+=================================================================+ | Time | *Standard Names:* | ``time`` | | +-----------------------+-----------------------------------------------------------------+ | | *Names:* | ``t``, ``time``, ``datetime`` | +--------------------------------+-----------------------+-----------------------------------------------------------------+ | Longitude | *Standard Names:* | ``longitude`` | | +-----------------------+-----------------------------------------------------------------+ | | *Names:* | ``lon``, ``long``, ``longitude`` | +--------------------------------+-----------------------+-----------------------------------------------------------------+ | Latitude | *Standard Names:* | ``latitude`` | | +-----------------------+-----------------------------------------------------------------+ | | *Names:* | ``lat``, ``latitude`` | +--------------------------------+-----------------------+-----------------------------------------------------------------+ | Ocean's Surface East Velocity | *Standard Names:* |br| | | | ``surface_eastward_sea_water_velocity``, | | | ``eastward_sea_water_velocity``, | | | ``surface_geostrophic_eastward_sea_water_velocity``, | | | ``surface_geostrophic_sea_water_x_velocity``, | | | ``surface_geostrophic_eastward_sea_water_velocity_assuming_sea_level_for_geoid``, | | | ``surface_eastward_geostrophic_sea_water_velocity_assuming_sea_level_for_geoid``, | | | ``surface_geostrophic_sea_water_x_velocity_assuming_mean_sea_level_for_geoid``, | | | ``surface_geostrophic_sea_water_x_velocity_assuming_sea_level_for_geoid``, | | | ``surface_geostrophic_eastward_sea_water_velocity_assuming_mean_sea_level_for_geoid``, | | | ``sea_water_x_velocity``, | | | ``x_sea_water_velocity`` | + +-----------------------+-----------------------------------------------------------------+ | | *Names:* |br| | | | ``east_vel``, | | | ``eastward_vel``, | | | ``u``, | | | ``ugos``, | | | ``east_velocity``, | | | ``eastward_velocity``, | | | ``u-velocity`` | +--------------------------------+-----------------------+-----------------------------------------------------------------+ | Ocean's Surface North Velocity | *Standard Names:* |br| | | | ``surface_northward_sea_water_velocity``, | | | ``northward_sea_water_velocity``, | | | ``surface_geostrophic_northward_sea_water_velocity``, | | | ``surface_geostrophic_sea_water_y_velocity``, | | | ``surface_geostrophic_northward_sea_water_velocity_assuming_sea_level_for_geoid``, | | | ``surface_northward_geostrophic_sea_water_velocity_assuming_sea_level_for_geoid``, | | | ``surface_geostrophic_sea_water_y_velocity_assuming_mean_sea_level_for_geoid``, | | | ``surface_geostrophic_sea_water_y_velocity_assuming_sea_level_for_geoid``, | | | ``surface_geostrophic_northward_sea_water_velocity_assuming_mean_sea_level_for_geoid``, | | | ``sea_water_y_velocity``, | | | ``y_sea_water_velocity``, | + +-----------------------+-----------------------------------------------------------------+ | | *Names:* |br| | | | ``north_vel``, | | | ``northward_vel``, | | | ``v``, | | | ``vgos``, | | | ``north_velocity``, | | | ``northward_velocity``, | | | ``v-velocity`` | +--------------------------------+-----------------------+-----------------------------------------------------------------+ .. _opt-var-sec: Optional NetCDF Variables ------------------------- Apart from the required variables mentioned above, you have the option to include the following additional variables in your input file. Note that there is no standard name established for these variables, so you should provide a <code>name</code> attribute according to the table. These variables are used exclusively for the purposes of **uncertainty quantification** by **generating data ensembles**. For more details, you may refer to the :ref:`Generating Ensembles <generating-ensembles>` section. +---------------------------------------------------+---------------------------+------------------------------+ | Variable | Acceptable Standard Names | Acceptable Names | +===================================================+===========================+==============================+ | Ocean's Surface East Velocity Error | N/A | ``east_err``, ``east_error`` | +---------------------------------------------------+---------------------------+------------------------------+ | Ocean's Surface North Velocity Error | N/A | ``east_err``, ``east_error`` | +---------------------------------------------------+---------------------------+------------------------------+ | Geometric Dilution of Precision (East Component) | N/A | ``dopx``, ``gdopx`` | +---------------------------------------------------+---------------------------+------------------------------+ | Geometric Dilution of Precision (North Component) | N/A | ``dopx``, ``gdopx`` | +---------------------------------------------------+---------------------------+------------------------------+ The following provides further details for each of the variables listed in the tables above. .. _time-var-sec: 1. Time Variable ---------------- The time variable should be a one-dimensional array and strictly increases in values. Optional Attributes ~~~~~~~~~~~~~~~~~~~ * ``units``: a string specifying both the time unit (such as ``years``, ``months``, ``days``, ``hours``, ``minutes``, ``seconds`` or ``microseconds``) and the origin of the time axis (such as ``since 1970-01-01 00:00:00 UTC``). If this attribute is not provided, the default assumption is ``days since 1970-01-01 00:00:00 UTC``. * ``calendar``: a string indicating the time calendar. If this attribute is not provided, the default assumption is ``gregorian``. Masking ~~~~~~~ Ensure that the time variable is not masked. If the ``_FillValue`` attribute is included, the variable will be masked. Therefore, make sure this attribute is not present for the time variable. .. _lon-lat-var-sec: 2. Longitude and Latitude Variables ----------------------------------- These variables should be one-dimensional arrays, each representing an axis of a rectilinear grid. The values in both longitude and latitude arrays should either strictly increase or strictly decrease. The units of the arrays should be degrees positive eastward (for longitude) and degrees positive northward (for latitude). Data on Irregular Grids ~~~~~~~~~~~~~~~~~~~~~~~ |project| is designed to process data on rectilinear grids which are presented by **one-dimensional longitude and latitude arrays**. However, if your data is on irregular grids represented by **two-dimensional longitude and latitude arrays**, you can remap the data to a rectilinear grid by using interpolation functions such as `scipy.interpolate.griddata <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html>`__ in Python or `griddata <https://www.mathworks.com/help/matlab/ref/griddata.html>`__ in MATLAB. Masking ~~~~~~~ Ensure that the longitude and latitude variables are not masked. The presence of ``_FillValue`` attribute, for example, will cause these variables to be masked. Therefore, make sure this attribute is not present for the longitude and latitude variables. .. _ocean-vel-var-sec: 3. Ocean's Surface East and North Velocity Variables ---------------------------------------------------- Unit ~~~~ There is no restriction on the physical unit of the velocity variables; however, they should be oriented positive eastward (for the east component) and positive northward (for the north component). Array Dimensions ~~~~~~~~~~~~~~~~ The east and north ocean's surface velocity variables should be **three-dimensional** arrays that include dimensions for *time*, *longitude*, and *latitude*. However, you can also provide **four-dimensional** arrays, where an additional dimension represents *depth*. In the latter case, only the **first index** of the depth dimension (representing the surface at near zero depth) will be read from these variables. Dimensions Order ~~~~~~~~~~~~~~~~ The order of dimensions for a velocity variable, named ``east_vel`` for instance, is as follows: * For three dimensional arrays, the order should be ``east_vel[time, lat, lon]`` in Python and ``east_vel(lon, lat, time)`` in MATLAB. * For four dimensional arrays, the order should be ``east_vel[time, depth, lat, lon]`` in Python and ``east_vel(lon, lat, depth, time)`` in MATLAB. Note that the order of dimensions in MATLAB is reversed compared to Python. Masking ~~~~~~~ In areas where the velocity is unknown (either due to being located on land or having incomplete data coverage), the velocity variable should be masked using one of the following methods: * The **recommended approach** is to use **masked arrays** such as by `numpy.ma.MaskArray <https://numpy.org/doc/stable/reference/maskedarray.baseclass.html#maskedarray-baseclass>`__ class in Python or `netcdf.defVarFill <https://www.mathworks.com/help/matlab/ref/netcdf.defvarfill.html>`__ function in MATLAB (only for **NetCDF4**). * Set the velocity value on such locations to a large number such as ``9999.0`` and assign the attribute ``missing_value`` or ``_FillValue`` with this value. * Set the velocity value on such locations to ``NaN``. .. _ocean-vel-err-var-sec: 4. Ocean's Surface East and North Velocity Error Variables (Optional) --------------------------------------------------------------------- When you enable the ``uncertainty_quant`` option in :func:`restoreio.restore` to generate ensembles of velocity field for uncertainty quantification, the east and north velocity error variables are used. However, for uncertainty quantification purposes, you have the alternative option of providing the :ref:`Geometric Dilution of Precision Variables <ocean-gdop-var-sec>` instead of the velocity error variables. For further details, refer to :ref:`Generating Ensembles <generating-ensembles>` section. Unit ~~~~ The velocity error variables should be expressed as **non-negative** values and use the **same unit as the velocity** variable, such as both being in meters per second. If your velocity error values are not in the same unit as the velocity variables (e.g., velocity in **meters per second** and velocity error in **centimeters per second**), you can convert the velocity error unit by using the ``scale_error`` argument in :func:`restoreio.restore`. This scale factor will be directly multiplied to the error variables in your files. Array Dimensions ~~~~~~~~~~~~~~~~ The east and north ocean's surface velocity error variables should be **three-dimensional** arrays that include dimensions for *time*, *longitude*, and *latitude*. However, you can also provide **four-dimensional** arrays, where an additional dimension represents *depth*. In the latter case, only the **first index** of the depth dimension (representing the surface at near zero depth) will be read from these variables. Dimensions Order ~~~~~~~~~~~~~~~~ The order of dimensions for a velocity error variable, named ``east_vel`` for instance, is as follows: * For three dimensional arrays, the order should be ``east_vel[time, lat, lon]`` in Python and ``east_vel(lon, lat, time)`` in MATLAB. * For four dimensional arrays, the order should be ``east_vel[time, depth, lat, lon]`` in Python and ``east_vel(lon, lat, depth, time)`` in MATLAB. Note that the order of dimensions in MATLAB is reversed compared to Python. Masking ~~~~~~~ Unlike the velocity variable, masking the velocity error variables is not mandatory. However, if you choose to apply masks to the velocity error variables, the same rules that apply to the velocity variable should also be followed for the velocity error variables. .. _ocean-gdop-var-sec: 5. Geometric Dilution of Precision Variables (Optional) ------------------------------------------------------- The Geometric Dilution of Precision (GDOP) is relevant to HF radar datasets, and it quantifies the effect of the geometric configuration of the HF radars on the uncertainty in velocity estimates. To gain a better understanding of the GDOP variables, we recommend referring to Section 2 of :ref:`[2] <ref2>`. When you enable the ``uncertainty_quant`` option in :func:`restoreio.restore` to generate ensembles of velocity field for uncertainty quantification, the :ref:`Ocean's East and North Velocity Error Variables <ocean-vel-err-var-sec>` are used. However, for uncertainty quantification purposes, you have the alternative option of providing the GDOP variables instead of the velocity error variables. For further details on the usage of GDOP variables, refer to :ref:`Generating Ensembles <generating-ensembles>` section. Set Scale Velocity Error Entry ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When utilizing the GDOP variables instead of the velocity error variables, ensure to specify the ``scale_error`` argument in :func:`restoreio.restore`. This value should be set to the **radial error of HF radars**. The velocity error is then calculated as the product of this scale factor and the GDOP variables. Unit ~~~~ The GDOP variables should be expressed as **non-negative** values. The GDOP variables are **dimensionless**, however, when the GDOP variables are provided instead of the velocity error, the unit of the ``scale_error`` argument in :func:`restoreio.restore` should be the same unit as your velocity variable. Array Dimensions ~~~~~~~~~~~~~~~~ The east and north ocean's surface velocity error variables should be **three-dimensional** arrays that include dimensions for *time*, *longitude*, and *latitude*. However, you can also provide **four-dimensional** arrays, where an additional dimension represents *depth*. In the latter case, only the **first index** of the depth dimension (representing the surface at near zero depth) will be read from these variables. Dimensions Order ~~~~~~~~~~~~~~~~ The order of dimensions for a velocity error variable, named ``east_vel`` for instance, is as follows: * For three dimensional arrays, the order should be ``east_vel[time, lat, lon]`` in Python and ``east_vel(lon, lat, time)`` in MATLAB. * For four dimensional arrays, the order should be ``east_vel[time, depth, lat, lon]`` in Python and ``east_vel(lon, lat, depth, time)`` in MATLAB. Note that the order of dimensions in MATLAB is reversed compared to Python. Masking ~~~~~~~ Unlike the velocity variable, masking the velocity error variables is not mandatory. However, if you choose to apply masks to the velocity error variables, the same rules that apply to the velocity variable should also be followed for the velocity error variables. .. _provide-input-sec: Providing Input Data ==================== You can provide the input dataset in two different ways: 1. Using files from your local machine. 2. By specifying the URL of data hosted on remote THREDDS data servers. You can provide either the full path file name of you local files or the *OpenDap* URL of a remote dataset using the ``input`` argument in :func:`restoreio.restore`. Finding the OpenDap URL from THREDDS Catalogs --------------------------------------------- Many providers of geophysical data host their datasets on `THREDDS Data servers <https://www.unidata.ucar.edu/software/tds/>`__ , which offer OpenDap protocols. The following steps guide you to obtain the OpenDap URL of a remote dataset hosted on a THREDDS server. In the example below, we use a sample HF radar data hosted on our THREDDS server available at `https://transport.me.berkeley.edu/thredds <https://transport.me.berkeley.edu/thredds>`__. 1. Visit the `catalog webpage <https://transport.me.berkeley.edu/thredds/catalog/catalog.html?dataset=WHOI-HFR/WHOI_HFR_2014_original.nc>`__ of the dataset. 2. From the list of *Service*, select the *OPENDAP* service. This brings you to the `OPENDAP Dataset Access Form <https://transport.me.berkeley.edu/thredds/dodsC/root/WHOI-HFR/WHOI_HFR_2014_original.nc.html>`__ for this dataset. 3. From the OPENDAP Dataset Access Form, find the *Data URL* text box. This contains the OpenDap URL of this dataset, which is: .. prompt:: https://transport.me.berkeley.edu/thredds/dodsC/root/WHOI-HFR/WHOI_HFR_2014_restored.nc For a visual demonstration of the steps described above, you may refer to the animated clip. .. image:: ../_static/images/user-guide/OpenDap.gif :align: center :class: custom-dark .. _multi-file-sec: Multi-File Datasets =================== You have the option to provide multiple files. A multi-file datasets can appear in two scenarios: .. _multi-file-single-data-sec: Single Dataset Stored Across Multiple Files ------------------------------------------- If your dataset is divided into multiple files, where each file represents a distinct part of the data (e.g., different time frames), you can use the NetCDF Markup Language (NcML) to create an ``ncml`` file that aggregates all the individual NetCDF files into a single dataset. To provide this multi-file dataset, simply specify the URL of the NcML file. For detailed guidance on using NcML, you can consult the `NcML Tutorial <https://docs.unidata.ucar.edu/netcdf-java/4.6/userguide/ncml/Tutorial.html>`__. .. _multi-file-multiple-data-sec: Multiple Separate Datasets, Each within a File ---------------------------------------------- Alternatively, you may have several files, with each file representing an independent dataset. An example of such multiple files could be ensembles obtained from ocean models, where each file corresponds to a velocity ensemble. The following steps guide you to provide multiple files. 1. Name Your Files with a Numeric Pattern ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When providing multiple files, the name of your files (or the URLs) should include a numeric pattern. For instance, you can use the file name format like ``MyInputxxxxFile.nc`` where ``xxxx`` is the numeric pattern. An example of such data URLs where the pattern ranges from ``0000`` to ``0020`` could be: .. prompt:: https://transport.me.berkeley.edu/thredds/dodsC/public/SomeDirectory/MyInput0000File.nc https://transport.me.berkeley.edu/thredds/dodsC/public/SomeDirectory/MyInput0001File.nc https://transport.me.berkeley.edu/thredds/dodsC/public/SomeDirectory/MyInput0002File.nc ... https://transport.me.berkeley.edu/thredds/dodsC/public/SomeDirectory/MyInput0020File.nc 2. Provide File Iterator Range ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provide the ``min_file_index`` and ``max_file_index`` arguments in :func:`restoreio.restore` function to define the range of files to be processed. This allows |project| to search through your uploaded files or generate new URLs based on the provided URL to access the other datasets. For example, in the case of the URLs mentioned earlier, you can enter ``0`` as the minimum file index and ``20`` as the maximum file index. Alternatively, you can specify the full iterator pattern with the leading zeros as ``0000`` to ``0020``. .. _scan-input-data-sec: Scan Input Data =============== It is recommended that you perform a scan of your dataset using the :func:`restoreio.scan` function. This function performs a simple check on your data to make sure required variables exists and are readable. This is often useful if you do not have a priori knowledge on the time and spatial extent of your data. The following code demonstrate scanning of a dataset: .. code-block:: python :emphasize-lines: 9 >>> # Import package >>> from restoreio import scan >>> # OpenDap URL of HF radar data >>> input = 'https://transport.me.berkeley.edu/thredds/dodsC/' + \ ... 'root/MontereyBay/MontereyBay_2km_original.nc' >>> # Run script >>> info = scan(input, scan_velocity=True) The ``info`` dictionary in the above contains information about the input dataset, such as its spatial extent, time span, and the range of velocity field values. Here is an example of printing this variable: .. code-block:: python >>> import json >>> json_obj = json.dumps(info, indent=4) >>> print(json_obj) { "Scan": { "ScanStatus": true, "Message": "" }, "TimeInfo": { "InitialTime": { "Year": "2017", "Month": "01", "Day": "20", "Hour": "06", "Minute": "00", "Second": "00", "Microsecond": "000000" }, "FinalTime": { "Year": "2017", "Month": "01", "Day": "25", "Hour": "21", "Minute": "00", "Second": "00", "Microsecond": "000000" }, "TimeDuration": { "Day": "5", "Hour": "15", "Minute": "00", "Second": "00" }, "TimeDurationInSeconds": "486000.0", "DatetimeSize": "136" }, "SpaceInfo": { "DataResolution": { "LongitudeResolution": "96", "LatitudeResolution": "84" }, "DataBounds": { "MinLatitude": "36.29128", "MidLatitude": "37.03744888305664", "MaxLatitude": "37.78362", "MinLongitude": "-123.59292", "MidLongitude": "-122.6038818359375", "MaxLongitude": "-121.614845" }, "DataRange": { "LongitudeRange": "175771.3634036201", "LatitudeRange": "166126.5386743735", "ViewRange": "246079.90876506813", "PitchAngle": "45.373085021972656" }, "CameraBounds": { "MinLatitude": "35.995285353686455", "MaxLatitude": "38.079612412426826", "MinLongitude": "-123.98635925709257", "MaxLongitude": "-121.22140441478243" } }, "VelocityInfo": { "EastVelocityName": "u", "NorthVelocityName": "v", "EastVelocityStandardName": "surface_eastward_sea_water_velocity", "NorthVelocityStandardName": "surface_northward_sea_water_velocity", "VelocityStandardName": "surface_sea_water_velocity", "MinEastVelocity": "-0.6357033237814904", "MaxEastVelocity": "0.5624764338135719", "MinNorthVelocity": "-0.6599066462367773", "MaxNorthVelocity": "0.8097501311451196", "TypicalVelocitySpeed": "1.005058422798982" } }
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/user_guide/input_data.rst
0.931392
0.742503
input_data.rst
pypi
.. _restore-setting: Data Restoration Settings ========================= The core function within |project| is :func:`restoreio.restore`, which serves a dual purpose: reconstructing incomplete data and generating data ensembles. This section delves into the intricacies of this function for the first application. Alongside this page, you can also explore the comprehensive list of settings available in the API of the :func:`restoreio.restore` function. .. contents:: :depth: 2 .. _time-sec: Time ---- You can process either the whole or a part of the time span of the input dataset. There are two options available to specify time: single time and time interval. 1. **Single Time:** Select the ``time`` argument to process a specific time within the input dataset. If the chosen time does not exactly match any time stamp in your input data, the closest available time will be used for processing. 2. **Time Interval:** Alternatively, you can use ``min_time`` and ``max_time`` arguments to process a specific time interval within the input dataset. If the specified times do not exactly match any time stamps in your input data, the closest available times will be used for processing. Alternatively, if you do not specify any of the above arguments, the entire time span within your input data will be processed. Please note that the time interval option cannot be used if you have enabled generating ensembles (refer to the ``uncertainty_quant`` argument). .. _domain-sec: Domain ------ You have the option to specify a spatial subset of the data for processing using ``min_lon``, ``max_lon``, ``min_lat``, and ``max_lat`` argument. By choosing a subset of the domain, the output file will only contain the specified spatial region. If you do not specify these arguments, the entire spatial extent within your input data will be processed. However, please be aware that for large spatial datasets, this option might require a significant amount of time for processing. To optimize efficiency, we recommend subsetting your input dataset to a relevant segment that aligns with your analysis. .. _domain-seg-sec: Domain Segmentation ------------------- The input dataset's grid comprises two distinct sets of points: locations with available velocity data and locations where velocity data is not provided. These regions are referred to as the *known* domain :math:`\Omega_k` and the *unknown* domain :math:`\Omega_u`, respectively. Therefore, the complete grid of the input data :math:`\Omega` can be decomposed into :math:`\Omega = \Omega_k \cup \Omega_u`. The primary objective of data reconstruction is to fill the data gaps within the regions where velocity data is missing. The region of *missing* data, :math:`\Omega_m`, is part of the unknown domain :math:`\Omega_u`. However, the unknown domain contains additional points that are not necessarily missing, such as points located on land, denoted as :math:`\Omega_l`, or regions of the ocean that are not included in the dataset, which we denote as :math:`\Omega_o`. Before proceeding with reconstructing the missing velocity data, it is essential to first identify the missing domain :math:`\Omega_m`. This involves segmenting the unknown domain :math:`\Omega_u` into :math:`\Omega_u = \Omega_m \cup \Omega_l \cup \Omega_o`. These tasks require the knowledge of the ocean's domain and land domain. You can configure these steps as described in :ref:`Detect Data Domain <detect-data-domain-sec>` and :ref:`Detect Land <detect-land-sec>` below. For detailed information on domain segmentation, we recommend referring to :ref:`[1] <ref1>`. .. _detect-data-domain-sec: Detect Data Domain ~~~~~~~~~~~~~~~~~~ By the data *domain*, :math:`\Omega_d`, we refer to the union of both the known domain :math:`\Omega_k` and the missing domain :math:`\Omega_m`, namely, :math:`\Omega_d = \Omega_k \cup \Omega_m`. Once the missing velocity field is reconstructed, the combination of both the known and missing domains will become the data domain. Identifying :math:`\Omega_d` can be done in two ways: .. _convex-hullsec: 1. Using Convex Hull .................... By enabling the ``convex_hull`` option, the data domain :math:`\Omega_d` is defined as the region enclosed by a convex hull around the known domain :math:`\Omega_k`. As such, any unknown point inside the convex hull is flagged as missing, and all points outside this convex hull are considered as part of the ocean domain :math:`\Omega_o` or land :math:`\Omega_l`. .. _concave-hull-sec: 2. Using Concave Hull ..................... By disabling the ``convex_hull`` option, the data domain :math:`\Omega_d` is defined as the region enclosed by a convex hull around the known domain :math:`\Omega_k`. As such, any unknown point inside the convex hull is flagged as missing, and all points outside this convex hull are considered as part of the ocean domain :math:`\Omega_o` or land :math:`\Omega_l`. Note that a concave hull (also known as `alpha shape <https://en.wikipedia.org/wiki/Alpha_shape>`__) is not unique and is characterized by a radius parameter. The radius is the inverse of the :math:`\alpha` parameter in alpha-shapes. A smaller radius causes the concave hull to shrink more toward the set of points it is encompassing. Conversely, a larger radius yields a concave hull that is closer to a convex hull. We recommend setting the radius (in the unit of Km) to a few multiples of the grid size. For instance, for an HF radar dataset with a 2km resolution, where the grid points are spaced 2 km apart, a radius of approximately 10 km works fine for most datasets. We recommend choosing concave hull over convex hull as it can better identify the data domain within your input files, provided that the radius parameter is tuned appropriately. .. _detect-land-sec: Illustration of Domain Segmentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The following figure serves as an illustration of the domain segmentation in relation to the provided :ref:`example code <quick-code-1>`. In the left panel, the green domain represents the known area :math:`\Omega_k` where velocity data is available, while the red domain signifies the region :math:`\Omega_u` without velocity data. In the right panel, the missing domain :math:`\Omega_m` is highlighted in red. This domain is determined by the red points from the left panel that fall within the concave hull around the green points. The points located outside the concave hull are considered non-data points, representing the ocean domain :math:`\Omega_o`. The :func:`restoreio.restore` function reconstructs the velocity field within the red points shown in the right panel. .. image:: ../_static/images/user-guide/grid-1.png :align: center :class: custom-dark Detect Land ~~~~~~~~~~~ In some cases, a part of the convex or concave hull might overlap with the land domain, leading to the mistaken flagging of such intersections as missing domains to be reconstructed. To avoid this issue, it is recommended to detect the land domain :math:`\Omega_l` and exclude it from the data domain :math:`\Omega_d` if there is any intersection. There are three options available regarding the treatment of the land domain: * Do not detect land, assume all grid is in ocean. This corresponds to setting ``detect_land`` option to ``0``. * Detect and exclude land (high accuracy, very slow). This correspond to setting ``detect_land`` to ``1``. * Detect and exclude land. This corresponds to setting ``detect_land`` option to ``2``. The land boundaries are queried using the `Global Self-consistent, Hierarchical, High-resolution Geography Database (GSHHG) <https://www.soest.hawaii.edu/pwessel/gshhg/>`__ . For large datasets, we advise against using the third option, as using high accuracy map can significantly increase the processing time for detecting land. For most datasets, we recommend using the second option, as it offers sufficient accuracy while remaining relatively fast. Extend Data Domain to Coastline ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If your dataset's data domain is close to land (e.g., in HF radar datasets spanning across coastlines), you can extend the data domain beyond the region identified by the convex or concave hulls, reaching up to the coastline. To achieve this, you can enable the ``fill_coast`` option. By extending the data domain to the land, a zero boundary condition for the velocity field on the land is imposed. However, it's important to note that this assumption results in less credible reconstructed fields, especially when dealing with large coastal gaps. The illustration below showcases the impact of activating the ``fill_coast`` feature in the provided :ref:`example code <quick-code-1>`. Notably, the alteration can be observed in the right panel, where the area between the data domain and the coastline is highlighted in red. This signifies that the gaps extending up to the coastlines will be comprehensively reconstructed. .. image:: ../_static/images/user-guide/grid-2.png :align: center :class: custom-dark .. _refine-grid-sec: Refine Grid ----------- With the ``refine`` argument, you can increase the dataset's grid size by an integer factor along **both** longitude and latitude axes. This process involves interpolating the data onto a more refined grid. It's important to note that this refinement **doesn't enhance** the data resolution. We advise keeping the refinement level at the default value of 1, unless there's a specific reason to refine the grid size. Increasing the refinement level can significantly increase computation time and may not provide additional benefits in most cases.
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/user_guide/restore_setting.rst
0.961597
0.860252
restore_setting.rst
pypi
.. _generating-ensembles: Generating Ensembles ==================== Beyond its data reconstruction capabilities, |project| also provides the feature to create ensembles of the velocity vector field. These ensembles are crucial for quantifying uncertainties, which holds significance for various applications. For a more in-depth understanding of the ensemble generation algorithm, we direct interested readers to :ref:`[2] <ref2>`. To create velocity ensembles, simply activate the ``uncertainty_quant`` option within :func:`restoreio.restore`. Do note that ensembles can be generated for **a single time point** only. This section elaborates on the utilization of :func:`restoreio.restore` specifically for ensemble generation purposes. .. contents:: :depth: 2 .. _ensemble-var-sec: Required Variables ------------------ To generate ensembles, you should provide one of the following additional variables in your input file: * :ref:`Ocean's Surface East and North Velocity Error Variables <ocean-vel-err-var-sec>` * :ref:`Geometric Dilution of Precision Variables <ocean-gdop-var-sec>` If you choose to provide GDOP variables instead of the velocity error variables, the velocity errors are calculated from GDOP as follows: .. math:: \begin{align} \sigma_e &= \sigma_r \mathrm{GDOP}_e, \\ \sigma_n &= \sigma_r \mathrm{GDOP}_n, \end{align} where :math:`\sigma_e` and :math:`\sigma_n` are the east and north components of the velocity error, :math:`\mathrm{GDOP_e}` and :math:`\mathrm{GDOP}_n` are the east and north components of the GDOP, respectively, and :math:`\sigma_r` is the radar's radial error. You can specify :math:`\sigma_r` using the ``scale_error`` argument within the function (also refer to :ref:`Scale Velocity Errors <scale-vel-error-sec>` section below). .. _ensemble-settings-sec: Ensemble Generation Settings ---------------------------- The following settings for ensemble generation can be set within the :func:`restoreio.restore` function: .. _write-ensembles: Write Ensembles to Output ~~~~~~~~~~~~~~~~~~~~~~~~~ The ``write_ensembles`` option allows you to save the entire population of ensemble vector fields to the output file. If this option is not enabled, only the *mean* and *standard deviation* of the ensembles will be stored. For more details, please refer to the :ref:`Output Variables <output-var>` section. .. _num-samples-sec: Number of (Monte-Carlo) Samples ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The ``num_ensembles`` argument of the function enables you to specify the number of ensembles to be generated. This value should be greater than the number of velocity data points. Keep in mind that the processing time increases **linearly** with larger sample sizes. .. _num-eigenmodes-sec: Number of Eigen-Modes ~~~~~~~~~~~~~~~~~~~~~ To generate ensembles, the eigenvalues and eigenvectors of the covariance matrix of the velocity data need to be computed. For a velocity data with :math:`n` data points, this means the eigenvalues and eigenvectors of an :math:`n \times n` matrix have to be calculated. However, such a computation has a complexity of :math:`\mathcal{O}(n^3)`, which can be infeasible for large datasets. To handle this, we employ a practical approach where we only compute a reduced number of :math:`m` eigenvalues and eigenvectors of the covariance matrix, where :math:`m` can be much smaller than :math:`n`. This simplification reduces the complexity to :math:`\mathcal{O}(n m^2)`, which enables us to process larger datasets while maintaining a reasonable level of accuracy. For a better understanding of this concept, we refer the interested reader to Section 4 of :ref:`[2] <ref2>`. The ``ratio_num_modes`` argument of the function allows you to specify the number of eigenvectors of the data covariance to be utilized in the computations. The number of modes should be given as a percentage of the ratio :math:`m/n`. Keep in mind that the processing time **quadratically** increases with the number of eigenmodes. We recommend setting this value to around 5% to 10% for most datasets. .. _kernel-width-sec: Kernel Width ~~~~~~~~~~~~ The ``kernel_width`` argument of the function represents the width of a spatial kernel used to construct the covariance matrix of the velocity data. The kernel width is measured in the unit of the velocity data points. For example, a kernel width of 5 on an HF radar dataset with a 2 km spatial resolution implies a kernel width of 10 km. It is assumed that spatial distances larger than the kernel width are uncorrelated. Therefore, reducing the kernel width makes the covariance matrix of the data more sparse, resulting in more efficient processing. However, a smaller kernel width may lead to information loss within the dataset. As a general recommendation, we suggest setting this value to 5 to 20 data points. .. _scale-vel-error-sec: Scale Velocity Errors ~~~~~~~~~~~~~~~~~~~~~ The ``scale_error`` argument serves two purposes: * If the :ref:`Ocean's Surface East and North Velocity Error Variables <ocean-vel-err-var-sec>` are included in the input dataset, the provided scale value is multiplied by the velocity error. This is useful to match the unit of the velocity error to the unit of the velocity data if they are not in the same unit. If you have velocity errors in the same unit as the velocity data, it is recommended to set this quantity to 1. * If the :ref:`Geometric Dilution of Precision (GDOP) Variables <ocean-gdop-var-sec>` are included in the input dataset, the given scale value is interpreted as the HF radar's radial error, :math:`\sigma_r`. In this case, the velocity error is calculated by multiplying the radar's radial error by the GDOP variables. The typical range for the radial errors of HF radars is between 0.05 to 0.20 meters per second.
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/user_guide/generating_ensembles.rst
0.976209
0.891008
generating_ensembles.rst
pypi
.. _output-data: Output Data *********** .. contents:: :depth: 3 Output Files ============ Depending on your selection of single or multi-file dataset (refer to :ref:`Multi-File Datasets <multi-file-sec>`), the output file can be one of the following: .. _output-single-data-sec: 1. Output for Single Dataset ---------------------------- If your input consists of a single dataset (either as a single input file or :ref:`multiple files representing a single dataset <multi-file-single-data-sec>`), the output result will be a single ``.nc`` file. .. _output-multiple-data-sec: 2. Output for Multi-File Dataset -------------------------------- If your input files represent multiple separate datasets (refer to :ref:`Multiple Separate Dataset, Each within a File <multi-file-multiple-data-sec>` section), a distinct output file with a ``.nc`` format is generated for each input file (or URL). These output files are named similarly to their corresponding input files. All of these files are then bundled into a ``.zip`` file. .. _output-var: Output Variables ================ The results of |project| are stored in a NetCDF file with a ``.nc`` format. This file comprises a range of variables, as outlined below, depending on the chosen configuration. 1. :ref:`Mask <output-mask>` 2. :ref:`Reconstructed East and North Velocities <output-vel-var>` 3. :ref:`East and North Velocity Errors <output-vel-err-var>` 4. :ref:`East and North Velocity Ensembles <output-vel-ens-var>` .. _output-mask: 1. Mask ------- The mask variable is a three-dimensional array with dimensions for *time*, *longitude*, and *latitude*. This variable is stored under the name ``mask`` in the output file. Interpreting Variable over Segmented Domains ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The mask variable includes information about the result of domain segmentation (refer to :ref:`Domain Segmentation <domain-seg-sec>` section). This array contains integer values ``-1``, ``0``, ``1``, and ``2`` that are interpreted as follows: * The value ``-1`` indicates the location is identified to be on the **land** domain :math:`\Omega_l`. In these locations, the output velocity variable is masked. * The value ``0`` indicates the location is identified to be on the **known** domain :math:`\Omega_k`. These locations have velocity data in the input file. The same velocity values are preserved in the output file. * The value ``1`` indicates the location is identified to be on the **missing** domain :math:`\Omega_m`. These locations do not have a velocity data in the input file, but they do have a reconstructed velocity data on the output file. * The value ``2`` indicates the location is identified to be on the **ocean** domain :math:`\Omega_0`. In these locations, the output velocity variable is masked. .. _output-vel-var: 2. Reconstructed East and North Velocities ------------------------------------------ The reconstructed east and north velocity variables are stored in the output file under the names ``east_vel`` and ``north_vel``, respectively. These variables are three-dimensional arrays with dimensions for *time*, *longitude*, and *latitude*. Interpreting Variable over Segmented Domains ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The velocity variables on each of the segmented domains are defined as follows: * On locations where the :ref:`Mask <output-mask>` value is ``-1`` or ``2``, the output velocity variables are masked. * On locations where the :ref:`Mask <output-mask>` value is ``0``, the output velocity variables have the same values as the corresponding variables in the input file. * On locations where the :ref:`Mask <output-mask>` value is ``1``, the output velocity variables are reconstructed. If the ``uncertainty_quant`` option is enabled, these output velocity variables are obtained by the **mean** of the velocity ensembles, where the missing domain of each ensemble is reconstructed. .. _output-vel-err-var: 3. East and North Velocity Errors --------------------------------- If the ``uncertainty_quant`` option is enabled, the east and north velocity error variables will be included in the output file under the names ``east_err`` and ``north_err``, respectively. These variables are three-dimensional arrays with dimensions for *time*, *longitude*, and *latitude*. Interpreting Variable over Segmented Domains ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The velocity error variables on each of the segmented domains are defined as follows: * On locations where the :ref:`Mask <output-mask>` value is ``-1`` or ``2``, the output velocity error variables are masked. * On locations where the :ref:`Mask <output-mask>` value is ``0``, the output velocity error variables are obtained from either the corresponding velocity error or GDOP variables in the input file scaled by the value of ``scale_error`` argument. * On locations where the :ref:`Mask <output-mask>` value is ``1``, the output velocity error variables are obtained from the **standard deviation** of the ensembles, where the missing domain of each ensemble is reconstructed. .. _output-vel-ens-var: 4. East and North Velocity Ensembles ------------------------------------ When you activate the ``uncertainty_quant`` option, a collection of velocity field ensembles is created. Yet, by default, the output file only contains the mean and standard deviation of these ensembles. To incorporate all ensembles into the output file, you should additionally enable the ``write_ensembles`` option. This action saves the east and north velocity ensemble variables in the output file as ``east_vel_ensembles`` and ``north_vel_ensembles``, respectively. These variables are four-dimensional arrays with dimensions for *ensemble*, *time*, *longitude*, and *latitude*. Ensemble Dimension ~~~~~~~~~~~~~~~~~~ The *ensemble* dimension of the array has the size :math:`s+1` where :math:`s` is the number of ensembles specified by ``num_ensembles`` (also refer to :ref:`Number of (Monte-Carlo) Samples <num-samples-sec>` section). The first ensemble with the index :math:`0` (assuming zero-based numbering) corresponds to the original input dataset. The other ensembles with the indices :math:`1, \dots, s` correspond to the generated ensembles. Interpreting Variable over Segmented Domains ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The velocity ensemble variables on each of the segmented domains are defined similar to those presented for :ref:`Reconstructed East and North Velocities <output-vel-var>`. In particular, the missing domain of each ensemble is reconstructed independently. Mean and Standard Deviation of Ensembles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note that the *mean* and *standard deviation* of the velocity ensemble arrays over the ensemble dimension yield the :ref:`Reconstructed East and North Velocities <output-vel-var>` and :ref:`East and North Velocity Errors <output-vel-err-var>` variables, respectively.
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/docs/source/user_guide/output_data.rst
0.94437
0.831827
output_data.rst
pypi
# ======= # Imports # ======= import netCDF4 import datetime import numpy __all__ = ['get_datetime_info'] # ================= # Get Datetime Info # ================= def get_datetime_info(datetimes_obj): """ This is used in writer function. Converts date char format to datetime numeric format. This parses the times chars and converts them to date times. """ # Datetimes units if (hasattr(datetimes_obj, 'units')) and \ (datetimes_obj.units != ''): datetimes_unit = datetimes_obj.units else: datetimes_unit = 'days since 1970-01-01 00:00:00 UTC' # Datetimes calendar if (hasattr(datetimes_obj, 'calendar')) and \ (datetimes_obj.calendar != ''): datetimes_calendar = datetimes_obj.calendar else: datetimes_calendar = 'gregorian' # Datetimes days_list = [] original_datetimes_array = datetimes_obj[:] if original_datetimes_array.ndim == 1: # Datetimes in original dataset is already suitable to use datetimes_array = original_datetimes_array[:].astype(numpy.double) elif original_datetimes_array.ndim == 2: # Datetime in original dataset is in the form of string. They # should be converted to numerics for i in range(original_datetimes_array.shape[0]): # Get row as string (often it is already a string, or a byte # type) char_time = numpy.chararray(original_datetimes_array.shape[1]) for j in range(original_datetimes_array.shape[1]): char_time[j] = original_datetimes_array[i, j].astype('str') # Parse chars to integers # Year if char_time.size >= 4: year = int(char_time[0] + char_time[1] + char_time[2] + char_time[3]) else: year = 1970 # Month if char_time.size >= 6: month = int(char_time[5] + char_time[6]) else: month = 1 # Day if char_time.size >= 9: day = int(char_time[8] + char_time[9]) else: day = 1 # Hour if char_time.size >= 13: hour = int(char_time[11] + char_time[12]) else: hour = 0 # Minute if char_time.size >= 15: minute = int(char_time[14] + char_time[15]) else: minute = 0 # Second if char_time.size >= 19: second = int(char_time[17] + char_time[18]) else: second = 0 # Create day object days_list.append(datetime.datetime(year, month, day, hour, minute, second)) # Convert dates to numbers datetimes_array = netCDF4.date2num( days_list, units=datetimes_unit, calendar=datetimes_calendar).astype(numpy.double) else: raise RuntimeError("Datetime ndim is more than 2.") # Create a Time dictionary datetime_info = { 'array': datetimes_array, 'unit': datetimes_unit, 'calendar': datetimes_calendar } return datetime_info
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/examples/uncertainty_quant/_utils/_load_variables/_get_datetime_info.py
0.546254
0.52409
_get_datetime_info.py
pypi
# ======= # Imports # ======= import numpy import math from ._array_utilities import check_monotonicity, find_closest_index from _utils._server_utils import terminate_with_error __all__ = ['subset_domain'] # ============= # Subset Domain # ============= def subset_domain( lon, lat, min_lon, max_lon, min_lat, max_lat): """ Find min and max indices to subset the processing domain. """ # Check longitude and latitude arrays are monotonic check_monotonicity(lon[:], 'Longitudes') check_monotonicity(lat[:], 'Latitudes') # Dataset bound dataset_min_lon = numpy.min(lon[:]) dataset_max_lon = numpy.max(lon[:]) dataset_min_lat = numpy.min(lat[:]) dataset_max_lat = numpy.max(lat[:]) # Check consistency of the bounds if (not math.isnan(min_lon)) and (not math.isnan(max_lon)): if min_lon >= max_lon: terminate_with_error( 'The given min longitude (%0.4f) ' % min_lon + 'should be smaller than the given max longitude ' + '(%0.4f).' % max_lon) if (not math.isnan(min_lat)) and (not math.isnan(max_lat)): if min_lat >= max_lat: terminate_with_error( 'The given min latitude (%0.4f) ' % min_lat + 'should be smaller than the given max latitude ' + '(%0.4f).' % max_lat) # min lon if math.isnan(min_lon): min_lon_index = 0 else: # Check bound if min_lon < dataset_min_lon: terminate_with_error( 'The given min longitude %0.4f ' % min_lon + 'is smaller ' + 'then the min longitude of the data, which is %f.' % dataset_min_lon) if min_lon > dataset_max_lon: terminate_with_error( 'The given min longitude %0.4f ' % min_lon + 'is larger ' + 'then the max longitude of the data, which is %f.' % dataset_max_lon) # Find min lon index min_lon_index = find_closest_index(lon[:], min_lon) # max lon if math.isnan(max_lon): max_lon_index = lon.size-1 else: # Check bound if max_lon > dataset_max_lon: terminate_with_error( 'The given max longitude %0.4f ' % max_lon + 'is greater ' + 'than the max longitude of the data, which is %f.' % dataset_max_lon) if max_lon < dataset_min_lon: terminate_with_error( 'The given max longitude %0.4f ' % max_lon + 'is smaller ' + 'than the min longitude of the data, which is %f.' % dataset_min_lon) # Find max lon index max_lon_index = find_closest_index(lon[:], max_lon) # min lat if math.isnan(min_lat): min_lat_index = 0 else: # Check bound if min_lat < dataset_min_lat: terminate_with_error( 'The given min latitude %0.4f ' % min_lat + 'is smaller ' + 'than the min latitude of the data, which is %f.' % dataset_min_lat) if min_lat > dataset_max_lat: terminate_with_error( 'The given min latitude %0.4f ' % min_lat + 'is larger ' + 'than the max latitude of the data, which is %f.' % dataset_max_lat) # Find min lat index min_lat_index = find_closest_index(lat[:], min_lat) # max lat if math.isnan(max_lat): max_lat_index = lat.size-1 else: # Check bound if max_lat > dataset_max_lat: terminate_with_error( 'The given max latitude %0.4f ' % max_lat + 'is greater ' + 'than the max latitude of the data, which is %f.' % dataset_max_lat) if max_lat < dataset_min_lat: terminate_with_error( 'The given max latitude %0.4f ' % max_lat + 'is smaller ' + 'than the min latitude of the data, which is %f.' % dataset_min_lat) # Find max lat index max_lat_index = find_closest_index(lat[:], max_lat) # In some dataset, the direction of lon or lat arrays are reversed, meaning # they are decreasing monotonic. In such a case, the min or max indices # should be swapped. # Swap min and max lon indices if min_lon_index > max_lon_index: temp_min_lon_index = min_lon_index min_lon_index = max_lon_index max_lon_index = temp_min_lon_index # Swap min and max lat indices if min_lat_index > max_lat_index: temp_min_lat_index = min_lat_index min_lat_index = max_lat_index max_lat_index = temp_min_lat_index return min_lon_index, max_lon_index, min_lat_index, max_lat_index
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/examples/uncertainty_quant/_utils/_subset/subset_domain.py
0.722233
0.516717
subset_domain.py
pypi
# ======= # Imports # ======= import numpy import sys import warnings import matplotlib.pyplot as plt import matplotlib.colors as mcolors from matplotlib.colors import LinearSegmentedColormap from matplotlib import cm from mpl_toolkits.basemap import Basemap import netCDF4 # Modules import InputOutput import Geography # ================= # Make Array Masked # ================= def MakeArrayMasked(Array): """ Some datasets are not masked, rather they use nan or inf for unavailable datasets. This function creates a mask for those datastes. """ if (not hasattr(Array,'mask')) or (Array.mask.size == 1): if numpy.isnan(Array).any() or numpy.isinf(Array).any(): # This array is not masked. Make a mask based no nan and inf Mask_nan = numpy.isnan(Array) Mask_inf = numpy.isinf(Array) Mask = numpy.logical_or(Mask_nan,Mask_inf) Array = numpy.ma.masked_array(Array,mask=Mask) else: # This array is masked. But check if any non-masked value is nan or inf for i in range(Array.shape[0]): for j in range(Array.shape[1]): if Array.mask[i,j] == False: if numpy.isnan(Array[i,j]) or numpy.isinf(Array[i,j]): Array.mask[i,j] = True return Array # ============= # Plot Coverage # ============= def PlotCoverage(Datetime,Latitude,Longitude,Coverage): print("Plot ...") # Mesh grid LongitudesGrid,LatitudesGrid = numpy.meshgrid(Longitude,Latitude) # Corner points (Use 0.05 for MontereyBay and 0.1 for Martha dataset) # Percent = 0.05 Percent = 0.1 LongitudeOffset = Percent * numpy.abs(Longitude[-1] - Longitude[0]) LatitudeOffset = Percent * numpy.abs(Latitude[-1] - Latitude[0]) MinLongitudeWithOffset = numpy.min(Longitude) - LongitudeOffset MidLongitude = numpy.mean(Longitude) MaxLongitudeWithOffset = numpy.max(Longitude) + LongitudeOffset MinLatitudeWithOffset = numpy.min(Latitude) - LatitudeOffset MidLatitude = numpy.mean(Latitude) MaxLatitudeWithOffset = numpy.max(Latitude) + LatitudeOffset # Basemap (set resolution to 'i' for faster rasterization and 'f' for full resolution but very slow.) # -------- # Draw Map # -------- def DrawMap(axis): map = Basemap( \ ax = axis, \ projection = 'aeqd', \ llcrnrlon=MinLongitudeWithOffset, \ llcrnrlat=MinLatitudeWithOffset, \ urcrnrlon=MaxLongitudeWithOffset, \ urcrnrlat=MaxLatitudeWithOffset, \ area_thresh = 0.1, \ lon_0 = MidLongitude, \ lat_0 = MidLatitude, \ resolution='i') # Map features map.drawcoastlines() # map.drawstates() # map.drawcountries() # map.drawcounties() map.drawlsmask(land_color='Linen', ocean_color='#CCFFFF',lakes=True) # map.fillcontinents(color='red', lake_color='white', zorder=0) map.fillcontinents(color='moccasin') # map.bluemarble() map.shadedrelief() # map.etopo() # Latitude and Longitude lines LongitudeLines = numpy.linspace(numpy.min(Longitude),numpy.max(Longitude),2) LatitudeLines = numpy.linspace(numpy.min(Latitude),numpy.max(Latitude),2) # map.drawparallels(LatitudeLines,labels=[1,0,0,0],fontsize=10) map.drawmeridians(LongitudeLines,labels=[0,0,0,1],fontsize=10) return map # Custom colormap from transparent to blue Res=100 # colors = [(0.9,0.54,0.2,c) for c in numpy.linspace(0,1,Res)] # orange # colors = [(0.3,0.5,0.1,c) for c in numpy.linspace(0,1,Res)] # green # colors = [(0.17,0.34,0.52,c) for c in numpy.linspace(0,1,Res)] # blue colors = [(0.17,0.4,0.63,c) for c in numpy.linspace(0,1,Res)] # blue cmapblue = mcolors.LinearSegmentedColormap.from_list('mycmap',colors,N=Res) # Plot array fig,axis = plt.subplots() map = DrawMap(axis) LongitudesGridOnMap,LatitudesGridOnMap= map(LongitudesGrid,LatitudesGrid) # CoverageMap = map.pcolormesh(LongitudesGridOnMap,LatitudesGridOnMap,Coverage,cmap=cm.Blues,edgecolors='blue') CoverageMap = map.pcolormesh(LongitudesGridOnMap,LatitudesGridOnMap,Coverage,cmap=cmapblue,vmin=0,vmax=100) cbar = fig.colorbar(CoverageMap,ticks=[0,25,50,75,100],orientation='horizontal') # FirstTime = netCDF4.num2date(Datetime[0],Datetime.units,Datetime.calendar) # LastTime = netCDF4.num2date(Datetime[-1],Datetime.units,Datetime.calendar) # axis.set_title('Coverage from: %s to %s'%(FirstTime,LastTime)) plt.show() # ==== # Main # ==== def main(argv): """ This code scans the input file and creates an array of size (lat,log) and initiate it with zseros. Then it counts through all time steps that how many times a specific location has mask=False, that is how many times the data are available. Then the array (coverage array) is normalized to percent. The result is ploted with basemap. """ # Print usage def PrintUsage(ExecName): UsageString = "Usage: " + ExecName + "<InputFilename.{nc,ncml}>" print(UsageString) # Parse arguments, get InputFilename InputFilename = '' if len(argv) < 1: PrintUsage(argv[0]) sys.exit(0) else: InputFilename = argv[1] # Check input if InputFilename == '': PrintUsage(argv[0]) sys.exit(0) # Open file agg = InputOutput.LoadDataset(InputFilename) # Load variables DatetimeObject,LongitudeObject,LatitudeObject,EastVelocityObject,NorthVelocityObject,EastVelocityErrorObject,NorthVelocityErrorObject = InputOutput.LoadVariables(agg) # Get arrays Datetime = DatetimeObject Longitude = LongitudeObject[:] Latitude = LatitudeObject[:] U_AllTimes = EastVelocityObject[:] V_AllTimes = NorthVelocityObject[:] # Sizes TimeSize = U_AllTimes.shape[0] LatitudeSize = U_AllTimes.shape[1] LongitudeSize = U_AllTimes.shape[2] # Initialize Inpainted arrays FillValue = 999 Coverage = numpy.ma.zeros((LatitudeSize,LongitudeSize),dtype=float,fill_value=FillValue) # Determine the land # LandIndices,OceanIndices = Geography.FindLandAndOceanIndices(Longitude,Latitude) LandIndices,OceanIndices = Geography.FindLandAndOceanIndices2(Longitude,Latitude) # Iterate through all times print("Calculating coverage map ...") for TimeIndex in range(TimeSize): # print("Process: %d / %d"%(TimeIndex+1,TimeSize)) # Get U and V U = U_AllTimes[TimeIndex,:] V = V_AllTimes[TimeIndex,:] # Mask U and V (if they are not masked already) U = MakeArrayMasked(U) V = MakeArrayMasked(V) # Iterate over lon and lat for LatitudeIndex in range(LatitudeSize): for LongitudeIndex in range(LongitudeSize): MaskU = U.mask[LatitudeIndex,LongitudeIndex] MaskV = V.mask[LatitudeIndex,LongitudeIndex] if (MaskU == False) and (MaskV == False): Coverage[LatitudeIndex,LongitudeIndex] = Coverage[LatitudeIndex,LongitudeIndex] + 1.0 # Normalize coverage to percent Coverage = 100.0 * Coverage / TimeSize # Mask land indices if LandIndices.shape[0] > 0: for i in range(LandIndices.shape[0]): Coverage[LandIndices[i,0],LandIndices[i,1]] = numpy.ma.masked # Plot PlotCoverage(Datetime,Latitude,Longitude,Coverage) agg.close() # =========== # System Main # =========== if __name__ == "__main__": # Converting all warnings to error # warnings.simplefilter('error',UserWarning) # Main function main(sys.argv)
/restoreio-0.7.0.tar.gz/restoreio-0.7.0/examples/restore/plot_coverage.py
0.610221
0.580352
plot_coverage.py
pypi
Restorething ============ ``restorething`` is a tool for restoring files from a syncthing versioning archive. Supply ``restorething`` the path to the syncthing versioning directory and a date, it will index the available files in the versioning archive and restore files for you. ``restorething`` has multiple restore modes and the ability to filter files and directories. Restore Modes ------------- ``restorething`` will restore files using the following modes - Nearest file before/after a specific date/time (default behaviour) - Nearest file before a specific date/time - Nearest file after a specific date/time - All instances of a specific file with no date/time restriction ``restorething`` has filtering options - Filter files with specific string - Filter dir with specific string - Filter both dir and file with specific string Installation ------------ ``restorething`` from source .. code:: bash $ python setup.py sdist $ pip install dist\restorething-x.x.x.tar.gz ``restorething`` from PyPI .. code:: bash $ pip install restorething Usage ----- ``$ python -m restorething { date [ -hr {0-24} | -b | -a | -pm {int} | -ai {path and filename} | -vd {dir} | -rd {dir} | -dd {dir} | -df {filename} | -nf | -nd | -ic | -ns | [ -ff {string} | -fd {string} | -fb {path and filename} ] | -d | --version] }`` +-----------+---------+---------------+--------------------------+-------------------+ | Argument | Type | Format | Default | Description | +===========+=========+===============+==========================+===================+ | date | integer | YYYYMMDD | No default value. Field | Date to restore | | | | | must be supplied by user | files, date will | | | | | | be used to find | | | | | | closest file | | | | | | before or after | | | | | | date | +-----------+---------+---------------+--------------------------+-------------------+ | -hr | integer | -hr {0-24} | 12 | Hour to compare | | | | | | file's | | | | | | modification time | +-----------+---------+---------------+--------------------------+-------------------+ | -b | switch | -b | disabled | Limit restore of | | | | | | files to before | | | | | | the supplied date | | | | | | and hour | +-----------+---------+---------------+--------------------------+-------------------+ | -a | switch | -a | disabled | Limit restore of | | | | | | files to after | | | | | | the supplied date | | | | | | and hour | +-----------+---------+---------------+--------------------------+-------------------+ | -pm | integer | -pm | 0 | Limit restore of | | | | {0-2147483647 | | files to | | | | hrs} | | plus/minus hours | | | | | | each side of the | | | | | | supplied date and | | | | | | hour | +-----------+---------+---------------+--------------------------+-------------------+ | -ai | string | -ai {absolute | disabled | Recovers all | | | | path of file} | | versions of a | | | | | | file ignoring any | | | | | | date and times | | | | | | specified | +-----------+---------+---------------+--------------------------+-------------------+ | -vd | string | -vd {absolute | .stversions | Sets the location | | | | or relative | | of the syncthing | | | | path of DIR} | | versioning | | | | | | folder, by | | | | | | default script | | | | | | looks in | | | | | | directory script | | | | | | is run from | +-----------+---------+---------------+--------------------------+-------------------+ | -rd | string | -rd {absolute | restore | Enables the | | | | or relative | | ability to | | | | path of DIR} | | restore to a | | | | | | location other | | | | | | than the default | +-----------+---------+---------------+--------------------------+-------------------+ | -dd | string | -dd {absolute | /home/name/.restorething | Enables the | | | | or relative | | ability to use a | | | | path of DIR} | | database file in | | | | | | a different | | | | | | location, default | | | | | | behaviour is to | | | | | | store database | | | | | | file in users | | | | | | home directory | +-----------+---------+---------------+--------------------------+-------------------+ | -df | string | -df | restorething.db | Enables the | | | | {filename} | | ability to use a | | | | | | database file | | | | | | with a different | | | | | | name | +-----------+---------+---------------+--------------------------+-------------------+ | -nf | switch | -nf | disabled | Enables indexing | | | | | | archived files | | | | | | every time script | | | | | | is run, by | | | | | | default script | | | | | | will reuse | | | | | | existing DB file | | | | | | for 24 hours | +-----------+---------+---------------+--------------------------+-------------------+ | -nd | switch | -nd | disabled | Enables restoring | | | | | | files that have | | | | | | been deleted or | | | | | | changed due to | | | | | | renaming, by | | | | | | default deleted | | | | | | or renamed files | | | | | | are not included | | | | | | in restore | +-----------+---------+---------------+--------------------------+-------------------+ | -ic | switch | -ic | disabled | Enables restoring | | | | | | files that were | | | | | | marked as | | | | | | conflict files by | | | | | | syncthing and | | | | | | deleted by user, | | | | | | by default | | | | | | conflict files | | | | | | are not restored | +-----------+---------+---------------+--------------------------+-------------------+ | -ns | switch | -ns | disabled | Enables no | | | | | | simulation mode, | | | | | | default behaviour | | | | | | is to simulate | | | | | | restore, no | | | | | | simulation mode | | | | | | will copy files | | | | | | from syncthing | | | | | | archive to hard | | | | | | drive | +-----------+---------+---------------+--------------------------+-------------------+ | -ff | string | -ff {string} | disabled | Recovers a single | | | | | | version of any | | | | | | files matching | | | | | | the string | | | | | | supplied | +-----------+---------+---------------+--------------------------+-------------------+ | -fd | string | -fd {string} | disabled | Recovers a single | | | | | | version of all | | | | | | files in any DIR | | | | | | matching the | | | | | | string supplied | +-----------+---------+---------------+--------------------------+-------------------+ | -fb | string | -fb {absolute | disabled | Recovers a single | | | | path of file} | | version of a file | | | | | | matching the DIR | | | | | | and Filename | +-----------+---------+---------------+--------------------------+-------------------+ | -d | switch | -d | disabled | Enables debug | | | | | | output to console | +-----------+---------+---------------+--------------------------+-------------------+ | --version | switch | --version | disabled | Displays version | +-----------+---------+---------------+--------------------------+-------------------+ Default behaviour ----------------- - The default behaviour of the script is to look for the closest file older (before) than supplied date/time. If nothing is found, the script looks for the closest file younger (after) than supplied date/time. The default behaviour can be limited to plus/minus hours by supplying ``-pm {hours}`` argument or changed to only looking before or after supplied date/time by using the ``-b`` or ``-a`` flags, respectively. - If no hour is supplied the default time value the script uses is 12pm. This can be changed by using the ``-hr {0-24}`` argument - The script will always simulate a restore by default giving the user an opportunity to review any detected warnings. By supplying the -ns flag, the user can enable the no simulation mode and do an actual restore, no simulation, no undo. - The script will create a directory named restore in the directory the script is being called from and restore all files recursively inside of it - If no syncthing versioning directory is supplied, the default behaviour is to look in the directory the script is being called from. - All config, log and database files are stored in user's home directory under the directory named .restorething. Examples -------- Restore closest file before 6am 15th August 2016, if no file is found restore closet file after 6am 15th August 2016. Due to not supplying versioning directory, script will need to be called from directory containing versioning directory .. code:: bash $ python -m restorething 20160815 -hr 6 Restore closest file after 6am 15th August 2016, if no file is found, no file will be restored. Versioning directory is supplied as a relative path to where the script is being called from. .. code:: bash $ python -m restorething 20160815 -hr 6 -a -vd sync/.stversions Restore closest file before 6am 15th August 2016, if no file is found, no file will be restored. Versioning directory is supplied as a relative path to where the script is being called from. .. code:: bash $ python -m restorething 20160815 -hr 6 -b -vd sync/.stversions Restore closest file no more than 10 hours before 6am 15th August 2016, if no file is found ``restorething`` will look for the closet file no more than 10 hours after 6am 15th August 2016. Versioning directory is supplied as a relative path to where the script is being called from. .. code:: bash $ python -m restorething 20160815 -hr 6 -pm 10 -vd sync/.stversions Restore all instances of a file located in directory ``/some/important/directory/``, named ``file.txt``. Current script limitation is you have to supply a date, although it will be ignored. .. code:: bash $ python -m restorething 20160815 -ai /some/important/directory/file.txt
/restorething-0.2.4.tar.gz/restorething-0.2.4/README.rst
0.862439
0.657751
README.rst
pypi
Restorething ============ `restorething` is a tool for restoring files from a syncthing versioning archive. Supply `restorething` the path to the syncthing versioning directory and a date, it will index the available files in the versioning archive and restore files for you. `restorething` has multiple restore modes and the ability to filter files and directories. Restore Modes ------------- `restorething` will restore files using the following modes * Nearest file before/after a specific date/time (default behaviour) * Nearest file before a specific date/time * Nearest file after a specific date/time * All instances of a specific file with no date/time restriction `restorething` has filtering options * Filter files with specific string * Filter dir with specific string * Filter both dir and file with specific string Installation ------------- ```restorething``` from source ```bash $ python setup.py sdist $ pip install dist\restorething-x.x.x.tar.gz ``` ```restorething``` from PyPI ```bash $ pip install restorething ``` Usage ----- ` $ python -m restorething { date [ -hr {0-24} | -b | -a | -pm {int} | -ai {path and filename} | -vd {dir} | -rd {dir} | -dd {dir} | -df {filename} | -nf | -nd | -ic | -ns | [ -ff {string} | -fd {string} | -fb {path and filename} ] | -d | --version] } ` Argument | Type | Format | Default | Description ----------|--------|---------------|----------------------------|-------------------- date | integer | YYYYMMDD | No default value. Field must be supplied by user | Date to restore files, date will be used to find closest file before or after date -hr | integer | -hr {0-24} | 12 | Hour to compare file's modification time -b | switch | -b | disabled | Limit restore of files to before the supplied date and hour -a | switch | -a | disabled | Limit restore of files to after the supplied date and hour -pm | integer | -pm {0-2147483647 hrs} | 0 | Limit restore of files to plus/minus hours each side of the supplied date and hour -ai | string | -ai {absolute path of file} | disabled | Recovers all versions of a file ignoring any date and times specified -vd | string | -vd {absolute or relative path of DIR} | .stversions | Sets the location of the syncthing versioning folder, by default script looks in directory script is run from -rd | string | -rd {absolute or relative path of DIR} | restore | Enables the ability to restore to a location other than the default -dd | string | -dd {absolute or relative path of DIR} | /home/name/.restorething | Enables the ability to use a database file in a different location, default behaviour is to store database file in users home directory -df | string | -df {filename} | restorething.db | Enables the ability to use a database file with a different name -nf | switch | -nf | disabled | Enables indexing archived files every time script is run, by default script will reuse existing DB file for 24 hours -nd | switch | -nd | disabled | Enables restoring files that have been deleted or changed due to renaming, by default deleted or renamed files are not included in restore -ic | switch | -ic | disabled | Enables restoring files that were marked as conflict files by syncthing and deleted by user, by default conflict files are not restored -ns | switch | -ns | disabled | Enables no simulation mode, default behaviour is to simulate restore, no simulation mode will copy files from syncthing archive to hard drive -ff | string | -ff {string} | disabled | Recovers a single version of any files matching the string supplied -fd | string | -fd {string} | disabled | Recovers a single version of all files in any DIR matching the string supplied -fb | string | -fb {absolute path of file} | disabled | Recovers a single version of a file matching the DIR and Filename -d | switch | -d | disabled | Enables debug output to console --version | switch | --version | disabled | Displays version Default behaviour ----------------- * The default behaviour of the script is to look for the closest file older (before) than supplied date/time. If nothing is found, the script looks for the closest file younger (after) than supplied date/time. The default behaviour can be limited to plus/minus hours by supplying `-pm {hours}` argument or changed to only looking before or after supplied date/time by using the `-b` or `-a` flags, respectively. * If no hour is supplied the default time value the script uses is 12pm. This can be changed by using the `-hr {0-24}` argument * The script will always simulate a restore by default giving the user an opportunity to review any detected warnings. By supplying the -ns flag, the user can enable the no simulation mode and do an actual restore, no simulation, no undo. * The script will create a directory named restore in the directory the script is being called from and restore all files recursively inside of it * If no syncthing versioning directory is supplied, the default behaviour is to look in the directory the script is being called from. * All config, log and database files are stored in user's home directory under the directory named .restorething. Examples -------- Restore closest file before 6am 15th August 2016, if no file is found restore closet file after 6am 15th August 2016. Due to not supplying versioning directory, script will need to be called from directory containing versioning directory ```bash $ python -m restorething 20160815 -hr 6 ``` Restore closest file after 6am 15th August 2016, if no file is found, no file will be restored. Versioning directory is supplied as a relative path to where the script is being called from. ```bash $ python -m restorething 20160815 -hr 6 -a -vd sync/.stversions ``` Restore closest file before 6am 15th August 2016, if no file is found, no file will be restored. Versioning directory is supplied as a relative path to where the script is being called from. ```bash $ python -m restorething 20160815 -hr 6 -b -vd sync/.stversions ``` Restore closest file no more than 10 hours before 6am 15th August 2016, if no file is found `restorething` will look for the closet file no more than 10 hours after 6am 15th August 2016. Versioning directory is supplied as a relative path to where the script is being called from. ```bash $ python -m restorething 20160815 -hr 6 -pm 10 -vd sync/.stversions ``` Restore all instances of a file located in directory `/some/important/directory/`, named `file.txt`. Current script limitation is you have to supply a date, although it will be ignored. ```bash $ python -m restorething 20160815 -ai /some/important/directory/file.txt ```
/restorething-0.2.4.tar.gz/restorething-0.2.4/README.md
0.445168
0.950503
README.md
pypi
import logging import urlparse import httplib2 logger = logging.getLogger(__name__) class Request(dict): def __init__(self, uri, method, body=None, headers=None): super(Request, self).__init__() self._uri = uri self._method = method self._body = body if headers is None: headers = {} self._headers = headers self.update(dict([(k.title().replace('_', '-'), v) for k, v in headers.items()])) @property def headers(self): """ Return the actual headers. """ return self._headers @property def uri(self): return self._uri @property def method(self): return self._method @property def body(self): return self._body class Response(dict): def __init__(self, client, response_headers, response_content, request): super(Response, self).__init__() self.client = client self.headers = response_headers self.raw_content = response_content self.content = response_content self.request = request # Make headers consistently accessible. self.update(dict([(k.title().replace('_', '-'), v) for k, v in response_headers.items()])) # Set status code on its own property. self.status_code = int(self.pop('Status')) class ClientMixin(object): """ This mixin contains the attribute ``MIME_TYPE`` which is ``None`` by default. Subclasses can set it to some mime-type that will be used as ``Content-Type`` and ``Accept`` header in requests. If the ``MIME_TYPE`` is also found in the ``Content-Type`` response headers, the response contents will be deserialized. """ root_uri = '' MIME_TYPE = None def serialize(self, data): """ Produces a serialized version suitable for transfer over the wire. Subclasses should override this function to implement their own serializing scheme. This implementation simply returns the data passed to this function. Data from the serialize function passed to the deserialize function, and vice versa, should return the same value. :param data: Data. :return: Serialized data. """ return data def deserialize(self, data): """ Deserialize the data from the raw data. Subclasses should override this function to implement their own deserializing scheme. This implementation simply returns the data passed to this function. Data from the serialize function passed to the deserialize function, and vice versa, should return the same value. :param data: Serialized data. :return: Data. """ return data def create_request(self, uri, method, body=None, headers=None): """ Returns a ``Request`` object. """ if not uri.startswith(self.root_uri): uri = urlparse.urljoin(self.root_uri, uri) if headers is None: headers = {} if self.MIME_TYPE: headers.update({ 'Accept': self.MIME_TYPE, 'Content-Type': self.MIME_TYPE, }) data = self.serialize(body) return Request(uri, method, data, headers) def create_response(self, response_headers, response_content, request): """ Returns a ``Response`` object. """ response = Response(self, response_headers, response_content, request) if not self.MIME_TYPE or ('Content-Type' in response and response['Content-Type'].startswith(self.MIME_TYPE)): response.content = self.deserialize(response_content) return response def get(self, uri): """ Convenience method that performs a GET-request. """ return self.request(uri, 'GET') def post(self, uri, data): """ Convenience method that performs a POST-request. """ return self.request(uri, 'POST', data) def put(self, uri, data): """ Convenience method that performs a PUT-request. """ return self.request(uri, 'PUT', data) def delete(self, uri): """ Convenience method that performs a DELETE-request. """ return self.request(uri, 'DELETE') class BaseClient(httplib2.Http): """ Simple RESTful client based on ``httplib2.Http``. """ def __init__(self, *args, **kwargs): """ Takes one additional argument ``root_uri``. All other arguments are passed to the ``httplib2.Http`` constructor. """ if 'root_uri' in kwargs: self.root_uri = kwargs.pop('root_uri') super(BaseClient, self).__init__(*args, **kwargs) def request(self, uri, method='GET', body=None, headers=None, redirections=5, connection_type=None): """ Creates a ``Request`` object by calling ``self.create_request(uri, method, body, headers)`` and performs the low level HTTP-request using this request object. A ``Response`` object is created with the data returned from the request, by calling ``self.create_response(response_headers, response_content, request)`` and is returned. """ # Create request. request = self.create_request(uri, method, body, headers) # Perform an HTTP-request with ``httplib2``. try: response_headers, response_content = super(BaseClient, self).request(request.uri, request.method, request.body, request, redirections, connection_type) except Exception, e: # Logging. logger.critical('%(method)s %(uri)s\n%(headers)s\n\n%(body)s\n\n\nException: %(exception)s', { 'method': request.method, 'uri': request.uri, 'headers': '\n'.join(['%s: %s' % (k, v) for k, v in request.items()]), 'body': request.body if request.body else '', 'exception': unicode(e), }) raise else: # Create response. response = self.create_response(response_headers, response_content, request) # Logging. if logger.level > logging.DEBUG: logger.info('%(method)s %(uri)s (HTTP %(response_status)s)' % { 'method': request.method, 'uri': request.uri, 'response_status': response.status_code }) else: logger.debug('%(method)s %(uri)s\n%(headers)s\n\n%(body)s\n\n\nHTTP %(response_status)s\n%(response_headers)s\n\n%(response_content)s', { 'method': request.method, 'uri': request.uri, 'headers': '\n'.join(['%s: %s' % (k, v) for k, v in request.items()]), 'body': request.body if request.body else '', 'response_status': response.status_code, 'response_headers': '\n'.join(['%s: %s' % (k, v) for k, v in response.items()]), # Show the actual content, not response.content 'response_content': response_content }) return response class Client(BaseClient, ClientMixin): pass
/restorm-setuptools-0.3.1.tar.gz/restorm-setuptools-0.3.1/restorm/clients/base.py
0.708515
0.169887
base.py
pypi
from restorm.clients.jsonclient import JSONClientMixin, json from restorm.clients.mockclient import BaseMockApiClient class LibraryApiClient(BaseMockApiClient, JSONClientMixin): """ Mock library webservice containing books and authors. .. note:: This is a very inconsistent webservice. All resources are for demonstration purposes and show different kinds of ReST structures. """ def __init__(self, root_uri=None): # Creating a mock server from this MockApiClient, related resource # URI's need to show the same IP address and port. if not root_uri: root_uri = 'http://localhost/api/' responses = { # The index. '': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( [{ 'description': 'List of books.', 'resource_url': '%sbook/' % root_uri }, { 'description': 'List of authors.', 'resource_url': '%sauthor/' % root_uri }, { 'description': 'Search in our database', 'resource_url': '%ssearch/' % root_uri }]) ) }, # Book list view contains a ``list`` of ``objects`` representing a # (small part of the) book. 'book/': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( [{ 'isbn': '978-1441413024', 'title': 'Dive into Python', 'resource_url': '%sbook/978-1441413024' % root_uri }, { 'isbn': '978-1590597255', 'title': 'The Definitive Guide to Django', 'resource_url': '%sbook/978-1590597255' % root_uri }]) ) }, # Book item view contains a single ``object`` representing a book, # including (in addition to the list view) the author resource, # ISBN and subtitle. 'book/978-1441413024': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'isbn': '978-1441413024', 'title': 'Dive into Python', 'subtitle': None, 'author': '%sauthor/1' % root_uri }) ) }, 'book/978-1590597255': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'isbn': '978-1590597255', 'title': 'The Definitive Guide to Django', 'subtitle': 'Web Development Done Right', 'author': '%sauthor/2' % root_uri }) ) }, # Author list view contains an ``object`` with a single item # containing the ``list`` of ``objects``. This, in contrast to the # list view of books, which contains a ``list`` as root element. 'author/': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'author_set': [{ 'id': 1, 'name': 'Mark Pilgrim', 'resource_url': '%sauthor/1' % root_uri }, { 'id': 2, 'name': 'Jacob Kaplan-Moss', 'resource_url': '%sauthor/2' % root_uri }] }) ) }, # Author item view. Contains a nested list of all books the author # has written. 'author/1': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'id': 1, 'name': 'Mark Pilgrim', 'books': [{ 'isbn': '978-1441413024', 'title': 'Dive into Python', 'resource_url': '%sbook/978-1441413024' % root_uri }] }) ) }, 'author/2': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'id': 2, 'name': 'Jacob Kaplan-Moss', 'books': [{ 'isbn': '978-1590597255', 'title': 'The Definitive Guide to Django', 'resource_url': '%sbook/978-1590597255' % root_uri }] }) ) }, # Ofcourse, it doesn't matter what you sent to this resource, the # results will always be the same. 'search/': { 'POST': ({'Status': 200, 'Content-Type': 'application/json', 'X-Cache': 'MISS'}, json.dumps( { 'meta': { 'query': 'Python', 'total': 1, }, 'results': [{ 'isbn': '978-1441413024', 'title': 'Dive into Python', 'resource_url': '%sbook/978-1441413024' % root_uri }] }) ) } } super(LibraryApiClient, self).__init__(responses=responses, root_uri=root_uri) class TicketApiClient(BaseMockApiClient, JSONClientMixin): """ Mock issue ticket API. .. note:: This is a very inconsistent webservice. All resources are for demonstration purposes and show different kinds of ReST structures. """ def __init__(self, root_uri=None): # Creating a mock server from this MockApiClient, related resource # URI's need to show the same IP address and port. if not root_uri: root_uri = 'http://localhost/api/' responses = { # Issue list view contains a ``list`` of ``objects``. 'issue/': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( [{ 'id': 1, 'title': 'Cannot update an issue', 'resource_url': '%sissue/1' % root_uri }, { 'id': 2, 'title': 'Cannot create an issue', 'resource_url': '%sissue/2' % root_uri }]) ), 'POST': ({'Status': 201, 'Content-Type': 'application/json', 'Location': '%sissue/2' % root_uri}, json.dumps('')) }, # Issue item view contains a single ``object`` representing an issue. 'issue/1': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'id': 1, 'title': 'Cannot update an issue', 'description': 'This needs more work.', }) ) }, 'issue/2': { 'GET': ({'Status': 200, 'Content-Type': 'application/json'}, json.dumps( { 'id': 2, 'title': 'Cannot create an issue', 'description': 'This needs more work.', }) ), 'PUT': ({'Status': 204, 'Content-Type': 'application/json'}, json.dumps('')) }, } super(TicketApiClient, self).__init__(responses=responses, root_uri=root_uri)
/restorm-setuptools-0.3.1.tar.gz/restorm-setuptools-0.3.1/restorm/examples/mock/api.py
0.644449
0.185025
api.py
pypi
import time import hashlib import random import datetime import M2Crypto.X509 import M2Crypto.EVP import M2Crypto.ASN1 import M2Crypto.RSA import M2Crypto.BIO _SERIAL_NUMBER_GENERATOR_CB = lambda: \ hashlib.sha1(str(time.time()) + str(random.random())).\ hexdigest() def pem_private_to_rsa(private_key_pem, passphrase=None): def passphrase_cb(*args): return passphrase rsa = M2Crypto.RSA.load_key_string( private_key_pem, callback=passphrase_cb) return rsa def pem_csr_to_csr(csr_pem): return M2Crypto.X509.load_request_string(csr_pem) def pem_certificate_to_x509(cert_pem): return M2Crypto.X509.load_cert_string(cert_pem) def new_cert(ca_private_key_pem, csr_pem, validity_td, issuer_name, bits=2048, is_ca=False, passphrase=None): ca_rsa = pem_private_to_rsa( ca_private_key_pem, passphrase=passphrase) def callback(*args): pass csr = pem_csr_to_csr(csr_pem) public_key = csr.get_pubkey() name = csr.get_subject() cert = M2Crypto.X509.X509() sn_hexstring = _SERIAL_NUMBER_GENERATOR_CB() sn = int(sn_hexstring, 16) cert.set_serial_number(sn) cert.set_subject(name) now_epoch = long(time.time()) notBefore = M2Crypto.ASN1.ASN1_UTCTIME() notBefore.set_time(now_epoch) notAfter = M2Crypto.ASN1.ASN1_UTCTIME() notAfter.set_time(now_epoch + long(validity_td.total_seconds())) cert.set_not_before(notBefore) cert.set_not_after(notAfter) cert.set_issuer(issuer_name) cert.set_pubkey(public_key) ext = M2Crypto.X509.new_extension('basicConstraints', 'CA:FALSE') cert.add_ext(ext) pkey = M2Crypto.EVP.PKey() pkey.assign_rsa(ca_rsa) cert.sign(pkey, 'sha1') cert_pem = cert.as_pem() return cert_pem def sign(ca_key_filepath, ca_crt_filepath, csr_filepath, passphrase=None): with open(ca_crt_filepath) as f: ca_cert_pem = f.read() with open(ca_key_filepath) as f: ca_private_key_pem = f.read() ca_cert = pem_certificate_to_x509(ca_cert_pem) issuer_name = ca_cert.get_issuer() with open(csr_filepath) as f: csr_pem = f.read() validity_td = datetime.timedelta(days=400) return new_cert( ca_private_key_pem, csr_pem, validity_td, issuer_name, passphrase=passphrase) def new_selfsigned_cert(issuer_name, passphrase, validity_td, bits=2048, is_ca=False): pair = new_key(passphrase) (private_key_pem, public_key_pem) = pair csr_pem = new_csr( private_key_pem, issuer_name, passphrase=passphrase) cert_pem = new_cert( private_key_pem, csr_pem, validity_td, issuer_name, passphrase=passphrase, is_ca=is_ca) return (private_key_pem, public_key_pem, csr_pem, cert_pem) def new_csr(private_key_pem, name, passphrase=None): rsa = pem_private_to_rsa( private_key_pem, passphrase=passphrase) pkey = M2Crypto.EVP.PKey() pkey.assign_rsa(rsa) rsa = None # should not be freed here csr = M2Crypto.X509.Request() csr.set_pubkey(pkey) csr.set_subject(name) csr.sign(pkey, 'sha1') return csr.as_pem() def rsa_to_pem_private(rsa, passphrase=None): bio = M2Crypto.BIO.MemoryBuffer() private_key_kwargs = {} if passphrase is None: private_key_kwargs['cipher'] = None else: def passphrase_cb(arg1): return passphrase private_key_kwargs['callback'] = passphrase_cb rsa.save_key_bio(bio, **private_key_kwargs) return bio.read() def rsa_to_pem_public(rsa): bio = M2Crypto.BIO.MemoryBuffer() rsa.save_pub_key_bio(bio) return bio.read() def new_key_primitive(bits=2048): # This is called during key-generation to provide visual feedback. The # default callback shows progress dots. def progress_cb(arg1, arg2): pass return M2Crypto.RSA.gen_key(bits, 65537, progress_cb) def new_key(passphrase=None, bits=2048): rsa = new_key_primitive(bits) private_key_pem = rsa_to_pem_private(rsa, passphrase) public_key_pem = rsa_to_pem_public(rsa) return (private_key_pem, public_key_pem) def build_name_from_dict(**kwargs): name = M2Crypto.X509.X509_Name() for (k, v) in kwargs.items(): try: M2Crypto.X509.X509_Name.nid[k] except KeyError as e: raise KeyError(k) setattr(name, k, v) return name def create_csr(**name_fields): pk = M2Crypto.EVP.PKey() x = M2Crypto.X509.Request() rsa = new_key_primitive() pk.assign_rsa(rsa) x.set_pubkey(pk) name = x.get_subject() for k, v in name_fields.items(): setattr(name, k, v) public_key_pem = rsa_to_pem_public(rsa) private_key_pem = rsa_to_pem_private(rsa) csr_pem = x.as_pem() return (private_key_pem, public_key_pem, csr_pem)
/restpipe-0.2.20.tar.gz/restpipe-0.2.20/rpipe/resources/ssl/ssl_library.py
0.413477
0.207415
ssl_library.py
pypi
from .apis import Apis from .digest_algorithm import DigestAlgorithm from .file_reference import FileReference from .rest_pki_client import _get_api_version from .signature_starter import SignatureStarter from .signature_start_result import SignatureStartResult class CadesSignatureStarter(SignatureStarter): def __init__(self, client): super(CadesSignatureStarter, self).__init__(client) self.__file_to_sign = None self.__cms_to_cosign = None self.__encapsulate_content = True self.__digest_algorithms_for_detached_signature = [ DigestAlgorithm.SHA1, DigestAlgorithm.SHA256 ] # region "file_to_sign" accessors @property def file_to_sign(self): return self.__get_file_to_sign() def __get_file_to_sign(self): return self.__file_to_sign.file_desc @file_to_sign.setter def file_to_sign(self, value): self.__set_file_to_sign(value) def __set_file_to_sign(self, value): if value is None: raise Exception('The provided "file_to_sign" is not valid') self.__file_to_sign = FileReference.from_file(value) # endregion # region "file_to_sign_path" accessors @property def file_to_sign_path(self): return self.__get_file_to_sign_path() def __get_file_to_sign_path(self): return self.__file_to_sign.path @file_to_sign_path.setter def file_to_sign_path(self, value): self.__set_file_to_sign_path(value) def __set_file_to_sign_path(self, value): if value is None: raise Exception('The provided "file_to_sign_path" is not valid') self.__file_to_sign = FileReference.from_path(value) def set_file_to_sign_from_path(self, path): self.__set_file_to_sign_path(path) def set_file_to_sign_path(self, path): self.set_file_to_sign_from_path(path) def set_file_to_sign(self, path): self.set_file_to_sign_path(path) # endregion # region "file_to_sign_base64" accessors @property def file_to_sign_base64(self): return self.__get_file_to_sign_base64() def __get_file_to_sign_base64(self): return self.__file_to_sign.content_base64 @file_to_sign_base64.setter def file_to_sign_base64(self, value): self.__set_file_to_sign_base64(value) def __set_file_to_sign_base64(self, value): if value is None: raise Exception('The provided "file_to_sign_base64" is not valid') self.__file_to_sign_base64 = FileReference.from_content_base64(value) def set_file_to_sign_from_content_base64(self, content_base64): self.__set_file_to_sign_base64(content_base64) # endregion # region "file_to_sign_content" accessors @property def file_to_sign_content(self): return self.__get_file_to_sign_content() def __get_file_to_sign_content(self): return self.__file_to_sign_content @file_to_sign_content.setter def file_to_sign_content(self, value): self.__set_file_to_sign_content(value) def __set_file_to_sign_content(self, value): if value is None: raise Exception('The provided "file_to_sign_content" is not valid') self.__file_to_sign_content = value def set_file_to_sign_from_content_raw(self, content_raw): self.__set_file_to_sign_content(content_raw) def set_file_to_sign_content(self, content_raw): self.set_file_to_sign_from_content_raw(content_raw) # endregion # region "cms_to_cosign" accessors @property def cms_to_cosign(self): return self.__get_cms_to_cosign() def __get_cms_to_cosign(self): return self.__cms_to_cosign.file_desc @cms_to_cosign.setter def cms_to_cosign(self, value): self.__set_cms_to_cosign(value) def __set_cms_to_cosign(self, value): if value is None: raise Exception('The provided "cms_to_cosign" is not valid') self.__cms_to_cosign = FileReference.from_file(value) # endregion # region "cms_to_cosign_path" accessors @property def cms_to_cosign_path(self): return self.__get_cms_to_cosign_path() def __get_cms_to_cosign_path(self): return self.__cms_to_cosign.path @cms_to_cosign_path.setter def cms_to_cosign_path(self, value): self.__set_cms_to_cosign_path(value) def __set_cms_to_cosign_path(self, value): if value is None: raise Exception('The provided "cms_to_cosign_path" is not valid') self.__cms_to_cosign = FileReference.from_path(value) def set_cms_to_cosign_from_path(self, path): self.__set_cms_to_cosign_path(path) def set_cms_to_cosign_path(self, path): self.set_cms_to_cosign_from_path(path) def set_cms_to_cosign(self, path): self.set_cms_to_cosign_path(path) # endregion # region "cms_to_cosign_content" accessors @property def cms_to_cosign_content(self): return self.__get_cms_to_cosign_content() def __get_cms_to_cosign_content(self): return self.__cms_to_cosign.content_raw @cms_to_cosign_content.setter def cms_to_cosign_content(self, value): self.__set_cms_to_cosign_content(value) def __set_cms_to_cosign_content(self, value): if value is None: raise Exception('The provided "cms_to_cosign_content" is not valid') self.__cms_to_cosign = FileReference.from_content_raw(value) def set_cms_to_cosign_from_content_raw(self, content_raw): self.__set_cms_to_cosign_content(content_raw) def set_cms_to_cosign_content(self, content_raw): self.set_cms_to_cosign_from_content_raw(content_raw) # endregion # region "cms_to_cosign_base64" accessors @property def cms_to_cosign_base64(self): return self.__get_cms_to_cosign_base64() def __get_cms_to_cosign_base64(self): return self.__cms_to_cosign.content_base64 @cms_to_cosign_base64.setter def cms_to_cosign_base64(self, value): self.__set_cms_to_cosign_base64(value) def __set_cms_to_cosign_base64(self, value): if value is None: raise Exception('The provided "cms_to_cosign_base64" is not valid') self.__cms_to_cosign = FileReference.from_content_base64(value) def set_cms_to_cosign_from_content_base64(self, content_base64): self.__set_cms_to_cosign_base64(content_base64) # endregion # region "cms_to_cosign_result" accessors @property def cms_to_cosign_result(self): return self.__get_cms_to_cosign_result() def __get_cms_to_cosign_result(self): return self.__cms_to_cosign.result @cms_to_cosign_result.setter def cms_to_cosign_result(self, value): self.__set_cms_to_cosign_result(value) def __set_cms_to_cosign_result(self, value): if value is None: raise Exception('The provided "cms_to_cosign_result" is not valid') self.__cms_to_cosign = FileReference.from_result(value) # endregion @property def encapsulate_content(self): return self.__encapsulate_content @encapsulate_content.setter def encapsulate_content(self, value): self.__encapsulate_content = value def start(self): if self._signer_certificate is None: raise Exception('The certificate was not set') response = self.__start_common() return SignatureStartResult(response) def start_with_web_pki(self): response = self.__start_common() return SignatureStartResult(response) def start_with_webpki(self): return self.start_with_web_pki() def __start_common(self): if self.__file_to_sign is None and self.__cms_to_cosign is None: raise Exception('The content to sign was not set and no CMS to be ' 'co-signed was given') if self._signature_policy_id is None: raise Exception('The signature policy was not set') api_version = _get_api_version(self._client, Apis.START_CADES) if api_version == 1: return self.__start_common_v1() elif api_version == 2: return self.__start_common_v2() return self.__start_common_v3() def __start_common_v3(self): request = self.__get_start_common_request() if self.__file_to_sign is not None: if not self.__encapsulate_content: request['dataHashes'] = self.__file_to_sign.compute_data_hashes( self.__digest_algorithms_for_detached_signature) else: request['fileToSign'] = \ self.__file_to_sign.upload_or_reference(self._client) if self.__cms_to_cosign is not None: request['cmsToCoSign'] = \ self.__cms_to_cosign.upload_or_reference(self._client) return self._client.post('Api/v3/CadesSignatures', request) def __start_common_v2(self): request = self.__get_start_common_request() if self.__file_to_sign is not None: if not self.__encapsulate_content: request['dataHashes'] = self.__file_to_sign.compute_data_hashes( self.__digest_algorithms_for_detached_signature) else: request['contentToSign'] = self.__file_to_sign.content_base64 if self.__cms_to_cosign is not None: request['cmsToCoSign'] = self.__file_to_sign.content_base64 return self._client.post('Api/v2/CadesSignatures', request) def __start_common_v1(self): request = self.__get_start_common_request() if self.__file_to_sign is not None: request['contentToSign'] = self.__file_to_sign.content_base64 if self.__cms_to_cosign is not None: request['cmsToCoSign'] = self.__file_to_sign.content_base64 return self._client.post('Api/CadesSignatures', request) def __get_start_common_request(self): return { 'certificate': self._signer_certificate, 'signaturePolicyId': self._signature_policy_id, 'securityContextId': self._security_context_id, 'ignoreRevocationStatusUnknown': self._ignore_revocation_status_unknown, 'callbackArgument': self._callback_argument, 'encapsulateContent': self.__encapsulate_content } __all__ = ['CadesSignatureStarter']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/cades_signature_starter.py
0.656548
0.218294
cades_signature_starter.py
pypi
from .digest_algorithm import DigestAlgorithm from .pk_certificate import PKCertificate class SignatureStartResult(object): def __init__(self, response): certificate = response.get('certificate', None) if certificate is not None: self.__certificate = PKCertificate(certificate) self.__token = response.get('token', None) self.__to_sign_data = response.get('toSignData', None) self.__to_sign_hash = response.get('toSignHash', None) self.__digest_algorithm_oid = response.get('digestAlgorithmOid', None) self.__digest_algorithm = None # region "certificate" accessors @property def certificate(self): return self.__get_certificate() def __get_certificate(self): return self.__certificate @certificate.setter def certificate(self, value): self.__set_certificate(value) def __set_certificate(self, value): if value is None: raise Exception('The provided "certificate" is not valid') self.__certificate = value # endregion # region "token" accessors @property def token(self): return self.__get_token() def __get_token(self): return self.__token @token.setter def token(self, value): self.__set_token(value) def __set_token(self, value): if value is None: raise Exception('The provided "token" is not valid') self.__token = value # endregion # region "to_sign_data" accessors @property def to_sign_data(self): return self.__get_to_sign_data() def __get_to_sign_data(self): return self.__to_sign_data @to_sign_data.setter def to_sign_data(self, value): self.__set_to_sign_data(value) def __set_to_sign_data(self, value): if value is None: raise Exception('The provided "to_sign_data" is not valid') self.__to_sign_data = value # endregion # region "to_sign_hash" accessors @property def to_sign_hash(self): return self.__get_to_sign_hash() def __get_to_sign_hash(self): return self.__to_sign_hash @to_sign_hash.setter def to_sign_hash(self, value): self.__set_to_sign_hash(value) def __set_to_sign_hash(self, value): if value is None: raise Exception('The provided "to_sign_hash" is not valid') self.__to_sign_hash = value # endregion # region "digest_algorithm_oid" accessors @property def digest_algorithm_oid(self): return self.__get_digest_algorithm_oid() def __get_digest_algorithm_oid(self): return self.__digest_algorithm_oid @digest_algorithm_oid.setter def digest_algorithm_oid(self, value): self.__set_digest_algorithm_oid(value) def __set_digest_algorithm_oid(self, value): if value is None: raise Exception( 'The provided "digest_algorithm_oid" is not valid') self.__digest_algorithm_oid = value # endregion @property def digest_algorithm(self): if self.__digest_algorithm is None: if self.__digest_algorithm_oid is None: return None self.__digest_algorithm = DigestAlgorithm\ .get_instance_by_oid(self.__digest_algorithm_oid) return self.__digest_algorithm __all__ = ['SignatureStartResult']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/signature_start_result.py
0.779154
0.211071
signature_start_result.py
pypi
import six @six.python_2_unicode_compatible class ValidationResults(object): def __init__(self, model): self._errors = None self._warnings = None self._passed_checks = None if model.get('errors', None) is not None: self._errors = self._convert_items(model['errors']) if model.get('warnings', None) is not None: self._warnings = self._convert_items(model['warnings']) if model.get('passedChecks', None) is not None: self._passed_checks = self._convert_items(model['passedChecks']) @property def errors(self): return self._errors @errors.setter def errors(self, value): self._errors = value @property def warning(self): return self._warnings @warning.setter def warning(self, value): self._warnings = value @property def passed_checks(self): return self._passed_checks @passed_checks.setter def passed_checks(self, value): self._passed_checks = value @property def is_valid(self): return len(self._errors) == 0 @property def checks_performed(self): return len(self._errors) + \ len(self._warnings) + \ len(self._passed_checks) @property def has_errors(self): return not len(self._errors) == 0 @property def has_warnings(self): return not len(self._warnings) == 0 @staticmethod def _convert_items(items): converted = list() for item in items: converted.append(ValidationItem(item)) return converted @staticmethod def _join_items(items, indentation_level): text = '' is_first = True tab = '\t' * indentation_level for item in items: if is_first: is_first = False else: text += '\n' text += '%s- ' % tab text += item.to_string(indentation_level) return text @property def summary(self): return self.get_summary(0) def get_summary(self, indentation_level=0): tab = '\t' * indentation_level text = '%sValidation results: ' % tab if self.checks_performed == 0: text += 'no checks performed' else: text += '%s checks performed' % self.checks_performed if self.has_errors: text += ', %s errors' % len(self._errors) if self.has_warnings: text += ', %s warnings' % len(self._warnings) if len(self._passed_checks) > 0: if not self.has_errors and not self.has_warnings: text += ', all passed' else: text += ', %s passed' % len(self._passed_checks) return text def __str__(self): return self.to_string(0) def to_string(self, indentation_level): tab = '\t' * indentation_level text = '' text += self.get_summary(indentation_level) if self.has_errors: text += '\n%sErrors:\n' % tab text += self._join_items(self._errors, indentation_level) if self.has_warnings: text += '\n%sWarnings:\n' % tab text += self._join_items(self._warnings, indentation_level) if self._passed_checks is not None: text += '\n%sPassed checks:\n' % tab text += self._join_items(self._passed_checks, indentation_level) return text class ValidationItem: def __init__(self, model): self._item_type = model.get('type', None) self._message = model.get('message', None) self._detail = model.get('detail', None) self._inner_validation_results = None if model.get('innerValidationResults', None) is not None: self._inner_validation_results = ValidationResults( model['innerValidationResults']) @property def item_type(self): return self._item_type @item_type.setter def item_type(self, value): self._item_type = value @property def message(self): return self._message @message.setter def message(self, value): self._message = value @property def detail(self): return self._detail @detail.setter def detail(self, value): self._detail = value @property def inner_validation_results(self): return self._inner_validation_results @inner_validation_results.setter def inner_validation_results(self, value): self._inner_validation_results = value def __str__(self): return self.__unicode__() def __unicode__(self): return self.to_string(0) def to_string(self, indentation_level): text = '' text += self._message if self._detail is not None and len(self._detail) > 0: text += ' (%s)' % self._detail if self._inner_validation_results is not None: text += '\n' text += '' text += self._inner_validation_results\ .to_string(indentation_level + 1) return text __all__ = [ 'ValidationResults', 'ValidationItem' ]
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/validation.py
0.657978
0.209834
validation.py
pypi
import hashlib from abc import ABCMeta from abc import abstractmethod from six import BytesIO from .enum import Enum from .oids import Oids class DigestAlgorithms(Enum): MD5 = None SHA1 = None SHA256 = None SHA384 = None SHA512 = None SHA3_256 = None DigestAlgorithms.MD5 = DigestAlgorithms('MD5') DigestAlgorithms.SHA1 = DigestAlgorithms('SHA1') DigestAlgorithms.SHA256 = DigestAlgorithms('SHA256') DigestAlgorithms.SHA384 = DigestAlgorithms('SHA384') DigestAlgorithms.SHA512 = DigestAlgorithms('SHA512') DigestAlgorithms.SHA3_256 = DigestAlgorithms('SHA3_256') class DigestAlgorithm(object): __metaclass__ = ABCMeta MD5 = None SHA1 = None SHA256 = None SHA384 = None SHA512 = None SHA3_256 = None def __init__(self, name, oid, xml_uri, byte_length, api_model): self.__name = name self.__oid = oid self.__xml_uri = xml_uri self.__byte_length = byte_length self.__api_model = api_model def __eq__(self, instance): if instance is None: return False return self.__oid == instance.oid @staticmethod def _algorithms(): return [ DigestAlgorithm.MD5, DigestAlgorithm.SHA1, DigestAlgorithm.SHA256, DigestAlgorithm.SHA384, DigestAlgorithm.SHA512, DigestAlgorithm.SHA3_256 ] @staticmethod def _get_safe_algorithms(): return [ DigestAlgorithm.SHA256, DigestAlgorithm.SHA384, DigestAlgorithm.SHA512, DigestAlgorithm.SHA3_256 ] @staticmethod def get_instance_by_name(name): filtered_list = list(filter(lambda a: a.name == name, DigestAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized digest algorithm name: %s' % name) return alg @staticmethod def get_instance_by_oid(oid): filtered_list = list(filter(lambda a: a.oid == oid, DigestAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized digest algorithm oid: %s' % oid) return alg @staticmethod def get_instance_by_xml_uri(xml_uri): filtered_list = list(filter(lambda a: a.xml_uri == xml_uri, DigestAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized digest algorithm XML URI: %s' % xml_uri) return alg @staticmethod def get_instance_by_api_model(algorithm): if algorithm == DigestAlgorithms.MD5: return DigestAlgorithm.MD5 elif algorithm == DigestAlgorithms.SHA1: return DigestAlgorithm.SHA1 elif algorithm == DigestAlgorithms.SHA256: return DigestAlgorithm.SHA256 elif algorithm == DigestAlgorithms.SHA384: return DigestAlgorithm.SHA384 elif algorithm == DigestAlgorithms.SHA512: return DigestAlgorithm.SHA512 elif algorithm == DigestAlgorithms.SHA3_256: return DigestAlgorithm.SHA3_256 else: raise Exception('Unsupported digest algorithm: %s' % algorithm) def compute_hash_from_content(self, content, offset=0, count=-1): stream = BytesIO(content) stream.seek(offset, 0) hash_func = self.get_hash_func() hash_func.update(stream.read(count)) return hash_func.digest() def compute_hash_from_file(self, file_desc, offset=0, count=-1): file_desc.seek(offset, 0) hash_func = self.get_hash_func() hash_func.update(file_desc.read(count)) return hash_func.digest() def check_length(self, digest_value): if len(digest_value) != self.__byte_length: raise Exception('A %s digest should contain %s bytes, but a value ' 'with %s bytes was given' % (self.__name, self.__byte_length, len(digest_value))) @property def api_model(self): return self.__api_model @property def name(self): return self.__name @property def oid(self): return self.__oid @property def byte_length(self): return self.__byte_length @property def xml_uri(self): return self.__xml_uri @abstractmethod def get_hash_func(self): pass class MD5DigestAlgorithm(DigestAlgorithm): def __init__(self): name = 'MD5' oid = Oids.MD5 byte_length = 16 api_model = DigestAlgorithms.MD5 xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#md5' super(MD5DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) def get_hash_func(self): return hashlib.md5() class SHA1DigestAlgorithm(DigestAlgorithm): def __init__(self): name = 'SHA-1' oid = Oids.SHA1 byte_length = 20 api_model = DigestAlgorithms.SHA1 xml_uri = 'http://www.w3.org/2000/09/xmldsig#sha1' super(SHA1DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) def get_hash_func(self): return hashlib.sha1() class SHA256DigestAlgorithm(DigestAlgorithm): def __init__(self): name = 'SHA-256' oid = Oids.SHA256 byte_length = 32 api_model = DigestAlgorithms.SHA256 xml_uri = 'http://www.w3.org/2001/04/xmlenc#sha256' super(SHA256DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) def get_hash_func(self): return hashlib.sha256() class SHA384DigestAlgorithm(DigestAlgorithm): def __init__(self): name = 'SHA-384' oid = Oids.SHA384 byte_length = 48 api_model = DigestAlgorithms.SHA384 xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#sha384' super(SHA384DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) def get_hash_func(self): return hashlib.sha384() class SHA512DigestAlgorithm(DigestAlgorithm): def __init__(self): name = 'SHA-512' oid = Oids.SHA512 byte_length = 64 api_model = DigestAlgorithms.SHA512 xml_uri = 'http://www.w3.org/2001/04/xmlenc#sha512' super(SHA512DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) def get_hash_func(self): return hashlib.sha512() class SHA3DigestAlgorithm(DigestAlgorithm): def __init__(self, bit_length): if bit_length == 256: name = 'SHA3-256' oid = Oids.SHA3_256 byte_length = bit_length / 8 api_model = DigestAlgorithms.SHA3_256 xml_uri = 'http://www.w3.org/2007/05/xmldsig-more#sha3-256' # https://tools.ietf.org/html/rfc6931#section-2.1.5 super(SHA3DigestAlgorithm, self)\ .__init__(name, oid, xml_uri, byte_length, api_model) else: raise Exception('Bit length not supported') self.__bit_length = bit_length def get_hash_func(self): return hashlib.sha3_256() DigestAlgorithm.MD5 = MD5DigestAlgorithm() DigestAlgorithm.SHA1 = SHA1DigestAlgorithm() DigestAlgorithm.SHA256 = SHA256DigestAlgorithm() DigestAlgorithm.SHA384 = SHA384DigestAlgorithm() DigestAlgorithm.SHA512 = SHA512DigestAlgorithm() DigestAlgorithm.SHA3_256 = SHA3DigestAlgorithm(256) __all__ = [ 'DigestAlgorithms', 'DigestAlgorithm', 'MD5DigestAlgorithm', 'SHA1DigestAlgorithm', 'SHA256DigestAlgorithm', 'SHA384DigestAlgorithm', 'SHA512DigestAlgorithm' ]
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/digest_algorithm.py
0.759493
0.20834
digest_algorithm.py
pypi
from .pki_brazil_certificate_fields import PkiBrazilCertificateFields from .pki_italy_certificate_fields import PkiItalyCertificateFields from .name import Name class PKCertificate(object): def __init__(self, model): self._email_address = model.get('emailAddress', None) self._serial_number = model.get('serialNumber', None) self._validity_start = model.get('validityStart', None) self._validity_end = model.get('validityEnd', None) self._subject_name = None self._issuer_name = None self._pki_brazil = None self._pki_italy = None self._issuer = None subject_name = model.get('subjectName', None) if subject_name is not None: self._subject_name = Name(subject_name) issuer_name = model.get('issuerName', None) if issuer_name is not None: self._issuer_name = Name(issuer_name) pki_brazil = model.get('pkiBrazil', None) if pki_brazil is not None: self._pki_brazil = PkiBrazilCertificateFields(pki_brazil) pki_italy = model.get('pkiItaly', None) if pki_italy is not None: self._pki_italy = PkiItalyCertificateFields(pki_italy) issuer = model.get('issuer', None) if issuer is not None: self._issuer = PKCertificate(issuer) @property def email_address(self): return self._email_address @email_address.setter def email_address(self, value): self._email_address = value @property def serial_number(self): return self._serial_number @serial_number.setter def serial_number(self, value): self._serial_number = value @property def validity_start(self): return self._validity_start @validity_start.setter def validity_start(self, value): self._validity_start = value @property def validity_end(self): return self._validity_end @validity_end.setter def validity_end(self, value): self._validity_end = value @property def subject_name(self): return self._subject_name @subject_name.setter def subject_name(self, value): self._subject_name = value @property def issuer_name(self): return self._issuer_name @issuer_name.setter def issuer_name(self, value): self._issuer_name = value @property def pki_brazil(self): return self._pki_brazil @pki_brazil.setter def pki_brazil(self, value): self._pki_brazil = value @property def pki_italy(self): return self._pki_italy @pki_italy.setter def pki_italy(self, value): self._pki_italy = value @property def issuer(self): return self._issuer @issuer.setter def issuer(self, value): self._issuer = value __all__ = ['PKCertificate']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/pk_certificate.py
0.677047
0.16398
pk_certificate.py
pypi
from abc import ABCMeta from abc import abstractmethod from .oids import Oids from .digest_algorithm import DigestAlgorithm class SignatureAlgorithms(object): MD5_WITH_RSA = 'MD5WithRSA' SHA1_WITH_RSA = 'SHA1WithRSA' SHA256_WITH_RSA = 'SHA256WithRSA' SHA384_WITH_RSA = 'SHA384WithRSA' SHA512_WITH_RSA = 'SHA512WithRSA' class SignatureAlgorithm(object): MD5_WITH_RSA = None SHA1_WITH_RSA = None SHA256_WITH_RSA = None SHA384_WITH_RSA = None SHA512_WITH_RSA = None def __init__(self, name, oid, xml_uri, digest_algorithm, pk_algorithm): self.__name = name self.__oid = oid self.__xml_uri = xml_uri self.__digest_algorithm = digest_algorithm self.__pk_algorithm = pk_algorithm def __eq__(self, instance): if instance is None: return False return self.__oid == instance.oid @staticmethod def _algorithms(): return [ SignatureAlgorithm.MD5_WITH_RSA, SignatureAlgorithm.SHA1_WITH_RSA, SignatureAlgorithm.SHA256_WITH_RSA, SignatureAlgorithm.SHA384_WITH_RSA, SignatureAlgorithm.SHA512_WITH_RSA ] @staticmethod def _safe_algorithms(): return [ SignatureAlgorithm.SHA1_WITH_RSA, SignatureAlgorithm.SHA256_WITH_RSA, SignatureAlgorithm.SHA384_WITH_RSA, SignatureAlgorithm.SHA512_WITH_RSA ] @staticmethod def get_instance_by_name(name): filtered_list = list(filter(lambda s: s.name == name, SignatureAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized signature algorithm name: %s' % name) return alg @staticmethod def get_instance_by_oid(oid): filtered_list = list(filter(lambda s: s.oid == oid, SignatureAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized signature algorithm oid: %s' % oid) return alg @staticmethod def get_instance_by_xml_uri(xml_uri): filtered_list = list(filter(lambda s: s.xml_uri == xml_uri, SignatureAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized signature algorithm XML URI: %s', xml_uri) return alg @staticmethod def get_instance_by_api_model(algorithm): if algorithm == SignatureAlgorithms.MD5_WITH_RSA: return SignatureAlgorithm.MD5_WITH_RSA elif algorithm == SignatureAlgorithms.SHA1_WITH_RSA: return SignatureAlgorithm.SHA1_WITH_RSA elif algorithm == SignatureAlgorithms.SHA256_WITH_RSA: return SignatureAlgorithm.SHA256_WITH_RSA elif algorithm == SignatureAlgorithms.SHA384_WITH_RSA: return SignatureAlgorithm.SHA384_WITH_RSA elif algorithm == SignatureAlgorithms.SHA512_WITH_RSA: return SignatureAlgorithm.SHA512_WITH_RSA else: raise Exception('Unsupported signature algorithm: %s' % algorithm) @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value @property def oid(self): return self.__oid @oid.setter def oid(self, value): self.__oid = value @property def xml_uri(self): return self.__xml_uri @xml_uri.setter def xml_uri(self, value): self.__xml_uri = value @property def digest_algorithm(self): return self.__digest_algorithm @digest_algorithm.setter def digest_algorithm(self, value): self.__digest_algorithm = value @property def pk_algorithm(self): return self.__pk_algorithm @pk_algorithm.setter def pk_algorithm(self, value): self.__pk_algorithm = value class PKAlgorithms(object): RSA = 'RSA' class PKAlgorithm(object): __metaclass__ = ABCMeta RSA = None def __init__(self, name, oid): self.__name = name self.__oid = oid def __eq__(self, instance): if instance is None: return False return self.__oid == instance.oid @staticmethod def _algorithms(): return [PKAlgorithm.RSA] @staticmethod def get_instance_by_name(name): filtered_list = list(filter(lambda p: p.name == name, PKAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized private key algorithm name: %s' % name) return alg @staticmethod def get_instance_by_oid(oid): filtered_list = list(filter(lambda p: p.oid == oid, PKAlgorithm._algorithms())) alg = filtered_list[0] if len(filtered_list) > 0 else None if alg is None: raise Exception('Unrecognized private key algorithm oid: %s' % oid) return alg @staticmethod def get_instance_api_model(algorithm): if algorithm is PKAlgorithms.RSA: return PKAlgorithm.RSA else: raise Exception('Unsupported private key algorithm: %s' % algorithm) @property def name(self): return self.__name @name.setter def name(self, value): self.__name = value @property def oid(self): return self.__oid @oid.setter def oid(self, value): self.__oid = value @abstractmethod def get_signature_algorithm(self, digest_algorithm): pass class RSASignatureAlgorithm(SignatureAlgorithm): def __init__(self, digest_algorithm): name = '%s with RSA' % digest_algorithm pk_algorithm = PKAlgorithm.RSA if digest_algorithm == DigestAlgorithm.MD5: xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#rsa-md5' oid = Oids.MD5_WITH_RSA elif digest_algorithm == DigestAlgorithm.SHA1: xml_uri = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1' oid = Oids.SHA1_WITH_RSA elif digest_algorithm == DigestAlgorithm.SHA256: xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256' oid = Oids.SHA256_WITH_RSA elif digest_algorithm == DigestAlgorithm.SHA384: xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha384' oid = Oids.SHA384_WITH_RSA elif digest_algorithm == DigestAlgorithm.SHA512: xml_uri = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha512' oid = Oids.SHA512_WITH_RSA else: raise Exception('Unsupported digest algorithms: %s' % digest_algorithm) super(RSASignatureAlgorithm, self).__init__(name, oid, xml_uri, digest_algorithm, pk_algorithm) SignatureAlgorithm.MD5_WITH_RSA = RSASignatureAlgorithm(DigestAlgorithm.MD5) SignatureAlgorithm.SHA1_WITH_RSA = RSASignatureAlgorithm(DigestAlgorithm.SHA1) SignatureAlgorithm.SHA256_WITH_RSA = \ RSASignatureAlgorithm(DigestAlgorithm.SHA256) SignatureAlgorithm.SHA384_WITH_RSA = \ RSASignatureAlgorithm(DigestAlgorithm.SHA384) SignatureAlgorithm.SHA512_WITH_RSA = \ RSASignatureAlgorithm(DigestAlgorithm.SHA512) class RSAPKAlgorithm(PKAlgorithm): def __init__(self): name = 'RSA' oid = Oids.RSA super(RSAPKAlgorithm, self).__init__(name, oid) def get_signature_algorithm(self, digest_algorithm): return RSASignatureAlgorithm(digest_algorithm) PKAlgorithm.RSA = RSAPKAlgorithm() __all__ = [ 'SignatureAlgorithms', 'SignatureAlgorithm', 'PKAlgorithms', 'PKAlgorithm', 'RSASignatureAlgorithm', 'RSAPKAlgorithm' ]
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/pk_algorithm.py
0.821116
0.178633
pk_algorithm.py
pypi
from datetime import datetime from .validation import ValidationResults from .digest_algorithm_and_value import DigestAlgorithmAndValue from .signature_algorithm_and_value import SignatureAlgorithmAndValue from .signature_policy_identifier import SignaturePolicyIdentifier from .pk_certificate import PKCertificate class CadesSignature(object): def __init__(self, model): self.__encapsulated_content_type = \ model.get('encapsulatedContentType', None) self.__has_encapsulated_content = \ model.get('hasEncapsulatedContent', None) self.__signers = [] signers = model.get('signers', None) if signers is not None: self.__signers = [CadesSignerInfo(s) for s in signers] @property def encapsulated_content_type(self): return self.__encapsulated_content_type @encapsulated_content_type.setter def encapsulated_content_type(self, value): self.__encapsulated_content_type = value @property def has_encapsulated_content(self): return self.__has_encapsulated_content @has_encapsulated_content.setter def has_encapsulated_content(self, value): self.__has_encapsulated_content = value @property def signers(self): return self.__signers @signers.setter def signers(self, value): self.__signers = value class CadesTimestamp(CadesSignature): def __init__(self, model): super(CadesTimestamp, self).__init__(model) self.__gen_time = model.get('genTime', None) self.__serial_number = model.get('serialNumber', None) self.__message_imprint = model.get('messageImprint', None) @property def gen_time(self): return self.__gen_time @gen_time.setter def gen_time(self, value): self.__gen_time = value @property def serial_number(self): return self.__serial_number @serial_number.setter def serial_number(self, value): self.__serial_number = value @property def message_imprint(self): return self.__message_imprint @message_imprint.setter def message_imprint(self, value): self.__message_imprint = value class CadesSignerInfo(object): def __init__(self, model): self.__certified_date_reference = \ model.get('certifiedDateReference', None) self.__signing_time = None signing_time = model.get('signingTime', None) if signing_time is not None: # Parse date string from ISO 8601 pattern. # Partial solution: # - Return a datetime without timezone information. # Reason: # - Python doesn't have a good support for parsing string with # timezone. s_time = signing_time[:-6] self.__signing_time = datetime.strptime(s_time, '%Y-%m-%dT%H:%M:%S') self.__message_digest = None message_digest = model.get('messageDigest', None) if message_digest is not None: self.__message_digest = DigestAlgorithmAndValue(message_digest) self.__signature = None signature = model.get('signature', None) if signature is not None: self.__signature = SignatureAlgorithmAndValue(signature) self.__certificate = None certificate = model.get('certificate', None) if certificate is not None: self.__certificate = PKCertificate(certificate) self.__signature_policy = None signature_policy = model.get('signaturePolicy', None) if signature_policy is not None: self.__signature_policy = \ SignaturePolicyIdentifier(signature_policy) self.__timestamps = [] timestamps = model.get('timestamps', None) if timestamps is not None: for timestamp in timestamps: self.__timestamps.append(CadesTimestamp(timestamp)) self.__validation_results = None validation_results = model.get('validationResults', None) if validation_results is not None: self.__validation_results = ValidationResults(validation_results) @property def signing_time(self): return self.__signing_time @signing_time.setter def signing_time(self, value): self.__signing_time = value @property def certified_date_reference(self): return self.__certified_date_reference @certified_date_reference.setter def certified_date_reference(self, value): self.__certified_date_reference = value @property def message_digest(self): return self.__message_digest @message_digest.setter def message_digest(self, value): self.__message_digest = value @property def signature(self): return self.__signature @signature.setter def signature(self, value): self.__signature = value @property def certificate(self): return self.__certificate @certificate.setter def certificate(self, value): self.__certificate = value @property def signature_policy(self): return self.__signature_policy @signature_policy.setter def signature_policy(self, value): self.__signature_policy = value @property def timestamps(self): return self.__timestamps @timestamps.setter def timestamps(self, value): self.__timestamps = value @property def validation_results(self): return self.__validation_results @validation_results.setter def validation_results(self, value): self.__validation_results = value __all__ = [ 'CadesSignature', 'CadesSignerInfo', 'CadesTimestamp' ]
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/cades_signature.py
0.853715
0.187281
cades_signature.py
pypi
class Name(object): def __init__(self, model): self._common_name = model.get('commonName', None) self._country = model.get('country', None) self._dn_qualifier = model.get('dnQualifier', None) self._email_address = model.get('emailAddress', None) self._generation_qualifier = model.get('generationQualifier', None) self._given_name = model.get('givenName', None) self._initials = model.get('initials', None) self._locality = model.get('locality', None) self._organization = model.get('organization', None) self._organization_unit = model.get('organizationUnit', None) self._pseudonym = model.get('pseudonym', None) self._serial_number = model.get('serialNumber', None) self._state_name = model.get('stateName', None) self._surname = model.get('surname', None) self._title = model.get('title', None) @property def common_name(self): return self._common_name @common_name.setter def common_name(self, value): self._common_name = value @property def country(self): return self._country @country.setter def country(self, value): self._country = value @property def dn_qualifier(self): return self._dn_qualifier @dn_qualifier.setter def dn_qualifier(self, value): self._dn_qualifier = value @property def email_address(self): return self._email_address @email_address.setter def email_address(self, value): self._email_address = value @property def generation_qualifier(self): return self._generation_qualifier @generation_qualifier.setter def generation_qualifier(self, value): self._generation_qualifier = value @property def given_name(self): return self._given_name @given_name.setter def given_name(self, value): self._given_name = value @property def initials(self): return self._initials @initials.setter def initials(self, value): self._initials = value @property def locality(self): return self._locality @locality.setter def locality(self, value): self._locality = value @property def organization(self): return self._organization @organization.setter def organization(self, value): self._organization = value @property def organization_unit(self): return self._organization_unit @organization_unit.setter def organization_unit(self, value): self._organization_unit = value @property def pseudonym(self): return self._pseudonym @pseudonym.setter def pseudonym(self, value): self._pseudonym = value @property def serial_number(self): return self._serial_number @serial_number.setter def serial_number(self, value): self._serial_number = value @property def state_name(self): return self._state_name @state_name.setter def state_name(self, value): self._state_name = value @property def surname(self): return self._surname @surname.setter def surname(self, value): self._surname = value @property def title(self): return self._title @title.setter def title(self, value): self._title = value __all__ = ['Name']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/name.py
0.781205
0.205376
name.py
pypi
from .apis import Apis from .rest_pki_client import _get_api_version from .file_reference import FileReference from .signature_starter import SignatureStarter from .signature_start_result import SignatureStartResult class PadesSignatureStarter(SignatureStarter): def __init__(self, client): super(PadesSignatureStarter, self).__init__(client) self.__bypass_marks_if_signed = True self.__pdf_marks = [] self.__pdf_to_sign = None self.__measurement_units = None self.__page_optimization = None self.__visual_representation = None self.__custom_signature_field_name = None self.__certification_level = None # region "pdf_to_sign" accessors @property def pdf_to_sign(self): return self.__get_pdf_to_sign() def __get_pdf_to_sign(self): return self.__pdf_to_sign.file_desc @pdf_to_sign.setter def pdf_to_sign(self, value): self.__set_pdf_to_sign(value) def __set_pdf_to_sign(self, value): if value is None: raise Exception('The provided "pdf_to_sign" is not valid') self.__pdf_to_sign = FileReference.from_file(value) # endregion # region "pdf_to_sign_path" accessors @property def pdf_to_sign_path(self): return self.__get_pdf_to_sign_path() def __get_pdf_to_sign_path(self): return self.__pdf_to_sign.path @pdf_to_sign_path.setter def pdf_to_sign_path(self, value): self.__set_pdf_to_sign_path(value) def __set_pdf_to_sign_path(self, value): if value is None: raise Exception('The provided "pdf_to_sign_path" is not valid') self.__pdf_to_sign = FileReference.from_path(value) def set_pdf_to_sign_from_path(self, path): self.__set_pdf_to_sign_path(path) def set_pdf_to_sign_path(self, path): self.set_pdf_to_sign_from_path(path) def set_pdf_to_sign(self, path): self.set_pdf_to_sign_path(path) # endregion # region "pdf_to_sign_content" accessors @property def pdf_to_sign_content(self): return self.__get_pdf_to_sign_content() def __get_pdf_to_sign_content(self): return self.__pdf_to_sign.content_raw @pdf_to_sign_content.setter def pdf_to_sign_content(self, value): self.__set_pdf_to_sign_content(value) def __set_pdf_to_sign_content(self, value): if value is None: raise Exception('The provided "pdf_to_sign_content" is not valid') self.__pdf_to_sign = FileReference.from_content_raw(value) def set_pdf_to_sign_from_content_raw(self, content_raw): self.__set_pdf_to_sign_content(content_raw) def set_pdf_to_sign_content(self, content_raw): self.set_pdf_to_sign_from_content_raw(content_raw) # endregion # region "pdf_to_sign_base64" accessors @property def pdf_to_sign_base64(self): return self.__get_pdf_to_sign_base64() def __get_pdf_to_sign_base64(self): return self.__pdf_to_sign.content_base64 @pdf_to_sign_base64.setter def pdf_to_sign_base64(self, value): self.__set_pdf_to_sign_base64(value) def __set_pdf_to_sign_base64(self, value): if value is None: raise Exception('The provided "pdf_to_sign_base64" is not valid') self.__pdf_to_sign = FileReference.from_content_base64(value) def set_pdf_to_sign_from_content_base64(self, content_base64): self.__set_pdf_to_sign_base64(content_base64) # endregion @property def bypass_marks_if_signed(self): return self.__bypass_marks_if_signed @bypass_marks_if_signed.setter def bypass_marks_if_signed(self, value): self.__bypass_marks_if_signed = value @property def pdf_marks(self): return self.__pdf_marks @pdf_marks.setter def pdf_marks(self, value): self.__pdf_marks = value def add_mark(self, value): if self.__pdf_marks is None: self.__pdf_marks = [] self.__pdf_marks.append(value) @property def measurement_units(self): return self.__measurement_units @measurement_units.setter def measurement_units(self, value): self.__measurement_units = value @property def page_optimization(self): return self.__page_optimization @page_optimization.setter def page_optimization(self, value): self.__page_optimization = value @property def visual_representation(self): return self.__visual_representation @visual_representation.setter def visual_representation(self, value): self.__visual_representation = value @property def custom_signature_field_name(self): return self.__custom_signature_field_name @custom_signature_field_name.setter def custom_signature_field_name(self, value): self.__custom_signature_field_name = value @property def certification_level(self): return self.__certification_level @certification_level.setter def certification_level(self, value): self.__certification_level = value def start(self): if self._signer_certificate is None: raise Exception('The certificate was not set') response = self.__start_common() return SignatureStartResult(response) def start_with_web_pki(self): response = self.__start_common() return SignatureStartResult(response) def start_with_webpki(self): return self.start_with_web_pki() def __start_common(self): if not self.__pdf_to_sign: raise Exception('The PDF to be signed was not set') if not self._signature_policy_id: raise Exception('The signature policy was not set') api_version = _get_api_version(self._client, Apis.START_PADES) if api_version == 1: return self.__start_common_v1() return self.__start_common_v2() def __start_common_v2(self): request = self.__get_start_common_request() request['pdfToSign'] = \ self.__pdf_to_sign.upload_or_reference(self._client) return self._client.post('Api/v2/PadesSignatures', request) def __start_common_v1(self): request = self.__get_start_common_request() request['pdfToSign'] = self.__pdf_to_sign.content_base64 return self._client.post('Api/PadesSignatures', request) def __get_start_common_request(self): return { 'certificate': self._signer_certificate, 'signaturePolicyId': self._signature_policy_id, 'securityContextId': self._security_context_id, 'ignoreRevocationStatusUnknown': self._ignore_revocation_status_unknown, 'callbackArgument': self._callback_argument, 'pdfMarks': [m.to_model() for m in self.__pdf_marks], 'bypassMarksIfSigned': self.__bypass_marks_if_signed, 'measurementUnits': self.__measurement_units, 'pageOptimization': self.__page_optimization.to_model() if self.__page_optimization is not None else None, 'visualRepresentation': self.__visual_representation, 'customSignatureFieldName': self.__custom_signature_field_name, 'certificationLevel': self.__certification_level } __all__ = ['PadesSignatureStarter']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/pades_signature_starter.py
0.673192
0.185559
pades_signature_starter.py
pypi
import re class PkiBrazilCertificateFields(object): def __init__(self, model): self._certificate_type = model.get('certificateType', None) self._cpf = model.get('cpf', None) self._cnpj = model.get('cnpj', None) self._responsavel = model.get('responsavel', None) self._company_name = model.get('companyName', None) self._oab_uf = model.get('oabUF', None) self._oab_numero = model.get('oabNumero', None) self._rg_numero = model.get('rgNumero', None) self._rg_emissor = model.get('rgEmissor', None) self._rg_emissor_uf = model.get('rgEmissorUF', None) self._date_of_birth = model.get('dateOfBirth', None) @property def certificate_type(self): return self._certificate_type @certificate_type.setter def certificate_type(self, value): self._certificate_type = value @property def cpf(self): return self._cpf @cpf.setter def cpf(self, value): self._cpf = value @property def cpf_formatted(self): if self._cpf is None: return '' if not re.match('^\d{11}$', self._cpf): return self._cpf return "%s.%s.%s-%s" % (self._cpf[:3], self._cpf[3:6], self._cpf[6:9], self._cpf[9:]) @property def cnpj(self): return self._cnpj @cnpj.setter def cnpj(self, value): self._cnpj = value @property def cnpj_formatted(self): if self._cnpj is None: return '' if not re.match('^\d{14}', self._cnpj): return self._cnpj return "%s.%s.%s/%s-%s" % (self._cnpj[:2], self._cnpj[2:5], self._cnpj[5:8], self._cnpj[8:12], self._cnpj[12:]) @property def responsavel(self): return self._responsavel @responsavel.setter def responsavel(self, value): self._responsavel = value @property def company_name(self): return self._company_name @company_name.setter def company_name(self, value): self._company_name = value @property def oab_uf(self): return self._oab_uf @oab_uf.setter def oab_uf(self, value): self._oab_uf = value @property def oab_numero(self): return self._oab_numero @oab_numero.setter def oab_numero(self, value): self._oab_numero = value @property def rg_numero(self): return self._rg_numero @rg_numero.setter def rg_numero(self, value): self._rg_numero = value @property def rg_emissor(self): return self._rg_emissor @rg_emissor.setter def rg_emissor(self, value): self._rg_emissor = value @property def rg_emissor_uf(self): return self._rg_emissor_uf @rg_emissor_uf.setter def rg_emissor_uf(self, value): self._rg_emissor_uf = value @property def date_of_birth(self): return self._date_of_birth @date_of_birth.setter def date_of_birth(self, value): self._date_of_birth = value __all__ = ['PkiBrazilCertificateFields']
/restpki-client-1.2.1.tar.gz/restpki-client-1.2.1/restpki_client/pki_brazil_certificate_fields.py
0.607197
0.175786
pki_brazil_certificate_fields.py
pypi
Introduction to restq ********************* Why restq? We wanted to have a simple platform independent solution for managing the coordination and distribution of batched execution across our analysis platforms. restq solved our wants into a system that could: * segregate execution based on a category or type (realm), * manage priorities of job execution (ordered queues), * enqueue, check-out, and expiry time based (almost FIFO) dequeuing of jobs from a realm. * status of jobs remaining against arbitrary tag indices. * zero configuration for the concepts talked about above. What's in restq: * An implementation of the execution management system described above. * A RESTful web API that exposes complete control over the execution management system. * A Python client that seamlessly interfaces the RESTful web API. * Default configuration configurable through environment variables or /etc/restq.conf, ~/.restq.conf * A command line interface accessible in the shell through the entry point 'restq'. The CLI makes it trivial to kick off a restq server. It also implements a set of commands which allow users to enqueue and dequeue commands into a realm. This makes it super trivial to deploy scheduled execution jobs across a pool of servers. For additional tips / tricks with this restq feel free to post a question at the github `restq/issues`_ page. Project hosting provided by `github.com`_. |pypi_version| |build_status| |coverage| [mjdorma+restq@gmail.com] Install and run =============== Simply run the following:: > python setup.py install or `PyPi`_:: > pip install restq Coding with restq ================= A simple example on how :: > restq web & > ipython In [1]: from restq import Realms In [2]: realms = Realms() In [3]: realms.test. realms.test.add realms.test.bulk_add realms.test.bulk_flush realms.test.get_job realms.test.get_tag_status realms.test.get_tagged_jobs realms.test.name realms.test.pull realms.test.remove_job realms.test.remove_tagged_jobs realms.test.request realms.test.requester realms.test.set_default_lease_time realms.test.set_queue_lease_time realms.test.status In [3]: realms.test.add('job 1', 0, 'do the dishes', tags=['house work']) In [4]: realms.test.add('job 2', 0, 'cut the grass', tags=['house work']) In [5]: realms.test.add('job 3', 1, 'fix bugs in restq', tags=['devel']) In [6]: realms.test.add('job 4', 3, 'document restq', tags=['devel']) In [7]: realms.test.add('job 5', 0, 'go for walk', tags=['sport']) In [8]: realms.test.status Out[8]: {u'queues': {u'0': 4, u'1': 1, u'2': 1, u'3': 1}, u'total_jobs': 7, u'total_tags': 3} In [9]: jobs = realms.test.pull(count=7) In [10]: jobs Out[10]: {u'job 1': [0, u'do the dishes'], u'job 2': [0, u'cut the grass'], u'job 3': [1, u'fix bugs in restq'], u'job 4': [3, u'document restq'], u'job 5': [0, u'go for walk'], u'job 6': [0, u'go for walk with dog'], u'job 7': [2, u'go for bike ride']} In [11]: realms.test.get_tag_status('house work') Out[11]: {u'count': 2} In [12]: realms.test.get_tagged_jobs('devel') Out[12]: {u'job 3': {u'data': u'fix bugs in restq', u'queues': [[1, 82.17003393173218]], u'tags': [u'devel']}, u'job 4': {u'data': u'document restq', u'queues': [[3, 82.16989994049072]], u'tags': [u'devel']}} Using restq's CLI ================= Adding arguments into the default realm --------------------------------------- Add the argument "ls -lah" into the default realm. :: > restq add "ls -lah" If we want to refer to a group of commands we can tag a command (even if it already exists). Tag the argument "ls -lah" with a label of 'work'. :: > restq add --tags=work "ls -lah" Add another argument to the realm, but this time we'll tag it with work and fun. :: > restq add --tags=work,fun pwd Checkout the status of the realm. :: > restq status Status of realm default: Contains 2 tags with 2 jobs Defined queues: 0 Time to add pwd to another queue. :: > restq add --queue=1 pwd > > restq status Status of realm default: Contains 2 tags with 2 jobs Defined queues: 1, 0 Pulling (or doing a checkout) of arguments for execution -------------------------------------------------------- Continuation from the previous example. Pull and execute a maximum of two arguments from the default realm. After the default time out, these arguments will be available for checkout once again. :: > while read i; do eval "$i"; done < <(restq pull --count=2) drwxr-xr-x 9 mick mick 4.0K Jul 18 08:01 . drwxrwxr-x 9 mick mick 4.0K Jul 14 03:07 .. drwxrwxr-x 3 mick mick 4.0K Jul 12 00:04 docs -rw-rw-r-- 1 mick mick 72 Jul 12 00:04 MANIFEST.in -rw-rw-r-- 1 mick mick 3.7K Jul 12 00:04 README.rst drwxrwxr-x 2 mick mick 4.0K Jul 17 23:13 restq -rw-rw-r-- 1 mick mick 2.1K Jul 17 19:57 setup.py drwxrwxr-x 2 mick mick 4.0K Jul 12 00:04 tests -rw-rw-r-- 1 mick mick 321 Jul 12 00:04 .travis.yml /home/mick/work/restq The argument pwd was placed into two queues. The next pull will see pwd being dequeued from queue 1. :: > restq pull pwd Lets check the status of the pwd argument since checkout. This shows what queues a specific argument is in, what tags it has, and how long it has been since it was checked out (pulled). :: > restq status arg pwd Status of argument pwd: Tagged with: work queue id | (s) since dequeue 1 | 35.22 0 | 454.49 Time to remove pwd from our realm... We're done with this argument and we no longer require it for execution. You will notice that the fun tag no longer exists in the realm as it was only attached to pwd. :: > restq remove arg pwd > The default lease time for a dequeue of an argument is 600s. After this expiry time, 'ls -lah' will once again be available for dequeue. :: > restq pull ls -lah How to distribute a shell script for execution ---------------------------------------------- Add 'work.sh' script into the default realm. :: > restq add --file=work.sh "chmod +x work.sh; ./work.sh" Now when this job is dequeued using the restq cli, the path './work.sh' will be written to using the data read from the original 'work.sh' and the arguments will be written out to stdout. :: > eval "`restq pull`" The following is an example of a script that could be deployed across multiple machines to continuously pull and execute jobs that have been added into the default realm. :: > while [ 1 ]; do > while read i; do eval "$i"; done < <(restq pull); > sleep 1; > done Issues ====== Source code for *restq* is hosted on `GitHub <https://github.com/provoke-vagueness/restq>`_. Please file `bug reports <https://github.com/provoke-vagueness/restq/issues>`_ with GitHub's issues system. Change log ========== version 0.1.2 (26/08/2013) * bulk add and removal version 0.1.0 (18/07/2013) * implemented cli controls. * realms now using yaml -> breaks compatibility with previous version. version 0.0.4 (09/06/2013) * config and cli shell implementation version 0.0.3 (06/06/2013) * bulk post & stable error handling version 0.0.1 (10/04/2013) * pre life Contributions ============= Contributions to restq: * [sptonkin@outlook.com] .. _github.com: https://github.com/provoke-vagueness/restq .. _PyPi: http://pypi.python.org/pypi/restq .. _restq/issues: https://github.com/provoke-vagueness/restq/issues .. |coverage| image:: https://coveralls.io/repos/provoke-vagueness/restq/badge.png?branch=master :target: https://coveralls.io/r/provoke-vagueness/restq?branch=master :alt: Latest PyPI version .. |pypi_version| image:: https://pypip.in/v/restq/badge.png :target: https://crate.io/packages/restq/ :alt: Latest PyPI version .. |build_status| image:: https://secure.travis-ci.org/provoke-vagueness/restq.png?branch=master :target: http://travis-ci.org/#!/provoke-vagueness/restq
/restq-0.1.2.tar.gz/restq-0.1.2/README.rst
0.76145
0.675149
README.rst
pypi
import re __version__ = '0.0.7' class NoMatch: """ No match class """ def __bool__(self): return False class TokenStream: """ Token stream class is a wrapper on a list which provides ge, peak and seek functions to get and set the head of a consumable list """ def __init__(self, token_stream: list): """ Init :param token_stream: list to be converted into a token-string """ self.token_stream = token_stream self.head = 0 def get(self) -> list: """ Returns and consumes the head of the stream :return: the head element """ if self.head == len(self.token_stream): return [None, None] self.head += 1 return self.token_stream[self.head - 1] def peak(self) -> list: """ Returns the head of the stream but does not consume it :return: the head element """ if self.head == len(self.token_stream): return [None, None] return self.token_stream[self.head] def seek(self, head) -> None: """ Sets the head to an index :param head: The index of the new head :return: None """ if head < 0 or head > len(self.token_stream): return self.head = head def to_list(self): """ Returns the original list :return: original list """ return self.token_stream[self.head:] def __str__(self): """ String representation of the token stream :return: string representation """ return str(self.token_stream[self.head:]) class Lex: """ This is the lex class, this provides lexical scanning functions """ def __init__(self, token_list: list, ignore_list: list, ignore_case: bool): """ Init :param token_list: List of tokens {list of lists(name, regex)} :param ignore_list: List of tokens to ignore string(name) :param ignore_case: True for ignore case else False """ if ignore_case: self.token_list = [(token_name, re.compile(token_rule, re.IGNORECASE)) for token_name, token_rule in token_list] else: self.token_list = [(token_name, re.compile(token_rule)) for token_name, token_rule in token_list] self.ignore_list = ignore_list def tokenize(self, text: str) -> TokenStream: """ Tokenize the input string and returns a tokens-stream :param text: :return: """ matched_tokens = [] while text: for token_name, token_rule in self.token_list: match = token_rule.match(text) if match: if token_name not in self.ignore_list: matched_tokens.append((token_name, match.group())) text = text[match.end():] break else: err_str = text.split("\n", 2)[0] raise AssertionError('Error at: {} ...'.format(err_str)) return TokenStream(matched_tokens) def tokenize_verbose(self, text: str) -> TokenStream: """ Tokenize the input string and returns a tokens-stream with verbose outputs This is meant to be used for debugging :param text: :return: """ matched_tokens = [] while text: for token_name, token_rule in self.token_list: match = token_rule.match(text) if match: print('Matched: {}'.format(match.group())) if token_name not in self.ignore_list: matched_tokens.append((token_name, match.group())) text = text[match.end():] break else: err_str = text.split("\n", 2)[0] raise AssertionError('Error at: {} ...'.format(err_str)) return TokenStream(matched_tokens) class Yacc: """ This is the yacc class, this provides parsing of a token-string based on a grammar """ def __init__(self, grammar: dict): """ Init :param grammar: Grammar for the syntax """ self.grammar = grammar def parse(self, tokens: TokenStream, lhs: str = 'start') -> object: """ Parses a token-string into a data structure :param tokens: Token-stream :param lhs: Current state :return: parsed data structure else False of syntax error """ productions = self.grammar[lhs] head = tokens.head for production in productions: args = [] rhs = production[:-1] func = production[-1] for symbol in rhs: res = NoMatch() if symbol not in self.grammar and symbol == tokens.peak()[0]: res = tokens.get()[1] elif symbol in self.grammar: res = self.parse(tokens, symbol) if not isinstance(res, NoMatch): args.append(res) else: tokens.seek(head) break else: return func(*args) return NoMatch() def parse_verbose(self, tokens: TokenStream, lhs: str = 'start') -> object: """ Parses a token-string into a data structure with verbose outputs This is meant to be used for debugging :param tokens: Token-stream :param lhs: Current state :return: parsed data structure else False of syntax error """ productions = self.grammar[lhs] head = tokens.head for production in productions: print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>') print(f'production: {lhs} -> {" ".join(production[:-1])}') args = [] rhs = production[:-1] func = production[-1] for symbol in rhs: print('------------------------------------------------------------') print(f'Symbol: {symbol} - Token: {tokens.peak()[0]}') res = NoMatch() if symbol not in self.grammar and symbol == tokens.peak()[0]: res = tokens.get()[1] print(f'Matched constant: {res}') elif symbol in self.grammar: print(f'Matched production: {symbol}') res = self.parse_verbose(tokens, symbol) if not isinstance(res, NoMatch): args.append(res) else: tokens.seek(head) break print('------------------------------------------------------------') else: print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') return func(*args) print('<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') return NoMatch()
/restream-0.0.7.tar.gz/restream-0.0.7/restream.py
0.706089
0.410047
restream.py
pypi
__all__ = ["_ProtectFiles", "_ProtectDirs", "_LockPerms", "_Silent", "ref"] from sys import modules as __modules from os import name as __name from site import main as _main if __name != 'nt': __import__("readline") import importlib _ProtectFiles, _ProtectDirs, _LockPerms, _Silent, __version__, __file__, __protectfiles, __silent, __oldopen = *range(4), "1.4.3", None, None, None, open __restrict = { "os": ["execl", "execle", "execlp", "execlpe", "execv", "execve", "execvp", "execvpe", "fork", "forkpty", "kill", "killpg", "plock", "popen", "posix_spawn", "posix_spawnp", "spawnl", "spawnle", "spawnlp", "spawnlpe", "spawnv", "spawnve", "spawnvp", "spawnvpe", "system"], "subprocess": ["Popen", "call", "check_call", "check_output", "getoutput", "getstatusoutput", "run"], "pathlib.Path": [], "shutil": [] } def ref(*args) -> None: """ # Usage ## Basic usage ```py __ref__() # no need to import anything ``` ## Additional options - _ProtectFiles The `_ProtectFiles` option allows you to prevent Python files from using `open` to overwrite files, and block functions like `os.remove` from deleting files. To use, replace the setup with: ```py __ref__(ref._ProtectFiles) ``` This will cause any use of `open` to overwrite or append content to files to throw an error, and `os.remove`,`os.unlink`, and a few others are deleted. - _ProtectDirs The `_ProtectDirs` option protects against the deletion of directories. To use, replace the setup with: ```py __ref__(ref._ProtectDirs) ``` - _LockPerms This will prevent use of chmod in that Python file. To use, replace the setup with: ```py __ref__(ref._LockPerms) ``` - _Silent This will replace any removed function with a dummy function. To use, replace the setup with: ```py __ref__(ref._Silent) ``` That way, you won't get an error when trying to use `os.system("echo \"doing something that harms your system...\"")` but nothing will happen """ global __protectfiles, __restrict, __silent protectfiles, protectdirs, lockperms, silent = map(lambda x: x in args, range(4)) __protectfiles, __silent = protectfiles, silent if protectfiles: __restrict["os"].extend(["remove", "unlink", "rename", "replace"]) __restrict["pathlib.Path"].append("unlink") __restrict["shutil"].append("move") if protectdirs: __restrict["os"].extend(["rmdir", "removedirs", "rename", "replace"]) __restrict["shutil"].extend(["rmtree", "move"]) __restrict["pathlib.Path"].append("rmdir") if lockperms: __restrict["os"].append("chmod") __restrict["pathlib.Path"].append("chmod") __modules['__main__'].__builtins__.__dict__['__import__'] = __import __modules['__main__'].__builtins__.__dict__['open'] = __open def __open(filename, mode="r", *args, **kwargs): if __protectfiles and ("w" in mode or "a" in mode): raise AttributeError() return __oldopen(filename, mode, *args, **kwargs) def __import(name, *args): try: M = importlib.__import__(name, *args) except AttributeError: return __import__ for mod in __restrict: if name == mod: for method in __restrict[mod]: try: if __silent: M.__dict__[method] = lambda *_:None else: del M.__dict__[method] except (AttributeError, KeyError): pass return M if __name__ != '__main__': __modules['__main__'].__builtins__.__dict__['__ref__'] = ref
/restricted-functions-1.4.3.tar.gz/restricted-functions-1.4.3/ref/__init__.py
0.494873
0.378172
__init__.py
pypi
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterator from typing import Union def iter_partition(n: int, max_len: Union[int, None] = None) -> Iterator[list[int]]: """Iteratate over partitions of n, optionally limited to max_len. :param n: integer to partition :param max_len: optional maximum length of partitions to yield, at least 1 :yield: partitions as lists of summands (smallest to largest) :return: yields partitions as lists of summands (smallest to largest) :raise ValueError: if max_len is less than 1 >>> list(iter_partitions(3)) [[1, 1, 1], [1, 2], [3]] If max_len is specified, the first partition of max_len will be [1] * (max_len - 1) + [n - max_len + 1] Partitions after this might be longer than max_len. For example, if n=7 and max_len=3, the first partition found with len==3 will be [1, 1, 5], but the next partition will be [1, 2, 2, 2]. So, skip to [1, 1, 5] then filter the remaining partitions. """ if n < 0: return if max_len is not None and max_len < 1: msg = f"max_len must be at least 1, not {max_len}" raise ValueError(msg) ps = [0] * (n + 1) if max_len is None or n < max_len: # standard asc yield from _accel_asc(ps, 1, n - 1) return # max_len < n, skip most of the larger partitions ps[: max_len - 1] = [1] * (max_len - 1) ps[max_len - 1] = n - max_len + 1 yield ps[:max_len] remaining_partitions = _accel_asc(ps, max_len - 1, n - max_len) yield from (x for x in remaining_partitions if len(x) <= max_len) def _accel_asc(ps: list[int], k: int, shortage: int) -> Iterator[list[int]]: """The fastest known way to generate integer partitions in Python. :param ps: list of summands :param k: index of largest summand :param shortage: sum of remaining summands :yield: integer partitions of n :return: None Found at https://jeromekelleher.net/generating-integer-partitions.html """ while k != 0: # increment value one step to the left x = ps[k - 1] + 1 k -= 1 # fill until the sum can be reached with [x, x] or [x, shortage] while 2 * x <= shortage: ps[k] = x shortage -= x k += 1 # add x, move shortage to the right k_plus_1 = k + 1 k_plus_2 = k + 2 while x <= shortage: ps[k] = x ps[k_plus_1] = shortage yield ps[:k_plus_2] x += 1 shortage -= 1 ps[k] = x + shortage shortage = x + shortage - 1 yield ps[:k_plus_1] __all__ = ["iter_partition"]
/restricted_partition-0.1.1.tar.gz/restricted_partition-0.1.1/restricted_partition/__init__.py
0.899667
0.526404
__init__.py
pypi
# restring Easy to use functional enrichment terms retriever and aggregator, designed for the wet biology researcher ## Overview ```restring``` works on user-supplied differentially expressed (DE) genes list, and **automatically pulls and aggregates functional enrichment data** from [STRING](https://string-db.org/). It returns, in table-friendly format, aggregated results from **analyses of multiple comparisons**. Results can readily be visualized via **highly customizable heat/clustermaps** and **bubble plots** to produce beautiful publication-grade pics. Plus, it's got a GUI! What KEGG pathway was found in which comparisons? What pvalues? What DE genes annotated in that pathway were shared in those comparisons? How can I simultaneously show results for all my experimental groups, for all terms, all at once? This can all be managed by ```restring```. --- **Check it out**! We have a paper out in Scientific Reports, with detailed step-by-step installation and usage protocols, and real use cases implemented and discussed: **reString: an open-source Python software to perform automatic functional enrichment retrieval, results aggregation and data visualization** *Stefano Manzini, Marco Busnelli, Alice Colombo, Franchi Elsa, Grossano Pasquale, Giulia Chiesa* PMID: [34873191](https://pubmed.ncbi.nlm.nih.gov/34873191/) PMCID: [PMC8648753](http://www.ncbi.nlm.nih.gov/pmc/articles/pmc8648753/) DOI: [10.1038/s41598-021-02528-0](https://doi.org/10.1038/s41598-021-02528-0) [![Download from Nature Publishing Group](https://github.com/Stemanz/liputils/raw/master/images/npg.png)](https://www.nature.com/articles/s41598-021-02528-0.pdf) [![Download from PubMed Central](https://github.com/Stemanz/liputils/raw/master/images/pmc.png)](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC8648753/pdf/41598_2021_Article_2528.pdf) --- ## Table of contents - [Use case](#use-case) - [Installation](#installation) - [Installation in depth](#installation-in-depth) - [Installation troubleshooting](#installation-troubleshooting) - [Procedure](#procedure) - [1 | Prepping the files](#1--prepping-the-files) - [2 | Set input files and choosing the output path](#2--set-input-files-and-output-path) - [3 | Running the analysis (with default settings)](#3--running-the-analysis-with-default-settings) - [Results tables](#results-tables) - [Summary tables](#summary-tables) - [4 | Visualizing the results](#4--visualizing-the-results) - [Clustermap/Heatmap](#clustermap) - [Clustermap customization options](#clustermap-options) - [Bubble plot](#bubble-plot) - [Bubble plot options](#bubble-plot-options) - [5 | Configuring the analysis](#5--configuring-the-analysis) - [Species](#species) - [DE genes settings](#de-genes-settings) - [Set background](#set-background) - [Clear background](#clear-background) - [Choosing a specific STRING version](#choosing-a-specific-string-version) - [Getting help](#need-help) - [Investigating an issue](#investigating-an-issue) - [Reporting a bug](#reporting-a-bug) - [Requesting a new feature](#requesting-a-new-feature) - [Known bugs](#known-bugs) - **restring as a Python module** - [1 | Download required files from STRING](#1--download-required-files-from-string) - [2 | Aggregating the results](#2--aggregating-the-results) - [3 | Visualizing the results with ```draw_clustermap()```](#3--visualizing-the-results-with-a-clustermap) - [4 | Polishing up: making the clutermap pop](#4--polishing-up) ## Use case Modern high-throughput -omic approaches generate huge lists of differentially expressed (DE) genes/proteins, which can in turn be used for functional enrichment studies. Manualy reviewing a large number of such analyses is time consuming, especially for experimental designs with more than a few groups. Let's consider this experimental setup: ![](https://github.com/Stemanz/restring/raw/main/images/Figure%201.jpg) This represents a fairly common experimental design, but manually inspecting functional enrichment results for such all possible combinations would require substantial effort. Let's take a look at how we can tackle this issue with ```restring```. Our sample experimental setup has **two treatments**, given at **two time points** to **three different sample types**. Let's assume those samples are cells of different genotypes, and we'd like to mainly investigate genotype comparisons. After quantifying gene expression by RNAseq, we have DE genes for every comparison. As in many experimental pipelines, each list of DE genes is investigated with functional enrichment tools, such as [String](https://string-db.org/). But every comparison generates one or more tables. ```restring``` makes it easy to generate summary reports from all of them, automatically. ![](https://github.com/Stemanz/restring/raw/main/images/Figure%202.jpg) --- ## Installation ```reString``` is a Python application, and requires Python to run. Please refer to Python's official page for installation: [https://www.python.org/](https://www.python.org/). Once you have Python up and running, installing ```reString``` is as simple as opening up a terminal window and typing: ```pip install restring``` Here's what the installation process looks like in the Mac: ```bash (restest) cln-169-032-dhcp:~ manz$ pip install restring Collecting restring Downloading https://files.pythonhosted.org/packages/58/4c/03f7f06a15619bd8b53ada077a2e4f9d7cd187d9e9857ab57b3239963744/restring-0.1.16.tar.gz (1.2MB) 100% |████████████████████████████████| 1.2MB 437kB/s Requirement already satisfied: matplotlib in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from restring) Requirement already satisfied: seaborn in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from restring) Requirement already satisfied: pandas in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from restring) Requirement already satisfied: requests in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from restring) Requirement already satisfied: numpy>=1.6 in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from matplotlib->restring) Requirement already satisfied: python-dateutil in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from matplotlib->restring) Requirement already satisfied: pytz in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from matplotlib->restring) Requirement already satisfied: cycler in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from matplotlib->restring) Requirement already satisfied: pyparsing!=2.0.4,>=1.5.6 in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from matplotlib->restring) Requirement already satisfied: six>=1.5 in /Applications/Anaconda3/anaconda/lib/python3.4/site-packages (from python-dateutil->matplotlib->restring) Building wheels for collected packages: restring Running setup.py bdist_wheel for restring ... done Stored in directory: /Users/manz/Library/Caches/pip/wheels/25/67/13/73711665f987ae891784bef729f350429599d2e3cda015a37a Successfully built restring Installing collected packages: restring Successfully installed restring-0.1.16 (restest) cln-169-032-dhcp:~ manz$ ``` To **run** restring, simply open a terminal and type: ```restring-gui``` This will launch ```reString``` in its GUI form. On Windows systems, the first time the antivirus might want to check ```restring-gui.exe```, but the application should launch without issues once it realizes there are no threats. This is what it looks like in MacOS: ![](https://github.com/Stemanz/restring/raw/main/images/restring_main_window.png) ### Installation in depth Here are step-by-step instructions on how to install ```reString``` on specific platforms in the form of YouTube videos. [Windows 10](https://www.youtube.com/watch?v=agIYg93ticI) [Mac OS](https://www.youtube.com/watch?v=7zRQrWpRi1E) [Ubuntu GNU/linux](https://www.youtube.com/watch?v=Lejia7_Zcp0) [Raspberry Pi OS](https://www.youtube.com/watch?v=RybteNoaWOI) In each video description, the commands that should be inputted in the terminal to perfect the installation process are handily summarized. This covers both checking/installing Python, eventual missing dependencies and ```restring``` itself. ### Installation troubleshooting If you experience hiccups during the installation, maybe we got you covered: - If you get ```SyntaxError``` after trying to run ```restring```: make sure you are using Python 3.x and **not** Python 2.x. Python 2.x is _obsolete_ and _discontinued_. Many systems still support both, in this case you use ```python``` and ```pip``` for Python 2.x and ```python3``` and ```pip3``` or Python 3.x. In this case, use ```pip3``` to install restring. - If you get ```SyntaxError``` and you are **sure** you're running Python 3.x: then you're running a version prior to 3.6. Update it. - If you get errors launching reString by typing ```restring-gui```: To the exception of MacOS, we noticed that the installation script is not placed in the ```Path```/```PATH``` environment variable _(that is: even if the script is in your computer, your computer doesn't know where to pull it from when you type it)_. If this happens, you have two alternatives: alternative a) start ```restring``` by typing ```python -c "import restring; restring.restring_gui()"``` or ```python3 -c "import restring; restring.restring_gui()"```. Use the first command if ```python``` is Python 3.x in your system, use ```python3``` if in your system the version 2.x is called instead. These commands are guaranteed to work from within any folder the terminal is in; alternative b) permanently teach your system where the launch script lies. You will know the location from the installation log [(refer to the YouTube videos)](#installation-in-depth). In GNU/linux systems, it's far easier to google for something like "how to permanently add a folder to PATH in YOUR_DISTRO_HERE". In Windows, follow the instructions of the [YouTube installation guide](https://www.youtube.com/watch?v=agIYg93ticI). When done, you will be able to launch restring by just typing: ```restring-gui``` - If you get weird errors: Get in touch with us: [report a bug](#reporting-a-bug). --- ## Procedure ```restring``` can be used via its graphical user interface (recommended). A full protocol, with sample data and examples, is detailed below. Alternatively, it can be imported as a Python module. This hands-on procedure is detailed at the end of this document. ## ```restring``` GUI ### 1 | Prepping the files All ```restring``` requires is a gene list of choice per experimental condition. This gene list needs to be in tabular form, arranged like this [sample data](https://github.com/Stemanz/restring/tree/main/sample_data). This is very easily managed with any spreadsheet editor, such as Microsoft's Excel or Libre Office's Calc. ### 2 | Set input files and output path In the menu, choose ```File > Open...```, or hit the ```Open files..``` button. Tip: put all input files you want to process together in one or more analyses in the same folder. Input files can be individually selected from any one folder, but each time input files are added, the input files list is reset. Then, choose an existing directory where all putput files will be placed: choose ```File > Set output folder``` or hit ```Set folder``` button _(Choose a different output folder each time the analysis parameters are varied, see section 5)_. ### 3 | Running the analysis with default settings In the menu, choose ```Analysis > New analysis```, or hit the ```New analysis``` button. ```restring``` will look for genes in the files you have specified, interrogate STRING to get functional enrichment data back _(these tables, looking exactly the same to the ones you would manually retrieve, will be saved into subfolders of the output folder)_, then write aggregated results and summaries. These are found in the specified output directory, and take the form of **results**- or **summary**-type tables, in ```.tsv``` _(tab separated values)_ format, that can be opened out-of-the-box by Excel or Calc. Let's take a look at the anatomy of these tables. ### Results tables ![](https://github.com/Stemanz/restring/raw/main/images/Figure%203.png) The table contains all terms cumulatively retrieved from all comparisons _(each one of the inpt files containing the genes of interest between any two experimental conditions)_. For every term, common genes (if any) are listed. These common genes only include comparisons where the term actually shows up. If the term just appears in exactly one comparison, this is explicitly stated: ```n/a (just one condition)```. P-values are the ones retrieved from the STRING tables _(the lower, the better)_. Missing p-values are represented with ```1``` _(that is, in that specific comparison the term is 100% likely not enriched)_. ### Summary tables ![](https://github.com/Stemanz/restring/raw/main/images/Figure%204.png) These can be useful to find the most interesting terms across all comparisons: better p-value, presence in most/selected comparisons), as well as finding the most recurring DE genes for each term. ### 4 | Visualizing the results #### Clustermap ```restring``` makes it easy to inspect the results by visualizing **results**-type tables as clustermaps. In the menu, choose ```Analysis > Draw clustermap``` to open the Draw clustermap window: ![](https://github.com/Stemanz/restring/raw/main/images/draw_clustermap_window.png) #### Clustermap Options **readable**: if flagged, the output clustermap will be drawn as tall as required to fully display all the terms contained in it. Be warned that this might get very tall, depending on the number of terms. **log transform**: if flagged, the p-values are minus log-transformed with the specified base: -log(number, base chosen). Hit ```Apply``` to apply. **cluster rows**: if flagged, the rows are clustered (by distance) as per Scipy [defaults](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist). The column order is overridden. **cluster columns**: if flagged, the columns are clustered (by distance) as per Scipy [defaults](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html#scipy.spatial.distance.pdist). **P-value cutoff**: For each term _(row)_, if all values are higher than the specified threshold, the term is not included in the clustermap. For log-transformed heatmaps, for each term _(row)_, if all values are lower than the specified threshold, the term is not included in the clustermap. Insert a new value and hit ```Apply``` to see how many terms are retained/discarded by the new threshold. Note that the default value of ```1``` will include all terms of a non-transformed table, as all terms are necessarily 1 or lower _(moreover, there should automatically be at least a term per row that was significant, at P=0.05, in the files retrieved from STRING, otherwise the term would not appear in the table in the first place)_. To set a new threshold, for instance at P=0.001, one should input ```0.001```, or ```3``` when log-transforming in base 10. Always hit ```Apply```. **Log base**: choose the base for the logarithm. **DPI**: choose the output image resolution in DPI _(dot per inch)_. The higher, the larger the image. **Apply**: Applies the current settings to the table, and shows how the settings impact on the table. **Choose terms..**: This button opens a dialog to choose the terms. An example: ![](https://github.com/Stemanz/restring/raw/main/images/choose_terms.png) In this example, the results table contains terms that are irrelevant in the analysis being made. When loading a new table, all terms are automatically included, but the user chan choose to untick the terms that are unwanted. If a new **P-value cutoff** is applied, ```restring``` remembers the user choice even if some of the terms are now removed from the term list and are added back to the table at a later time. Hit ```Apply & OK``` to apply the choice and close the window. **Choose col order**: The user can reorder the column order by dragging the column names. Multiple adjacent columns can be selected and dragged together _(this is ineffective if_ **Cluster rows** _is flagged)_. Hit ```OK``` to apply and close the window. **Draw clustermap**: Draws, saves and opens the clustermap. **Reset**: Reloads the input table and clears term selection. **Help**: Opens a dialog that briefly outlines the procedure. **Online Manual**: Opens the default browser at the clustermap help section. **Close**: Closes the window. #### Bubble plot ```restring``` makes it easy to inspect the results by visualizing **summary**-type tables as bubble plots. In the menu, choose ```Analysis > Draw bubble plot``` to open the Draw bubble plot window: ![](https://github.com/Stemanz/restring/raw/main/images/bubble_plot_dialog.png) The bubble plot emphasizes the information gathered in summary-type tables, drawing, for each selected term, a bubble whose color and size reflect the FDR (color) and number of genes shared between all experimental conditions for each term (size). Here is an example: ![](https://github.com/Stemanz/restring/raw/main/images/bubble_plot_example.png) #### Bubble plot options **log transform**: if flagged, the p-values are minus log-transformed with the specified base: -log(number, base chosen). Hit ```Apply``` to apply. **P-value cutoff**: For each term _(row)_, if all values are higher than the specified threshold, the term is not included in the clustermap. For log-transformed heatmaps, for each term _(row)_, if all values are lower than the specified threshold, the term is not included in the clustermap. Insert a new value and hit ```Apply``` to see how many terms are retained/discarded by the new threshold. Note that the default value of ```1``` will include all terms of a non-transformed table, as all terms are necessarily 1 or lower _(moreover, there should automatically be at least a term per row that was significant, at P=0.05, in the files retrieved from STRING, otherwise the term would not appear in the table in the first place)_. To set a new threshold, for instance at P=0.001, one should input ```0.001```, or ```3``` when log-transforming in base 10. Always hit ```Apply```. **Log base**: choose the base for the logarithm. **DPI**: choose the output image resolution in DPI _(dot per inch)_. The higher, the larger the image. **terms height**: differently from the heatmap, bubble plots are always drawn such as all terms that survived the FDR cutoff and User selection are always readable. This parameter specifies how much distant (vertically) each term should be drawn in the resulting bubble plot. Defaults to ```0.25```. **Apply**: Applies the current settings to the table, and shows how the settings impact on the table. **Choose terms..**: This button opens a dialog to choose the terms. An example: ![](https://github.com/Stemanz/restring/raw/main/images/choose_terms.png) In this example, the results table contains terms that are irrelevant in the analysis being made. When loading a new table, all terms are automatically included, but the user chan choose to untick the terms that are unwanted. If a new **P-value cutoff** is applied, ```restring``` remembers the user choice even if some of the terms are now removed from the term list and are added back to the table at a later time. Hit ```Apply & OK``` to apply the choice and close the window. **Draw bubble plot**: Draws, saves and opens the bubble plot. **Reset**: Reloads the input table and clears term selection. **Help**: Opens a dialog that briefly outlines the procedure. **Online Manual**: Opens the default browser at the bubble plot help section. **Close**: Closes the window. ### 5 | Configuring the analysis. #### Species ```restring``` defaults to _Mus musculus_. To choose another species, choose ```Analysis > Set species``` to open the dialog: ![](https://github.com/Stemanz/restring/raw/main/images/set_species.png) STRING accepts species in the form of taxonomy IDs. Hit the button of your species of choice or supply a custom TaxID and hit ```Set```. Head over to STRING's [doc](https://string-db.org/cgi/help) to know if your species is supported. #### DE genes settings ```restring``` accepts as gene lists input something like this [sample data](https://github.com/Stemanz/restring/tree/main/sample_data). The input contains information of the gene name _(we developed_ ```restring``` _having the_ official gene name _in mind as the preferred gene identifier, as that's always the case among researchers in our experience)_ and information about the _direction_ of the change of expression with respect to experimental groups. This is the implied convention: ``` gene ID | cond1 | cond2 | cond1_vs_cond2 | log2FC | ---------|---------------------------------------------| gene1 | 143 | 748 | 0.191 | -2.38 | ---------|---------------------------------------------| gene2 | 50 | 4 | 12.5 | 3.64 | ``` In this example, ```cond1``` and ```cond2``` are the two experimental condition where the abundance of the transcript has been estimated. Every RNAseq analysis contains at least the log2FC _(base 2, log-transformed ratio of the expression values)_, that tells if the gene is upregulated or downregulated. ```restring``` follows this convention: **UP** is upregulated in ```cond1``` versus ```cond2```. That's the case of ```gene2```. ```Log2FC``` is > 0. **DOWN** is downregulated in ```cond1``` versus ```cond2```. That's the case of ```gene1```. ```Log2FC``` is < 0. ```restring``` does not actually care about the magnitude of ```Log2FC```: that's from the pre-processing of the genes that the researcher is interested in. Depending on how to treat the _directionality_ information, there are four types of different analyses: ![](https://github.com/Stemanz/restring/raw/main/images/analysis_settings.png) **Upregulated genes only**: Functional enrichment info is searched for upregulated genes only. Enrichment is performed on upregulated genes only _(Arrange the input data so as "upregulated" in your experiment matches the implied convention)_. **Downregulated genes only**: Functional enrichment info is searched for downregulated genes only. Enrichment is performed on downregulated genes only _(Arrange the input data so as "downregulated" in your experiment matches the implied convention)_. **Upregulated and Downregulated, separately**: This is the **default** option. For every comparison, both upregulated and downregulated genes are considered, but separately. This means that functional enrichment info is retrieved for upregulated and downregulated genes separately, but the terms are aggregated from both. If a term shows up in both UP and DOWN gene lists, then the lowest P-value one is recorded. **All genes together**: Functional enrichment info is searched for all genes together, and the resulting aggregation will reflect the functional enrichment analysis retrieved with all genes together _(still supply a gene list that has a number, for each gene ID, in the second column. Just write any number.)_ **_Tip_**: To avoid accumulating STRING files, consider setting a different output folder any time the analysis parameters are varied. Notwithstanding, ```restring``` clearly labels what enrichment files come from which gene lists: ```UP```, ```DOWN``` or ```ALL``` are prepended to each table retrieved from STRING. #### Set background In the words of [Szklarczyk _et al._ 2021's paper](https://academic.oup.com/nar/article/49/D1/D605/6006194): > An increasing number of STRING users enter the database not with a single protein as their query, but with a set of proteins. [..] STRING will perform automated pathway-enrichment analysis on the user's input and list any pathways or functional subsystems that are observed more frequently than expected (using hypergeometric testing, against a statistical background of either the entire genome or a user-supplied background gene list). By default, ```reString``` requests functional enrichment data against the statistical background of the entire genome. This is specified in the textual output during the anaysis: > Running the analysis against a statistical background of the entire genome (default). Otherwise, it is possible to specify a background that will be applied to all input files, via ```Analysis > Custom background```. You will be prompted to open a ```.csv```, ```.tsv```, ```.xls```, ```.xlsx``` file that need to be a headerless, one-column file containing your custom background entries. Alternatively, you can place one entry per line in a ```.txt``` file. During the analysis, this will be specified as follows in the textual output: > Running the analysis against a statistical background of user-supplied terms. #### Clear Background To clear (empty) the custom background and revert to the default background (the entire genome), choose ```Analysis > Clear custom background```. A message will confirm that the background has been cleared. #### Choosing a specific STRING version In the menu, choose ```Analysis > Choose STRING version``` to open the following dialog: ![](https://github.com/Stemanz/restring/raw/main/images/string_versions.png) ```reString``` is compatible with the output produced from STRING API version 11.0 and above. To get info about past and current STRING releases, see [here](https://string-db.org/cgi/access) or hit ```Info about STRING versions``` in the window. ```reString``` always defaults to the lastest release, but for compatibility purposes other versions (11.0b or 11.0) can be selected. ### Need help? #### Investigating an issue Please [let us know if you have any issue](https://github.com/Stemanz/restring/issues). From installation, to usage, to unforeseen application hiccups, there is a form to request assistance. Just hit ```New issue``` to start a new request. Files can be drag-and-dropped into the form as well, and your request can be previewed before being finalized. To help up pin down the issue, please always include details about your machine setup (CPU, RAM, GPU, vendor) as well as your Python, OS and ```restring``` version. To further help investigating the matter, you should also include a procedure to allow us to replicate the issue in order to fix it (if possible, also include your input files). If you've been encountering an issue, chances are that some other people have already stumbled over the same problem, and the answer might already be around in the [Issues](https://github.com/Stemanz/restring/issues) section. #### Reporting a bug Most of the time, ```restring``` communicates what it's doing by printing messages in the application window(s). In rare circumstances, errors are printed only to the **terminal window** _(the one you've launched_ ```restring-gui``` _from, and that's still around)_: ![](https://github.com/Stemanz/restring/raw/main/images/bug_reporting.png) In addition to all information needed to investigate an issue (see above section), please include all **terminal output** (copy-and-paste the text, or drop a screenshot) in your bug report. Help us improve ```restring``` and report any bug [here](https://github.com/Stemanz/restring/issues). #### Requesting a new feature If you feel like ```restring``` should be including some new awesome feature, please [let us know](https://github.com/Stemanz/restring/issues)! We are aimed at making ```restring``` richer and more user-friendly. ### Known bugs - The repository of the ARM version of Raspberry Pi OS is sometimes having problems with keeping binaries up to date or working properly, and some of them might be required by ```restring```. If you experience installation troubles with that distribution, wait for the developers to get all packages up to date. - When drawing a heatmap or a clustermap, if you load the wrong table type (e.g. a "results"-type table instead of a "summary"-type table, ```restring``` will complain but it will output some weird error to the terminal. Always keep an eye on what's going on in the terminal, as explained [here](https://github.com/Stemanz/restring#reporting-a-bug). This will be fixed in the upcoming releases. --- ## ```restring``` as a Python module ### 1 | Download required files from STRING Head over to [String](https://string-db.org/), and analyze your gene/protein list. Please refer to the [String documentation](https://string-db.org/cgi/help) for help. After running the analysis, hit the ![](https://github.com/Stemanz/restring/raw/main/images/analysis.png) button at the bottom of the page. This allows to download the results as tab delimited text files. ![](https://github.com/Stemanz/restring/raw/main/images/export_supported.png) ```restring``` is designed to work with the results types highlighted in green. For each one of your experimental settings, create a folder with a name that will serve as a label for it. Here's how our [sample data](https://github.com/Stemanz/restring/tree/main/sample_tables) is arranged: ![](https://github.com/Stemanz/restring/raw/main/images/files.png) Not all comparisons resulted in a DE gene list that's long enough to generate functional enrichment results (see image above), thus a few comparisons _(folders)_ are missing. When the DE gene list was sufficiently long to generate results for all analyses, this is what the folder content looks like _(example of one folder)_: ![](https://github.com/Stemanz/restring/raw/main/images/folder_content.png) For each enrichment (```KEGG```, ```Component```, ```Function```, ```Process``` and ```RCTM```), we fed String with DE genes that were either up- or downregulated with respect of one of the genotypes of the analysis. ```restring``` **makes use** of the ```UP``` and ```DOWN``` labels in the filenames to know what direction the analysis went _(it's possible to aggregate_ ```UP``` _and_ ```DOWN``` _DE genes together)_. It's OK to have folders that don't contain all files (if there were insufficient DE genes to produce some), like in the folder ```ctrl_t0_green_VS_ctrl_t0_blue_FC``` that you will find in your output directory after the analysis has finished. ### 2 | Aggregating the results Once everything is set up, we can run ```restring``` to aggregate info from all the sparse results. The following example makes use of the String results that can be found in [sample output](https://github.com/Stemanz/restring/tree/main/sample_output). ```python import restring dirs = restring.get_dirs() print(dirs) ``` ```python ['ctrl_t0_green_VS_ctrl_t0_blue_FC', 'ctrl_t0_green_VS_ctrl_t0_red_FC', 'ctrl_t0_red_VS_ctrl_t0_blue_FC', 'ctrl_t1_green_VS_ctrl_t1_blue_FC', 'ctrl_t1_green_VS_ctrl_t1_red_FC', 'ctrl_t1_red_VS_ctrl_t1_blue_FC', 'treatment_t0_green_VS_treatment_t0_blue_FC', 'treatment_t0_green_VS_treatment_t0_red_FC', 'treatment_t0_red_VS_treatment_t0_blue_FC', 'treatment_t1_green_VS_treatment_t1_blue_FC', 'treatment_t1_green_VS_treatment_t1_red_FC', 'treatment_t1_red_VS_treatment_t1_blue_FC'] ``` ```get_dirs()``` returns a ```list``` of all folders within the current directory, to the excepion of folders beginning with ```__``` or ```.```. We can start aggregating results with default parameters (```KEGG``` pathways for both ```UP``` and ```DOWN``` regulated genes). ```python db = restring.aggregate_results(dirs) ``` ```python Start walking the directory structure. Parameters ---------- folders: 12 kind=KEGG directions=['UP', 'DOWN'] Processing directory: ctrl_t0_green_VS_ctrl_t0_blue_FC Processing directory: ctrl_t0_green_VS_ctrl_t0_red_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: ctrl_t0_red_VS_ctrl_t0_blue_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: ctrl_t1_green_VS_ctrl_t1_blue_FC Processing directory: ctrl_t1_green_VS_ctrl_t1_red_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: ctrl_t1_red_VS_ctrl_t1_blue_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: treatment_t0_green_VS_treatment_t0_blue_FC Processing directory: treatment_t0_green_VS_treatment_t0_red_FC Processing file UP_enrichment.KEGG.tsv Processing directory: treatment_t0_red_VS_treatment_t0_blue_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: treatment_t1_green_VS_treatment_t1_blue_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: treatment_t1_green_VS_treatment_t1_red_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processing directory: treatment_t1_red_VS_treatment_t1_blue_FC Processing file DOWN_enrichment.KEGG.tsv Processing file UP_enrichment.KEGG.tsv Processed 12 directories and 17 files. Found a total of 165 KEGG elements. ``` Tip: you must start working in the same directory where you start ```restring```, as it memorizes the starting directory at startup and would otherwise complain that it can longer locate the folders. tl;dr: don't play around with ```os.chdir()```, get to the folder containing the output folders from the start. Running ```aggregate_results()``` with other parameters is possible: ```python help(restring.aggregate_results) ``` ``` # truncated output Walks the given <directories> list, and reads the String .tsv files of defined <kind>. Params: ======= directories: <list> of directories where to look for String files kind: <str> Defines the String filetype to process. Kinds defined in settings.file_types directions: <list> contaning the up- or down-regulated genes in a comparison. Info is retrieved from either UP and/or DOWN lists. * Prerequisite *: generating files form String with UP and/or DOWN regulated genes separately. verbose: <bool>; turns verbose mode on or off ``` The ```kind``` parameter is picked from the 5 supported String result tables: ```python print(restring.settings.file_types) ``` ```python ('Component', 'Function', 'KEGG', 'Process', 'RCTM') ``` To manipulate the aggregated results, it's convenient to put them into a table: ``` df = restring.tableize_aggregated(db) ``` This functions wraps the results into a handy ```pandas.DataFrame``` object, that can be saved as a table for further inspection: ``` df.to_csv("results.csv") ``` ![](https://github.com/Stemanz/restring/raw/main/images/Figure%203.png) The table contains all terms cumulatively retrieved from all comparisons _(directories/columns)_. For every term, common genes (if any) are listed. These common genes only include comparisons where the term actually shows up. If the term just appears in exactly one comparison, this is explicitly stated: ```n/a (just one condition)```. P-values are the ones retrieved from the String tables _(the lower, the better)_. Missing p-values are represented with ```1``` (this can be set to anything ```str()``` accepts when calling ```tableize_aggregated()``` with the ```not_found``` parameter). These 'aggregated' tables are useful for charting the results (see later). There's other info that can be extracted form aggregated results, in the form of a 'summary' table: ```python res = restring.summary(db) res.to_csv("summary.csv") ``` ![](https://github.com/Stemanz/restring/raw/main/images/Figure%204.png) These can be useful to find the most interesting terms across all comparisons: better p-value, presence in most/selected comparisons), as well as finding the most recurring DE genes for each term. ### 3 | Visualizing the results with a clustermap 'aggregated'-type tables can be readily transformed into beautiful clustermaps. This is simply done by passing either the ```df``` object previolsly created with ```tableize_aggregated()```, or the file name of the table that was saved from that object to the ```draw_clustermap()``` function: ```python clus = restring.draw_clustermap("results.csv") ``` ![](https://github.com/Stemanz/restring/raw/main/images/clus_1.png) _(The output may vary depending on your version of plotting libraries)_ Note that ```draw_clustermap()``` actually _returns_ the ```seaborn.matrix.ClusterGrid``` object that it generates internally, this might come handy to retrieve the reordered (clustered) elements (more on that later). The drawing function is basically a wrapper for [```seaborn.clustermap()```](https://seaborn.pydata.org/generated/seaborn.clustermap.html), of which retains all the flexible customization options, but allows for an immediate tweaking of the picture. For instance, we might just want to plot the highest-ranking terms and have all of them clearly written on a readable heatmap: ```python clus = restring.draw_clustermap("results.csv", pval_min=6, readable=True) ``` ![](https://github.com/Stemanz/restring/raw/main/images/clus_2.png) ### 4 | Polishing up More tweaking is possibile: ```python help(restring.draw_clustermap) ``` ``` Help on function draw_clustermap in module restring.restring: draw_clustermap(data, figsize=None, sort_values=None, log_transform=True, log_base=10, log_na=0, pval_min=None, custom_index=None, custom_cols=None, unwanted_terms=None, title=None, title_size=24, savefig=False, outfile_name='aggregated results.png', dpi=300, readable=False, return_table=False, **kwargs) Draws a clustermap of an 'aggregated'-type table. This functions expects this table layout (example): terms │ exp. cond 1 | exp. cond 2 | exp cond n .. ──────┼─────────────┼─────────────┼────────────.. term 1│ 0.01 | 1 | 0.00023 ------┼-------------┼-------------┼------------.. term 2│ 1 | 0.05 | 1 ------┼-------------┼-------------┼------------.. .. │ .. | .. | .. *terms* must be indices of the table. If present, 'common' column will be ignored. Params ------ data A <pandas.DataFrame object>, or a filename. If a filename is given, this will try to load the table as if it were produced by tableize_aggregated() and saved with pandas.DataFrame.to_csv() as a .csv file, with ',' as separator. sort_values A <str> or <list> of <str>. Sorts the table accordingly. Please *also* set col_cluster=False (see below, seaborn.clustermap() additional parameters), otherwise columns will still be clustered. log_transform If True, values will be log-transformed. Defaults to True. note: values are turned into -log values, thus p-value of 0.05 gets transformed into 1.3 (with default parameters), as 10^-1.3 ~ 0.05 log_base If log_transform, this base will be used as the logarithm base. Defaults to 10 log_na When unable to compute the logarithm, this value will be used instead. Defaults to 0 (10^0 == 1) pval_min Trims values to the ones matching *at least* this p value. If log_transform with default values, this needs to be set accordingly For example, if at least p=0.01 is desired, then aim for pval_min=2 (10^-2 == 0.01) custom_cols It is possible to pass a <list> of <str> to draw only specified columns of input table custom_index It is possible to pass a <list> of <str> to draw only specified rows of input table unwanted_terms If a <list> of <str> is supplied, readable If set to False (default), the generated heatmap will be of reasonable size, possibly not showing all term descriptors. Setting readable=True will result into a heatmap where all descriptors are visible (this might result into a very tall heatmap) savefig If True, a picture of the heatmap will be saved in the current directory. outfile_name The file name of the picture saved. dpi dpi resolution of saved picture. Defaults to 300. return_table If set to True, it also returns the table that was manipulated internally to draw the heatmap (with all modifications applied). Returns: <seaborn.matrix.ClusterGrid>, <pandas.core.frame.DataFrame> **kwargs The drawing is performed by seaborn.clustermap(). All additional keyword arguments are passed directly to it, so that the final picture can be precisely tuned. More at: https://seaborn.pydata.org/generated/seaborn.clustermap.html ``` With a few brush strokes we can obtain the picture we're looking for. Example: ```python bad = [ "Alzheimer's disease", "Huntington's disease", "Parkinson's disease", "Retrograde endocannabinoid signaling", "Staphylococcus aureus infection", "Tuberculosis", "Leishmaniasis", "Herpes simplex infection", "Kaposi's sarcoma-associated herpesvirus infection", "Proteoglycans in cancer", "Pertussis", "Malaria", "I'm not in the index" ] clus = restring.draw_clustermap( "results.csv", pval_min=8, title="Freakin' good results", unwanted_terms=bad, sort_values="treatment_t1_wt_vs_DKO", row_cluster=False, annot=True, ) ``` ![](https://github.com/Stemanz/restring/raw/main/images/clus_3.png)
/restring-0.1.20.tar.gz/restring-0.1.20/README.md
0.618089
0.93646
README.md
pypi
from __future__ import absolute_import import io from docutils import utils from docutils.core import Publisher from docutils.nodes import Element def lint(content, filepath=None, rst_prolog=None): """Lint reStructuredText and return errors :param string content: reStructuredText to be linted :param string filepath: Optional path to file, this will be returned as the source :param string rst_prolog: Optional content to prepend to content, line numbers will be offset to ignore this :rtype list: List of errors. Each error will contain a line, source (filepath), message (error message), and full message (error message + source lines) """ # Generate a new parser (copying `rst2html.py` flow) # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/tools/rst2html.py # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/core.py#l348 pub = Publisher(None, None, None, settings=None) pub.set_components('standalone', 'restructuredtext', 'pseudoxml') # Configure publisher # DEV: We cannot use `process_command_line` since it processes `sys.argv` which is for `rst-lint`, not `docutils` # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/core.py#l201 # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/core.py#l143 # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/core.py#l118 settings = pub.get_settings(halt_level=5) pub.set_io() # Prepare a document to parse on # DEV: We avoid the `read` method because when `source` is `None`, it attempts to read from `stdin`. # However, we already know our content. # DEV: We create our document without `parse` because we need to attach observer's before parsing # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/readers/__init__.py#l66 reader = pub.reader document = utils.new_document(filepath, settings) # Disable stdout # TODO: Find a more proper way to do this # TODO: We might exit the program if a certain error level is reached document.reporter.stream = None # Collect errors via an observer errors = [] # If we have an RST prolog, then prepend it and calculate its offset rst_prolog_line_offset = 0 if rst_prolog: content = rst_prolog + '\n' + content rst_prolog_line_offset = rst_prolog.count('\n') + 1 def error_collector(data): # Mutate the data since it was just generated # DEV: We will generate negative line numbers for RST prolog errors data.line = data.get('line') if isinstance(data.line, int): data.line -= rst_prolog_line_offset data.source = data['source'] data.level = data['level'] data.type = data['type'] data.message = Element.astext(data.children[0]) data.full_message = Element.astext(data) # Save the error errors.append(data) document.reporter.attach_observer(error_collector) # Parse the content (and collect errors) # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/readers/__init__.py#l75 reader.parser.parse(content, document) # Apply transforms (and more collect errors) # DEV: We cannot use `apply_transforms` since it has `attach_observer` baked in. We want only our listener. # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/core.py#l195 # http://repo.or.cz/w/docutils.git/blob/422cede485668203abc01c76ca317578ff634b30:/docutils/docutils/transforms/__init__.py#l159 document.transformer.populate_from_components( (pub.source, pub.reader, pub.reader.parser, pub.writer, pub.destination) ) transformer = document.transformer while transformer.transforms: if not transformer.sorted: # Unsorted initially, and whenever a transform is added. transformer.transforms.sort() transformer.transforms.reverse() transformer.sorted = 1 priority, transform_class, pending, kwargs = transformer.transforms.pop() transform = transform_class(transformer.document, startnode=pending) transform.apply(**kwargs) transformer.applied.append((priority, transform_class, pending, kwargs)) return errors def lint_file(filepath, encoding=None, *args, **kwargs): """Lint a specific file""" with io.open(filepath, encoding=encoding) as f: content = f.read() return lint(content, filepath, *args, **kwargs)
/restructuredtext_lint-1.4.0.tar.gz/restructuredtext_lint-1.4.0/restructuredtext_lint/lint.py
0.703346
0.216985
lint.py
pypi
import typing import flask import flask_restx from werkzeug.datastructures import MultiDict __all__ = ( "Argument", "RequestParser", ) class Argument(flask_restx.reqparse.Argument): @property def __schema__(self): param_ = super(Argument, self).__schema__ if param_ and self.action == "append": # fixes badly placed patter of lists param_["items"]["pattern"] = param_["pattern"] _ = param_.pop("pattern", None) return param_ def source(self, request: flask.Request) -> typing.Any: """ Pulls values off the request in the provided location :param request: The flask request object to parse arguments from """ if isinstance(self.location, str): if not request.is_json and self.location == "json": # fixes problem with new flask.Request json in GET request types return MultiDict() value = getattr(request, self.location, MultiDict()) if callable(value): value = value() return value if value is not None else MultiDict() else: values = MultiDict() locations = list(self.location) if not request.is_json and "json" in locations: # fixes problem with new flask.Request json in GET request types locations.remove("json") for _location in locations: value = getattr(request, _location, None) if callable(value): value = value() if value is not None: values.update(value) return values A_ = typing.TypeVar('A_', bound=flask_restx.reqparse.Argument) PR_ = typing.TypeVar('PR_', bound=flask_restx.reqparse.ParseResult) class RequestParser(flask_restx.reqparse.RequestParser): args: typing.List[typing.Type[A_]] argument_class: typing.Type[A_] result_class: typing.Type[PR_] trim: bool bundle_errors: bool def __init__( self, argument_class: typing.Type[A_] = Argument, result_class: typing.Type[PR_] = flask_restx.reqparse.ParseResult, trim: bool = False, bundle_errors: bool = False, ) -> None: super(RequestParser, self).__init__(argument_class, result_class, trim, bundle_errors)
/restx-monkey-0.4.0.tar.gz/restx-monkey-0.4.0/src/restx_monkey/restx_reqparser.py
0.595845
0.193681
restx_reqparser.py
pypi
# ReSuber [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/polak0v/ReSuber/HEAD) [![Python 3.6](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org/downloads/release/python-360/) [![PyPI version](https://badge.fury.io/py/resuber.svg)](https://badge.fury.io/py/resuber) ![GitHub](https://img.shields.io/github/license/polak0v/resuber) [![Donate with Bitcoin](https://en.cryptobadges.io/badge/small/12eAEKU4rgvhLCxvdkxKJYocJdEFRyNrta)](https://en.cryptobadges.io/donate/12eAEKU4rgvhLCxvdkxKJYocJdEFRyNrta) ![](logo.svg) ReSuber is an automatic tool to re-synchronize any SRT subtitles, using its corresponding vocal audio WAV stream from a movie. It uses machine learning techniques to perform language agnostic re-synchronization, by checking the signal correlation between the vocal audio stream and the corrected subtitle signal. ReSuber also provide different utilities, including vocal audio extraction, subtitle/video file merging into containers and automatic translation of SRT subtitles with the Google Cloud Translation API (no API key required). [License](LICENSE) # Usage The main tool of this toolbox, `resuber`, re-synchronize any `.srt` subtitle file, given its corresponding `.wav` audio vocal file from a movie. For the complete list of tools, you should read [this paragraph](#optionnal-tools). ## First use Given any directory with the following file-structure (and same name): ``` |-examples | |-movie_example.fr.srt | |-movie_example.eng.srt | |-movie_example.wav ``` Simply run `resuber` from within the directory: ``` cd examples resuber ``` After completion, each subtitle will be re-synchronized and saved into new files `*.resubed.srt`: ``` |-examples | |-movie_example.fr.srt | |-movie_example.eng.srt | |-movie_example.wav | |-movie_example.fr.srt.resubed.srt | |-movie_example.eng.srt.resubed.srt ``` If you don't have the audio track for your movie, follow [this section](#i-dont-have-the-audio-track-from-my-movie). Input subtitle language extensions must follow [ISO_639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes). ## Advanced use ### Arguments ``` usage: resuber [-h] [--debug] [--input-dir INPUT_DIR] [--output-dir OUTPUT_DIR] [--recursive] [--subtitles [SUBTITLES [SUBTITLES ...]]] [--vocals [VOCALS [VOCALS ...]]] [--refine {no,mask,sample}] [--fs FS] [--start START] [--end END] [--range-weight [RANGE_WEIGHT [RANGE_WEIGHT ...]]] [--range-offset [RANGE_OFFSET [RANGE_OFFSET ...]]] [--fix-weight] [--fix-offset] [--max-shift MAX_SHIFT] [--min-clusters-distance MIN_CLUSTERS_DISTANCE] [--encoding ENCODING] [--version] optional arguments: -h, --help show this help message and exit --debug enable debugging information (default: False) --input-dir INPUT_DIR input directory to the SRT subtitle and WAV audio file(s) (default: .) --output-dir OUTPUT_DIR output dir for the corrected SRT subtitle file (default: input_dir) --recursive allow recursive search if vocals and/or subtitles are not specified (default: False) --subtitles [SUBTITLES [SUBTITLES ...]] input filename(s) to the SRT subtitle file(s) per WAV vocal file (default: ./*.srt) --vocals [VOCALS [VOCALS ...]] input filename(s) to the WAV vocal file(s) (default: ./*.wav) --refine {no,mask,sample} mask (cluster-wise), sample-wise or no non-linear refinement of the subtitle signal (default: 'no') --fs FS sampling rate in Hz (default: 100 Hz) --start START Minimum timestamp to process with format 'h:m:s.ms' (default: '0:0:0.0') --end END Maximum timestamp to process with format 'h:m:s.ms (default: '24:60:60.99') --range-weight [RANGE_WEIGHT [RANGE_WEIGHT ...]] range allowed for the weight parameter during rough exploration (default: [-1e-2, 1e-2]) --range-offset [RANGE_OFFSET [RANGE_OFFSET ...]] range allowed in ms for the offset parameter during rough exploration (default: [-5000., 5000.]) --fix-weight disable the optimization of the weight parameter (default: False) --fix-offset disable the optimization of the offset parameter (default: False) --max-shift MAX_SHIFT if non-linear refinement is allowed, define the maximum acceptable shift in ms (default: 500 ms) --min-clusters-distance MIN_CLUSTERS_DISTANCE if masked non-linear refinement is allowed, specify minimal distance allowed between clusters in ms (default: 10000 ms) --encoding ENCODING encoding for subtitles (default: utf-8) --version show program's version number and exit ``` ### Customize the AI `resuber` makes the assumption that the subtitles are "linearly" de-synchronized with the audio (i.e. it exists a function such as y = α x + β). This is typically the case for subtitles that were created from a movie with a different framerate. There are several parameters that allows you to have some control over the fitting algorithm, more specifically the scaling α and offset parameter β. 1. You can first change the range for the initial parameter search with `--range-weight` and `--range-offset`. This can be usefull if you know approximately how your inputs are de-synchronized. 2. It is also possible to disable the gradient-descent loop with `--fix-weight` and `--fix-offset`. In this case, the algorithm simply make a standard search in the parameter space (defined by `--range-*`). 3. Though I would recommend to use [pysubs2](https://github.com/tkarabela/pysubs2) for that, you can also edit the subtitle yourself and completely disable the AI. For example if you know that your subtitle have a fixed delay of +200ms, use: ``` resuber --range-weight -0.0001 0.0001 --range-offset -200.1 -199.9 --fix-weight --fix-offset ``` ### Debugging I advice you to enable the `--debug` argument, it will create a new folder `resuber-debug` in which you will find usefull files. ``` |-resuber-debug | |-movie_example.fr | | |-data.html | | |-loss.html | | |-cost_2d.html | |-movie_example.eng_resubed.txt | |-movie_example.eng | | |-data.html | | |-loss.html | | |-cost_2d.html | |-movie_example.fr_resubed.txt ``` `*_resubed.txt` is the processed subtitle converted into a `.txt` [Audacity](https://www.audacityteam.org/) label file. This is really usefull if you want to load the audio track, and view the subtitles. `*.[lang]` folders contains intermediate and output from the algorithm: * `cost_2d.html` correspond to the initial affine parameters (scale and offset) before the gradient-descent. Ideally, the shape of the cost should be gaussian-like (if) linear de-synchronization). * `data.html` is a truncated view of the input subtitle signal (blue), target audio (green) and re-synchronized subtitle signal (orange). Re-synchronized subtitle signal should be as much close as possible to the target audio. * `loss.html` show the variation of the fitness (correlation) at each iteration. Ideally, it should be an asymptotic decreasing function. ### Non-linear refinement (WIP) Where `resuber` works relatively well for linear de-synchronization, it still has trouble for non-linear de-synchronization. If that is the case, you can try to use the `--refine` argument. With `mask`, `resuber` will decompose the signal into multiple clusters, and fit the best delay for each cluster (typically the case for anime song opening with varying lengths). `sample` means that each value will have a different delay. # Optionnal tools ReSuber is a software with different tools, each serving its own purpose. Instead of creating a big pipeline (and messing up with dependencies), I made multiple tools that are independent between each other. To know which tool is best suited for your case, select one of the following section. [>> I don't have the audio track from my movie](#i-dont-have-the-audio-track-from-my-movie) [>> I have an original (correct) subtitle, and I want to synchronize another one](#i-have-an-original-correct-subtitle-and-i-want-to-synchronize-another-one) [>> I want to translate my subtitle](#i-want-to-translate-my-subtitle) [>> I have a subtitle that I want to merge with my movie file](#i-have-a-subtitle-that-i-want-to-merge-with-my-movie-file) ## I don't have the audio track from my movie [Spleeter](https://github.com/deezer/spleeter) from [Deezer](https://www.deezer.com/us/) is a deep-learning tool that separates vocal track from an audio track. This is obviously really usefull here, since the music and sound effects "pollutes" the signal and makes the correlation between the subtitle and audio signal a mess. I made a tool called `spleeter2resuber` that: 1. take the audio track from the `.mp4`, `.mkv` or `.avi` movie file 2. extract the (human) vocal from the audio with `spleeter`. After installing `spleeter` and [ffmpeg](https://www.ffmpeg.org/), just run `spleeter2resuber` inside any folder with: ``` |-examples | |-movie_example.mkv | |-movie_example.fr ``` It will create a new folder `resuber`, ready to be use. Check also the sub-folder `resuber/spleeter` for debuging. ## I have an original (correct) subtitle, and I want to synchronize another one If that is the case and you were not successfull with `resuber` (for example, the other subtitle is non-linearly dependent on the audio) then you have another solution. You can use `resuber-move` that will take the reference timestamp from the (correct) subtitle, and do a nearest neighbor with your other (de-synchronized) subtitle. That way you will have the text from the (de-synchronized) subtitle, with approximately the reference timestamp of the (correct) subtitle. Given this folder: ``` |-examples | |-movie_example.fr.srt (original) | |-movie_example.eng.srt (de-synchronized) | |-movie_example.wav ``` Run: ``` resuber-move --ref-lang en --tgt-time fr ``` You have several other options to play with. ``` usage: resuber-move [-h] [--input-dir INPUT_DIR] [--ref-lang REFERENCE_LANGUAGE] [--tgt-time TARGET_TIMESTAMPS] [--encoding ENCODING] [--min-dist MIN_DIST] [--drop-far DROP_FAR] optional arguments: -h, --help show this help message and exit --input-dir INPUT_DIR --ref-lang REFERENCE_LANGUAGE --tgt-time TARGET_TIMESTAMPS --encoding ENCODING --min-dist MIN_DIST Maximum delay (ms) to be considered as a near neighbor (default: 2000ms). --drop-far DROP_FAR Drop subtitles that are too far. ``` ## I want to translate my subtitle Hopefully, if you are lazy like me there is the [google translate API](https://translate.google.com). With these files: ``` |-examples | |-movie_example.fr.srt | |-movie_example.wav ``` Translate from french subtitle `movie_example.fr.srt` to english `movie_example.eng.srt` with: ``` resuber-translate --ref-lang fr --tgt-lang en ``` Google imposes several limitations with the number of requests (limit of 100 per hour). I managed to process the translation batch by batch to reduce the burden, but be careful to not run this too often (or use a VPN...). ``` usage: resuber-translate [-h] [--input-dir INPUT_DIR] [--ref-lang REFERENCE_LANGUAGE] [--tgt-lang TARGET_LANGUAGE] [--encoding ENCODING] optional arguments: -h, --help show this help message and exit --input-dir INPUT_DIR --ref-lang REFERENCE_LANGUAGE --tgt-lang TARGET_LANGUAGE --encoding ENCODING ``` ## I have a subtitle that I want to merge with my movie file For this you can use [mkvmerge](https://mkvtoolnix.download/doc/mkvmerge.html), but I also made a home-made tool `resuber-merge` that requires [ffmpeg](https://www.ffmpeg.org/) to be installed. Given a folder with a movie file (`.mp4`, `.mkv` or `.avi`) and subtitle: ``` |-examples | |-movie_example.fr.srt | |-movie_example.mp4 ``` You can merge the subtitle inside a video `.mkv` file with: ``` resuber-merge ``` Make sure to check all the options. ``` usage: resuber-merge [-h] [--input-dir INPUT_DIR] [--output_container OUTPUT_CONTAINER] optional arguments: -h, --help show this help message and exit --input-dir INPUT_DIR --output_container OUTPUT_CONTAINER ``` # Installation ## pip ``` python3 -m pip install resuber ``` ## src ``` git clone https://github.com/polak0v/ReSuber cd ReSuber make install ``` # Unit testing You will need [pytest](https://docs.pytest.org/en/6.2.x/), and then run: ``` pytests tests/ ``` # Support If you like my work, you are welcome to donate some bitcoins. :) BTC: 12eAEKU4rgvhLCxvdkxKJYocJdEFRyNrta
/resuber-1.1.2.tar.gz/resuber-1.1.2/README.md
0.819677
0.948917
README.md
pypi
__all__ = [ "success", "failure", "unwrap_success", "unwrap_failure", "Result", "ResultType", "NoResult", "NoResultType", ] from typing import overload, TypeVar, Union from resultful.impl.result import Success, Failure from resultful.impl.no_result import NoResult, NoResultType ValueType = TypeVar("ValueType") ErrorType = TypeVar("ErrorType", bound=BaseException) Result = Union[Success[ValueType], Failure[ErrorType]] ResultType = (Success, Failure) # TODO(kprzybyla): Remove "type: ignore" once below feature will be implemented # https://github.com/python/typing/issues/599 @overload def success(value: Failure[ErrorType], /) -> NoResultType: # type: ignore ... @overload def success(value: Success[ValueType], /) -> Success[ValueType]: ... @overload def success(value: ValueType, /) -> Success[ValueType]: ... def success( # type: ignore value: Union[Failure[ErrorType], Success[ValueType], ValueType], / ) -> Union[NoResultType, Success[ValueType]]: """ Returns value wrapped in :class:`Success`. If value is a :class:`Failure`, returns NoResult. If value is a :class:`Success`, returns that :class:`Success`. :param value: any value """ if isinstance(value, Failure): return NoResult if isinstance(value, Success): return value return Success(value) @overload def failure(error: Success[ValueType], /) -> NoResultType: ... @overload def failure(error: Failure[ErrorType], /) -> Failure[ErrorType]: ... @overload def failure(error: ErrorType, /) -> Failure[ErrorType]: ... def failure( error: Union[Success[ValueType], Failure[ErrorType], ErrorType], / ) -> Union[NoResultType, Failure[ErrorType]]: """ Returns error wrapped in :class:`Failure`. If value is a :class:`Success`, returns NoResult. If value is a :class:`Failure`, returns that :class:`Failure`. :param error: any exception """ if isinstance(error, Success): return NoResult if isinstance(error, Failure): return error return Failure(error) @overload def unwrap_success(result: Failure[ErrorType]) -> NoResultType: ... @overload def unwrap_success(result: Success[ValueType]) -> ValueType: ... def unwrap_success(result: Result[ValueType, ErrorType]) -> Union[NoResultType, ValueType]: """ Unwraps error from given :class:`Success`. :param result: :class:`Success` """ if isinstance(result, Failure): return NoResult return result.value @overload def unwrap_failure(result: Success[ValueType]) -> NoResultType: ... @overload def unwrap_failure(result: Failure[ErrorType]) -> ErrorType: ... def unwrap_failure(result: Result[ValueType, ErrorType]) -> Union[NoResultType, ErrorType]: """ Unwraps error from given :class:`Failure`. :param result: :class:`Failure` """ if isinstance(result, Success): return NoResult return result.error
/ui/result.py
0.624523
0.340184
result.py
pypi
from sqlalchemy import \ Column,\ BigInteger,\ Boolean,\ Integer,\ Interval,\ String,\ Numeric,\ DateTime,\ JSON,\ Float,\ Text,\ ForeignKey,\ MetaData,\ DDL,\ event from sqlalchemy.types import ARRAY from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy.dialects.postgresql import JSONB import os Base = declarative_base(metadata=MetaData(schema='results')) event.listen( Base.metadata, 'before_create', DDL("CREATE SCHEMA IF NOT EXISTS results") ) group_proc_filename = os.path.join( os.path.dirname(__file__), 'model_group_stored_procedure.sql' ) with open(group_proc_filename) as f: stmt = f.read() event.listen( Base.metadata, 'before_create', DDL(stmt) ) class Experiment(Base): __tablename__ = 'experiments' experiment_hash = Column(String, primary_key=True) config = Column(JSONB) class ModelGroup(Base): __tablename__ = 'model_groups' model_group_id = Column(Integer, primary_key=True) model_type = Column(Text) model_parameters = Column(JSONB) feature_list = Column(ARRAY(Text)) model_config = Column(JSONB) class Model(Base): __tablename__ = 'models' model_id = Column(Integer, primary_key=True) model_group_id = Column(Integer, ForeignKey('model_groups.model_group_id')) model_hash = Column(String, unique=True, index=True) run_time = Column(DateTime) batch_run_time = Column(DateTime) model_type = Column(String) model_parameters = Column(JSONB) model_comment = Column(Text) batch_comment = Column(Text) config = Column(JSON) experiment_hash = Column(String, ForeignKey('experiments.experiment_hash')) train_end_time = Column(DateTime) test = Column(Boolean) train_matrix_uuid = Column(Text) training_label_timespan = Column(Interval) model_group_rel = relationship('ModelGroup') experiment_rel = relationship('Experiment') def delete(self, session): # basically implement a cascade, in case cascade is not implemented session.query(FeatureImportance)\ .filter_by(model_id=self.model_id)\ .delete() session.query(Evaluation)\ .filter_by(model_id=self.model_id)\ .delete() session.query(Prediction)\ .filter_by(model_id=self.model_id)\ .delete() session.delete(self) class FeatureImportance(Base): __tablename__ = 'feature_importances' model_id = Column(Integer, ForeignKey('models.model_id'), primary_key=True) model = relationship(Model) feature = Column(String, primary_key=True) feature_importance = Column(Numeric) rank_abs = Column(Integer) rank_pct = Column(Float) model_rel = relationship('Model') class Prediction(Base): __tablename__ = 'predictions' model_id = Column(Integer, ForeignKey('models.model_id'), primary_key=True) entity_id = Column(BigInteger, primary_key=True) as_of_date = Column(DateTime, primary_key=True) score = Column(Numeric) label_value = Column(Integer) rank_abs = Column(Integer) rank_pct = Column(Float) matrix_uuid = Column(Text) test_label_timespan = Column(Interval) model_rel = relationship('Model') class ListPrediction(Base): __tablename__ = 'list_predictions' model_id = Column(Integer, ForeignKey('models.model_id'), primary_key=True) entity_id = Column(BigInteger, primary_key=True) as_of_date = Column(DateTime, primary_key=True) score = Column(Numeric) rank_abs = Column(Integer) rank_pct = Column(Float) matrix_uuid = Column(Text) test_label_timespan = Column(Interval) model_rel = relationship('Model') class IndividualImportance(Base): __tablename__ = 'individual_importances' model_id = Column(Integer, ForeignKey('models.model_id'), primary_key=True) entity_id = Column(BigInteger, primary_key=True) as_of_date = Column(DateTime, primary_key=True) feature = Column(String, primary_key=True) method = Column(String, primary_key=True) feature_value = Column(Float) importance_score = Column(Float) model_rel = relationship('Model') class Evaluation(Base): __tablename__ = 'evaluations' model_id = Column(Integer, ForeignKey('models.model_id'), primary_key=True) evaluation_start_time = Column(DateTime, primary_key=True) evaluation_end_time = Column(DateTime, primary_key=True) as_of_date_frequency = Column(Interval, primary_key=True) metric = Column(String, primary_key=True) parameter = Column(String, primary_key=True) value = Column(Numeric) num_labeled_examples = Column(Integer) num_labeled_above_threshold = Column(Integer) num_positive_labels = Column(Integer) sort_seed = Column(Integer) model_rel = relationship('Model')
/results_schema-2.0.0.tar.gz/results_schema-2.0.0/results_schema/schema.py
0.529993
0.295675
schema.py
pypi
import factory import factory.fuzzy from results_schema import schema import uuid from datetime import datetime import testing.postgresql from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session, create_session sessionmaker = sessionmaker() session = scoped_session(sessionmaker) class ExperimentFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.Experiment sqlalchemy_session = session experiment_hash = factory.fuzzy.FuzzyText() config = {} class ModelGroupFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.ModelGroup sqlalchemy_session = session model_type = 'sklearn.ensemble.RandomForestClassifier' model_parameters = {'hyperparam1': 'value1', 'hyperparam2': 'value2'} feature_list = ['feature1', 'feature2', 'feature3'] model_config = {} class ModelFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.Model sqlalchemy_session = session model_group_rel = factory.SubFactory(ModelGroupFactory) model_hash = factory.fuzzy.FuzzyText() run_time = factory.LazyFunction(lambda: datetime.now()) batch_run_time = factory.LazyFunction(lambda: datetime.now()) model_type = 'sklearn.ensemble.RandomForestClassifier' model_parameters = {'hyperparam1': 'value1', 'hyperparam2': 'value2'} model_comment = '' batch_comment = '' config = {} experiment_rel = factory.SubFactory(ExperimentFactory) train_end_time = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) test = False train_matrix_uuid = factory.fuzzy.FuzzyText() training_label_timespan = '1y' class FeatureImportanceFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.FeatureImportance sqlalchemy_session = session model_rel = factory.SubFactory(ModelFactory) feature = factory.fuzzy.FuzzyText() feature_importance = factory.fuzzy.FuzzyDecimal(0, 1) rank_abs = 1 rank_pct = 1.0 class PredictionFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.Prediction sqlalchemy_session = session model_rel = factory.SubFactory(ModelFactory) entity_id = factory.fuzzy.FuzzyInteger(0) as_of_date = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) score = factory.fuzzy.FuzzyDecimal(0, 1) label_value = factory.fuzzy.FuzzyInteger(0, 1) rank_abs = 1 rank_pct = 1.0 matrix_uuid = factory.fuzzy.FuzzyText() test_label_timespan = '3m' class ListPredictionFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.ListPrediction sqlalchemy_session = session model_rel = factory.SubFactory(ModelFactory) entity_id = factory.fuzzy.FuzzyInteger(0) as_of_date = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) score = factory.fuzzy.FuzzyDecimal(0, 1) rank_abs = 1 rank_pct = 1.0 matrix_uuid = factory.fuzzy.FuzzyText() test_label_timespan = '3m' class IndividualImportanceFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.IndividualImportance sqlalchemy_session = session model_rel = factory.SubFactory(ModelFactory) entity_id = factory.fuzzy.FuzzyInteger(0) as_of_date = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) feature = factory.fuzzy.FuzzyText() feature_value = factory.fuzzy.FuzzyDecimal(0, 100) method = factory.fuzzy.FuzzyText() importance_score = factory.fuzzy.FuzzyDecimal(0, 1) class EvaluationFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = schema.Evaluation sqlalchemy_session = session model_rel = factory.SubFactory(ModelFactory) evaluation_start_time = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) evaluation_end_time = factory.fuzzy.FuzzyNaiveDateTime(datetime(2008, 1, 1)) as_of_date_frequency = '3d' metric = 'precision@' parameter = '100_abs' value = factory.fuzzy.FuzzyDecimal(0, 1) num_labeled_examples = 10 num_labeled_above_threshold = 8 num_positive_labels = 5 sort_seed = 8 def init_engine(new_engine): global sessionmaker, engine, session engine = new_engine session.remove() sessionmaker.configure(bind=engine)
/results_schema-2.0.0.tar.gz/results_schema-2.0.0/results_schema/factories.py
0.431105
0.173708
factories.py
pypi
# resultsFile Python interface to read output files of quantum chemistry programs To add a module to read a new kind of output file, just add a file in the `Modules` directory. # Using the library Example (`resultsFile` is supposed to be in your `sys.path`): ``` Python import resultsFile file = resultsFile.getFile("g09_output.log") print('recognized as', str(file).split('.')[-1].split()[0]) print(file.mo_sets) ``` ## Constraints ### Gaussian09 * `GFPRINT` : Needed to read the AO basis set * `pop=Full` : Needed to read all the MOs * `#p CAS(SlaterDet)` : CAS-SCI CI coefficients When doing a CAS with Gaussian, first do the Hartree-Fock calculation saving the checkpoint file and then do the CAS in a second calculation. ### GAMESS-US For MCSCF calculations, first compute the MCSCF single-point wave function with the GUGA algorithm. Then, put the the MCSCF orbitals (of the `.dat` file) in the GAMESS input file, and run a single-point GUGA CI calculation with the following keywords: * `PRTTOL=0.0001` in the `$GUGDIA` group to use a threshold of 1.E-4 on the CI coefficients * `NPRT=2` in the `$CIDRT` group to print the CSF expansions in terms of Slater determinants * `PRTMO=.T.` in the `$GUESS` group to print the molecular orbitals ### Molpro (deprecated) * `print, basis;` : Needed to read the AO basis set * `gprint,orbital;` : Needed to read the MOs * `gprint,civector; gthresh,printci=0.;` : Needed to read the CI coefficients * `orbprint` : Ensures all the MOs are printed An RHF calculation is mandatory before any MCSCF calculation, since some information is printed only the RHF section. Be sure to print *all* molecular orbitals using the `orbprint` keyword, and to use the same spin multiplicity and charge between the RHF and the CAS. # Debugging Any module can be run as an stand-alone executable. For example: ``` $ resultsFile/Modules/gamessFile.py resultsFile version 1.0, Copyright (C) 2007 Anthony SCEMAMA resultsFile comes with ABSOLUTELY NO WARRANTY; for details see the gpl-license file. This is free software, and you are welcome to redistribute it under certain conditions; for details see the gpl-license file. Usage: ------ resultsFile/Modules/gamessFile.py [options] file Options: -------- --date : When the calculation was performed. --version : Version of the code generating the file. --machine : Machine where the calculation was run. --memory : Requested memory for the calculation. --disk : Requested disk space for the calculation. --cpu_time : CPU time. --author : Who ran the calculation. --title : Title of the run. --units : Units for the geometry (au or angstroms). --methods : List of calculation methods. --options : Options given in the input file. --spin_restrict : Open-shell or closed-shell calculations. --conv_threshs : List of convergence thresholds. --energies : List of energies. --one_e_energies : List of one electron energies. --two_e_energies : List of two electron energies. --ee_pot_energies : List of electron-electron potential energies. --Ne_pot_energies : List of nucleus-electron potential energies. --pot_energies : List of potential energies. --kin_energies : List of kinetic energies. --virials : Virial ratios. --point_group : Symmetry used. --num_elec : Number of electrons. --charge : Charge of the system. --multiplicity : Spin multiplicity of the system. --nuclear_energy : Repulsion of the nuclei. --dipole : Dipole moment --geometry : Atom types and coordinates. --basis : Basis set definition --mo_sets : List of molecular orbitals --mo_types : Types of molecular orbitals (canonical, natural,...) --mulliken_mo : Mulliken atomic population in each MO. --mulliken_ao : Mulliken atomic population in each AO. --mulliken_atom : Mulliken atomic population. --lowdin_ao : Lowdin atomic population in each AO. --mulliken_atom : Mulliken atomic population. --lowdin_atom : Lowdin atomic population. --two_e_int_ao : Two electron integrals in AO basis --determinants : List of Determinants --num_alpha : Number of Alpha electrons. --num_beta : Number of Beta electrons. --closed_mos : Closed shell molecular orbitals --active_mos : Active molecular orbitals --virtual_mos : Virtual molecular orbitals --determinants_mo_type : MO type of the determinants --det_coefficients : Coefficients of the determinants --csf_mo_type : MO type of the determinants --csf_coefficients : Coefficients of the CSFs --symmetries : Irreducible representations --occ_num : Occupation numbers --csf : List of Configuration State Functions --num_states : Number of electronic states --two_e_int_ao_filename : --one_e_int_ao_filename : --atom_to_ao_range : --gradient_energy : Gradient of the Energy wrt nucl coord. --text : --uncontracted_basis : --uncontracted_mo_sets : ```
/resultsFile-2.2.tar.gz/resultsFile-2.2/README.md
0.795221
0.90723
README.md
pypi
import requests # type: ignore from contextlib import closing # type: ignore from re import fullmatch # type: ignore from enum import Enum import hashlib from typing import Union, Dict, Optional, Tuple, NamedTuple, Any from pathlib import Path from logging import getLogger path = Union[str, Path] log = getLogger(__name__) DownloadCheck = Enum('DownloadCheck', 'completed partial checksum_mismatch size_mismatch') # type: ignore class DownloadError(Exception): pass ContentRange = NamedTuple('ContentRange', [('start', int), ('end', int), ('total', Optional[int])]) def sha256(filename: path) -> str: sha = hashlib.sha256() chunksize = 524288 with Path(filename).open('rb') as f: data = f.read(chunksize) while data: sha.update(data) data = f.read(chunksize) return sha.hexdigest() def is_download_complete(filename: Path, sha256sum: str, filesize: int) -> Any: D = DownloadCheck # type: Any try: if sha256sum is not None: return D.completed if sha256(filename) == sha256sum else D.checksum_mismatch elif filesize is not None: return D.completed if filename.stat().st_size == filesize else D.size_mismatch else: return D.partial except (NameError, FileNotFoundError): return D.partial def parse_byte_range(content_range: str) -> ContentRange: try: start, end, total = fullmatch('bytes (\d+)-(\d+)/(\d+|\*)', content_range).groups() except AttributeError: raise DownloadError('Invalid Content-Range', content_range) else: total = int(total) if total != '*' else None return ContentRange(int(start), int(end), total) def get_resource_size(headers: Dict[str, str]) -> Optional[int]: cl = headers.get('Content-Length') cr = headers.get('Content-Range') if cr is not None: return parse_byte_range(cr).total elif cl: return int(cl) def starting_range(resp, filesize: Optional[int]) -> int: '''Find starting index from Content-Range, if any. Warn about problematic ranges''' if resp.status_code == 206 and 'Content-Range' in resp.headers: cr = parse_byte_range(resp.headers['Content-Range']) if filesize and filesize != cr.start: log.warning('The download is not resuming exactly where it ended') if cr.total and cr.end != cr.total - 1: log.warning("The download won't fetch the whole file," " you might want to run urlretrieve again") return cr.start else: return 0 def write_response(resp, filename: Path, reporthook, size: Optional[int], remote_size: Optional[int]): if size is None or size != remote_size: with filename.open('r+b') if filename.exists() else filename.open('xb') as f: start = starting_range(resp, size) f.seek(start) chunk_size = 16384 for i, chunk in enumerate(resp.iter_content(chunk_size=chunk_size), start // chunk_size): if chunk: f.write(chunk) if reporthook: reporthook(i, chunk_size, remote_size or -1) f.flush() def urlretrieve(url: str, filename: path, reporthook=None, method='GET', sha256sum=None, filesize=None, headers=None, **kwargs) -> Dict[str, str]: D = DownloadCheck # type: Any filename = Path(filename) if is_download_complete(filename, sha256sum, filesize) != D.completed: size = filename.stat().st_size if filename.exists() else None headers = headers or {} headers.update({'Range': 'bytes=%s-' % size} if size is not None else {}) with closing(requests.request(method, url, stream=True, headers=headers, **kwargs)) as resp: remote_size = get_resource_size(resp.headers) already_completed = resp.status_code == 416 if not already_completed: try: resp.raise_for_status() except requests.exceptions.HTTPError as e: raise DownloadError(e) write_response(resp, filename, reporthook, size, remote_size) check = is_download_complete(filename, sha256sum, filesize) if check not in (D.completed, D.partial): raise DownloadError(check) return resp.headers
/resumable-urlretrieve-0.1.6.tar.gz/resumable-urlretrieve-0.1.6/resumable/__init__.py
0.640186
0.20091
__init__.py
pypi
import json import logging import os from pathlib import Path from typing import Tuple import uuid import requests import validators # To validate that a certain string is a url from dotenv import load_dotenv # Use of environment variables from validators.utils import ValidationFailure def is_url_image(url: str) -> Tuple[str, bool]: """ [Check if an url is an image] Args: url (str): [The url to check] Returns: str: [The content type of the url image] bool: [A boolean that indicates if the url is an image] """ load_dotenv() image_formats = json.loads(str(os.getenv("IMAGE_FORMATS"))) if not is_string_an_url(url): return "Not a url", False else: r = requests.head(url, timeout=5) if r.headers["content-type"] in image_formats: return str(r.headers["content-type"]), True return str(r.headers), False def is_string_an_url(url_string: str) -> bool: """ [Check if a string is a valid url] Args: url_string (str): [the string to validate] Returns: bool: [a boolean indicating if the string is a valid url] """ result = validators.url(url_string) # type: ignore if isinstance(result, ValidationFailure): return False else: return True def store_image_to_temp(image_folder: str, url: str) -> str: """ [Store an image to a temporary folder] Args: image_folder (str): [The temporary folder to save the image to] url (str): [The url to fetch the image from] Returns: str: [The location of the image] """ logging.info( f"Downloading badge image from location {url} to folder {image_folder}" ) header, valid_url = is_url_image(url) if valid_url: img_data = requests.get(url, timeout=1).content # type: ignore with open(Path(image_folder, str(uuid.uuid4())), "wb") as file: file.write(img_data) return file.name else: raise ValueError( f"The url '{url}' does not contain a valid image url. (Header type: {header})" )
/resume-as-code-0.0.12.tar.gz/resume-as-code-0.0.12/resume_as_code/util.py
0.839898
0.242419
util.py
pypi
import logging import os import tempfile from typing import Dict, List import magic import requests # To request the images listed in the badges import yaml # Retrieve the context from docx.shared import Mm # Set the height of the inlined image from docxtpl import DocxTemplate, InlineImage # Create Microsoft Word template from jinja2 import Environment # To pass custom filters to template from resume_as_code.util import store_image_to_temp from resume_as_code.validation import validate_resume def fetch_resume_template(template_location: str) -> DocxTemplate: """ [Retrieve the resume template] Args: template_location (str): [the location where the resume template is stored] Raises: FileNotFoundError: [if the file with filename provided in template_location does not exist] ValueError: [if the file is of the wrong filetype] Returns: DocxTemplate: [the Docx-Jinja-template] """ if not os.path.exists(template_location): raise FileNotFoundError( "There is no file with location {}".format(template_location) ) if "Microsoft Word" not in magic.from_file(template_location): raise ValueError( "Wrong filetype provided for the template file with location {}".format( template_location ) ) return DocxTemplate(template_location) def fetch_yaml_context(context_location: str, schema_filename: str) -> Dict[str, Dict]: """ [Retrieve the yaml context from its file and return as dictionary] Args: context_location (str): [the location where the yaml-resume is stored] schema_filename (str): [the filename containing the yaml specification] Raises: FileNotFoundError: [if the file with filename provided in context_location does not exist] ValueError: [if the file with the filename provided in context_location does not adhere to the spec defined in $SCHEMA_FILENAME] Returns: Dict[str, Dict]: [a dictionairy of key-value pairs] """ if not os.path.exists(context_location): raise FileNotFoundError( "There is no file with location {}".format(context_location) ) validation_flag, msg = validate_resume(context_location, schema_filename) if validation_flag: logging.info(msg.format(context_location=context_location)) with open(context_location, "r") as file: yaml_resume = yaml.load(file, Loader=yaml.FullLoader) return yaml_resume else: raise ValueError(msg) def render_and_save( template: DocxTemplate, context: Dict[str, Dict], jinja_env: Environment, target_location: str, ) -> int: """ [Render the template with the provided context and store in the target location] Args: template (DocxTemplate): [the Jinja-parametrized template] context (Dict[str, Dict]): [the YAML-context retrieved from the resume] jinja_env (Environment): [the jinja2 Environment to be passed down to the template] target_location (str): [the location to store the file in] Returns: int: [an integer status code] """ with tempfile.TemporaryDirectory() as image_folder: preprocess_context(context, template, image_folder) template.render(context=context, jinja_env=jinja_env) template.save(target_location) return 0 def preprocess_context( context: Dict[str, Dict], template: DocxTemplate, image_folder: str ) -> None: """ [Preprocess the context. Inline the images.] Args: context (Dict[str, Dict]): [The dict containing the yaml resume-values] template (DocxTemplate): [The template to inline the images on] image_folder (str): [The name of the temporary directory to save the images in] """ if "certifications" not in context["contact"].keys(): return for cert in context["contact"]["certifications"]: if "badge_image" not in cert.keys(): continue badge_location = cert["badge_image"] try: image_location = store_image_to_temp(image_folder, badge_location) logging.info(f"Inlining image from location {image_location}") cert["image"] = InlineImage(template, image_location, height=Mm(20)) except ValueError as e: # In case of an invalid url, the image shouldn't be inlined. Log the error though. logging.warning(e) except requests.exceptions.ConnectionError as e: # type: ignore logging.warning(f"The url in string {badge_location} does not exist") def with_badge(certs: List[Dict[str, str]]) -> List[Dict[str, str]]: """ [Filter those certifications with a badge] Args: certs (List[Dict[str, str]]): [The unfiltered list of certifications] Returns: List[Dict[str, str]]: [Only those certifications that have a badge_image linked to it] """ badged_certs = [cert for cert in certs if "badge_image" in cert.keys()] return badged_certs def without_badge(certs: List[Dict[str, str]]) -> List[Dict[str, str]]: """ [Filter those certifications with a badge] Args: certs (List[Dict[str, str]]): [The unfiltered list of certifications] Returns: List[Dict[str, str]]: [Only those certifications that have a badge_image linked to it] """ badged_certs = [cert for cert in certs if "badge_image" not in cert.keys()] return badged_certs def generate_resume( template_location: str, context_location: str, target_location: str, schema_location: str, ) -> int: """ [Go through the entire flow of generating the resume] Args: template_location (str): [the location where the template is stored] context_location (str): [the location where the context is stored] target_location (str): [the location to store the generated resume in] schema_location (str): [the location where the yaml specification is stored] Returns: int: [the status code to indicate succes/not] """ template = fetch_resume_template(template_location) try: context = fetch_yaml_context(context_location, schema_location) except ValueError as _: logging.error( f"The context in '{context_location}' does not contain a valid resume. Please review the spec in {schema_location}" ) return -1 jinja_env = Environment(autoescape=True) jinja_env.filters["with_badge"] = with_badge jinja_env.filters["without_badge"] = without_badge status_code = render_and_save(template, context, jinja_env, target_location) return status_code
/resume-as-code-0.0.12.tar.gz/resume-as-code-0.0.12/resume_as_code/resume_generation.py
0.696681
0.428592
resume_generation.py
pypi
from resume_classification import utils as st from resume_classification import config as cf import re import pickle import warnings import numpy as np import pandas as pd from glob import glob from tika import parser from collections import Counter import matplotlib.pyplot as plt import logging import pkg_resources import sys from nltk.stem.snowball import SnowballStemmer from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import confusion_matrix, f1_score, accuracy_score warnings.filterwarnings('ignore') logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(funcName)s:%(message)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) class Train : ''' This class is used to train the resumes. ''' def __init__(self,path) : self.path = path self.count_vect = CountVectorizer() self.le = LabelEncoder() self.df = pd.DataFrame() self.scaler = StandardScaler() logger.info('Module Train: Initialization complete') def preprocess_resume(self,path) : logger.info('Inside preprocess_resume method') ''' This method performs the pre-processing of the resumes, getting the text out of resume, getting the common words and its count, getting the stop word count. @param path :: string: Contains the path to resumes file. @return: txt :: string: Extracted text from resume. common_word :: string: List of common word present in text. common_count :: int: Count of common words stop_count :: int: Count of stopwords ''' try: txt = parser.from_file(path)['content'].lower().strip() txt = re.sub(st.PREPROCESS_STRING, " ", txt) txt_list = re.sub(st.SPACE_STRING, " ", txt).split(' ') stop_count = len(set(txt_list) & st.STOP ) txt_list = [ word for word in txt_list if word not in st.STOP ] common_words = ' '.join(list(zip(*Counter(txt_list).most_common(10)))[0]) common_count = Counter(txt_list).most_common(1)[0][1] txt = ' '.join(txt_list) logger.info('Features successful extracted for {}'.format(path.split('/')[-1])) except: txt = '' common_words = '' common_count = 0 stop_count = 0 logger.error('Data for file {} could not be extracted'.format(path.split('/')[-1])) logger.info('Execution Complete') return txt, common_words, common_count, stop_count def extract_resume_content(self) : logger.info('Inside extract_resume_content method') ''' This method adds the following features: :path :: string: path to resumes - Path to resumes is passed by the user in config file. :resume_name :: string: File name :resume_type :: string: Domain ''' self.df['path'] = glob(self.path + '*/**/*') self.df['resume_name'] = self.df['path'].astype(str).str.split('/').str[-1] self.df['resume_type'] = self.df['path'].astype(str).str.split('/').str[-2] self.df['resume'], self.df['common_words'], self.df['common_count'], self.df['stop_count'] = zip(*self.df['path'].apply(self.preprocess_resume)) logger.info('Execution complete') def add_features(self) : logger.info('Inside add_features method') ''' This method adds some more feature for model training: :word_count :: int: Count of each word :character_count :: int: Count of each character :avg_word_size :: int: Average word count ''' self.df['word_count'] = self.df['resume'].astype(str).str.split().str.len() self.df['character_count'] = self.df['resume'].astype(str).str.len() self.df['avg_word_size'] = self.df['character_count']/self.df['word_count'] logger.info('Execution Complete! Successfully added features: word_count, character_count, avg_word_size') def train_model(self) : logger.info('Inside train_model method') ''' This method will train the model using Logistic regression. ''' self.df.drop_duplicates(subset='resume',inplace=True) self.add_features() self.save_data('resume_dataframe',self.df) self.df['resume_type'] = self.le.fit_transform(self.df['resume_type']) # data leakage. X = self.df.drop('resume_type', axis = 1) y = self.df['resume_type'] self.save_encoder('classes') x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 123) self.x_test = x_test self.y_test = y_test x_train_count = self.count_vect.fit_transform(x_train['resume'], y = y_train) self.save_data('count_vect',self.count_vect) clf = LogisticRegression(random_state = 123, class_weight = 'balanced') clf.fit(x_train_count, y_train) self.clf = clf self.save_data('latest_model', clf) logger.info('Model Training Completed successfully.') def test_model(self) : logger.info('Inside test_model') ''' This method test the model accuracy on unseen test data and gives the following metrics :Accuracy :F1 Score :Confusion matix ''' x_test_count = self.count_vect.transform(self.x_test['resume']) y_pred = self.clf.predict(x_test_count) print('The accuracy score of model is '+ str(round((accuracy_score(self.y_test, y_pred)) * 100, 2))) print('The f1 score of model is '+ str(round((f1_score(self.y_test, y_pred, average = 'macro')) * 100, 2))) print('Confusion matix '+ str(confusion_matrix(self.y_test, y_pred))) def save_data(self, filename, data) : logger.info('Inside save_data method') ''' This method is used to save the object passed using pickle. @param filename :: string: Name of object to be saved. @param data :: object: Object to be saved. ''' file_name = cf.FILE_NAME + filename + '.pkl' #file_name = './model/' + filename +'.pkl' pickle.dump(data, open(file_name, 'wb')) logger.info('{} saved successfully at location : {}'.format(filename, str(file_name))) def save_encoder(self, filename): logger.info('Inside save_encoder method') ''' This method saves the encoder using numpy. ''' file_name = cf.FILE_NAME + filename + '.npy' np.save(file_name, self.le.classes_) logger.info('{} saved successfully at location : {}'.format(filename, file_name))
/resume_classification-1.0.tar.gz/resume_classification-1.0/resume_classification/training/train.py
0.440469
0.183905
train.py
pypi
import json import typing class ResumeCreate: """ The class to create the json resume. This class is the place to keep the creation of the json resume in one place. Here it will create all the data structures from the input of the user and build the final json, including saving the file to the user location of choice """ def __init__(self, ui): self.ui = ui def get_location(self) -> typing.Dict: """ Adaptor method to create the location data as needed with the input data. :return: """ location = self.ui.get_location() return { 'country': location['country'], 'region': location['region'], 'city': location['city'], 'address': location['address'], 'postal_code': location['postal_code'], } def get_profiles(self) -> typing.List[typing.Dict]: """ Adaptor method to create the profiles data as needed with the input data. :return: """ profiles = [] while self.ui.add_another('social network account'): profile = self.ui.get_profile() profiles.append({ 'network': profile['network'], 'username': profile['username'], 'url': profile['url'], }) return profiles def get_position(self) -> typing.Dict: """ Adaptor method to get the position information from the user input. :return: """ position = self.ui.get_position() return { 'name': position['name'], 'location': position['location'], 'description': position['description'], 'position': position['position'], 'url': position['url'], 'startDate': position['startDate'], 'endDate': position['endDate'], 'summary': position['summary'], } def get_work_history(self) -> typing.List[typing.Dict]: """ Adaptor method to get the work history from the user input. :return: """ work_history = [] position = self.get_position() position['highlights'] = self.ui.add_list_of_items('highlight') work_history.append(position) while self.ui.add_item('work'): position = self.get_position() position['highlights'] = self.ui.add_list_of_items('highlight') work_history.append(position) return work_history def get_volunteering_history(self) -> typing.List[typing.Dict]: """ Adaptor method to get the volunteering history of the user. :return: """ volunteering_history = [] if self.ui.add_item('volunteering'): volunteer = self.ui.get_volunteering() volunteer['highlights'] = self.ui.add_list_of_items('highlight') volunteering_history.append(volunteer) while self.ui.add_another('volunteering'): volunteer = self.ui.get_volunteering() highlights = self.ui.add_list_of_items('highlight') volunteering_history.append({ 'organization': volunteer['organization'], 'position': volunteer['position'], 'url': volunteer['url'], 'startDate': volunteer['start_date'], 'endDate': volunteer['end_date'], 'summary': volunteer['summary'], 'highlights': highlights }) return volunteering_history def get_education_info(self) -> typing.List[typing.Dict]: """ Adaptor method to get the education of the user. :return: """ education_info = [] while self.ui.add_item('education'): education_info = [] education = self.ui.get_education_info() courses = self.ui.add_list_of_items('course') education_info.append({ 'institution': education['institution'], 'url': education['url'], 'area': education['area'], 'studyType': education['study_type'], 'startDate': education['start_date'], 'endDate': education['end_date'], 'gpa': education['gpa'], 'courses': courses }) return education_info def get_awards(self) -> typing.List[typing.Dict]: """ Adaptor method to get the awards of the user. :return: """ awards = [] while self.ui.add_item('award'): award = self.ui.get_award() awards.append({ 'title': award['title'], 'date': award['date'], 'awarder': award['awarder'], 'summary': award['summary'], }) return awards def get_publications(self) -> typing.List[typing.Dict]: """ Adaptor method to get the publications of the user/ :return: """ publications = [] while self.ui.add_item('publication'): publication = self.ui.get_publication() publications.append({ 'name': publication['name'], 'publisher': publication['publisher'], 'releaseDate': publication['release_date'], 'url': publication['url'], 'summary': publication['summary'], }) return publications def get_skills(self) -> typing.List[typing.Dict]: """ Adaptor method to get the skills of the user. :return: """ skills = [] while self.ui.add_item('skill'): skill = self.ui.get_skill() keywords = self.ui.add_list_of_items('keyword') skills.append({ 'name': skill['name'], 'level': skill['level'], 'keywords': keywords, }) return skills def get_languages(self) -> typing.List[typing.Dict]: """ Adaptor method to get the user languages. :return: """ languages = [] while self.ui.add_item('language'): language = self.ui.get_language() languages.append({ 'language': language['language'], 'fluency': language['fluency'], }) return languages def get_interests(self) -> typing.List[typing.Dict]: """ Adaptor method to get the user interests. :return: """ interests = [] while self.ui.add_item('interest'): interest_name = self.ui.get_interest() keywords = self.ui.add_list_of_items('keyword') interests.append({ 'name': interest_name, 'keywords': keywords, }) return interests def get_references(self) -> typing.List[typing.Dict]: """ Adaptor method to get the user references. :return: """ references = [] while self.ui.add_item('reference'): reference = self.ui.get_reference() references.append({ 'name': reference['name'], 'reference': reference['reference'], }) return references def get_projects(self) -> typing.List[typing.Dict]: """ Adaptor method to get the user projects. :return: """ projects = [] while self.ui.add_item('project'): project = self.ui.get_project() highlights = self.ui.add_list_of_items('highlight') keywords = self.ui.add_list_of_items('keyword') roles = self.ui.add_list_of_items('role') projects.append({ 'name': project['name'], 'description': project['description'], 'highlights': highlights, 'keywords': keywords, 'startDate': project['start_date'], 'endDate': project['end_date'], 'url': project['url'], 'entity': project['entity'], 'type': project['type'], 'roles': roles }) return projects def create(self, file_path: str, file_name: str = 'resume.json') -> None: """ Get all the data from the user, create the json structure and save it. :param file_path: the path to save the file at. :param file_name: the name to save the file with. :return: None """ # gathering all the data for the json file location = self.ui.get_location() full_name, profession, image, email, phone, url, summary = self.ui.get_basics() profiles = self.get_profiles() work_history = self.get_work_history() volunteering = self.get_volunteering_history() education = self.get_education_info() awards = self.get_awards() publications = self.get_publications() skills = self.get_skills() languages = self.get_languages() interests = self.get_interests() references = self.get_references() projects = self.get_projects() # setting the data into template template = { "$schema": "https://raw.githubusercontent.com/jsonresume/resume-schema/v1.0.0/schema.json", "basics": { "name": f"{full_name}", "label": f"{profession}", "image": f"{image}", "email": f"{email}", "phone": f"{phone}", "url": f"{url}", "summary": f"{summary}", "location": location, "profiles": profiles }, "work": work_history, "volunteer": volunteering, "education": education, "awards": awards, "publications": publications, "skills": skills, "languages": languages, "interests": interests, "references": references, "projects": projects, "meta": { "canonical": "https://raw.githubusercontent.com/jsonresume/resume-schema/master/resume.json", "version": "v1.0.0", "lastModified": "2017-12-24T15:53:00" } } # creating the file with open(f'{file_path}/{file_name}', 'w') as file_to_write: json.dump(template, file_to_write, indent=4)
/resume-json-cli-0.3.0.tar.gz/resume-json-cli-0.3.0/resume_json/resume_init.py
0.61231
0.407687
resume_init.py
pypi
import typing from abc import ABC class UI(ABC): """ Base class as an interface for ui classes for resume json One should use this class as a base to know which methods to implement and what signatures one should implement, for an actual example look at BasicTui below. """ def get_location(self) -> typing.Dict: """ Method to get the location data. :return: dict with the location data """ pass def get_basics(self) -> typing.Tuple: """ Method for getting the data for all the basic information. This method returns a tuple, that is because it holds more information and data structures than other places and it's less related to each other. Thus the decision was to have it as a tuple to make sure it's still as readable as it can be while still easy to work with. :return: tuple of the basic data """ pass def add_item(self, item: str) -> bool: """ Method to check if the user want to add subject section or leave it blank. :param item: the string one wants to ask about :return: bool according to the user answer """ pass def add_another(self, item: str) -> bool: """ Method to check if the user want to add more data on the subject processed now. :param item: the string one wants to ask about :return: bool according to the user answer """ pass def get_profile(self) -> typing.Dict: """ Method to get the data about the user profile of social networks and such. :return: dict with the data about the network """ pass def get_position(self) -> typing.Dict: """ Method to get the data about the position of the user. :return: dict """ pass def get_volunteering(self) -> typing.Dict: """ Method to get information about the volunteering history of the user. :return: """ pass def add_list_of_items(self, kind: str) -> typing.List[str]: """ Method to get a list of items of kind <kind> (according to the section one is filling). :param kind: :return: """ pass def get_education_info(self) -> typing.Dict: """ Method to get the information about the education of the user. :return: """ pass def get_award(self) -> typing.Dict: """ Method to get the information about an award the user received. :return: """ pass def get_publication(self) -> typing.Dict: """ Method to get the information about a publication of the user. :return: """ pass def get_skill(self) -> typing.Dict: """ Method to get a skill of the user. :return: """ pass def get_language(self) -> typing.Dict: """ Method to get a language the user knows. :return: """ pass def get_interest(self) -> str: """ Method to get an interest of the user. :return: """ pass def get_reference(self) -> typing.Dict: """ Method to get a reference/recommendation of the user. :return: """ pass def get_project(self) -> typing.Dict: """ Method to get information about a project of the user. :return: """ pass class BasicTui(UI): """ A class that implements the UI interface methods. This is the class that works as the default implementation for the cli interface """ def get_location(self) -> typing.Dict: country = input('country code: ') region = input('region: ') city = input('city: ') address = input('address: ') postal_code = input('postal code: ') return { 'country': country, 'region': region, 'city': city, 'address': address, 'postal_code': postal_code, } def get_basics(self) -> typing.Tuple: full_name = input('full name: ') email = input('email: ') phone = input('phone: ') profession = input('profession: ') image = input('image: ') url = input('url: ') summary = input('summary: ') return full_name, profession, image, email, phone, url, summary def add_item(self, item: str) -> bool: res = input(f'want to add {item}? [no] ').lower() return res == 'y' or res == 'yes' def add_another(self, item: str) -> bool: res = input(f'want to add another {item} [no]? ').lower() return res == 'y' or res == 'yes' def get_profile(self) -> typing.Dict: network = input('network: ') username = input('username: ') url = input('url: ') return { 'network': network, 'username': username, 'url': url } def get_position(self) -> typing.Dict: company_name = input('company name: ') location = input('location: ') company_description = input('company description: ') position = input('position: ') company_url = input('company url: ') start_date = input('start date [YYYY-mm-dd]: ') end_date = input('end date [YYYY-mm-dd]: ') summary = input('summary: ') return { 'name': company_name, 'location': location, 'description': company_description, 'position': position, 'url': company_url, 'startDate': start_date, 'endDate': end_date, 'summary': summary, } def get_volunteering(self) -> typing.Dict: organization = input('volunteering organization: ') position = input('volunteering position: ') url = input('volunteering organization url: ') start_date = input('start date [YYYY-mm-dd]: ') end_date = input('end date [YYYY-mm-dd]: ') summary = input('summary: ') return { 'organization': organization, 'position': position, 'url': url, 'start_date': start_date, 'end_date': end_date, 'summary': summary, } def add_list_of_items(self, kind: str) -> typing.List[str]: items = [] while self.add_item(kind): item = input(f'{kind}: ') items.append(item) return items def get_education_info(self) -> typing.Dict: institution = input('institution: ') url = input('institution url: ') area = input('study subject: ') study_type = input('degree type (BA, Bachelor, etc.): ') start_date = input('start date [YYYY-mm-dd]: ') end_date = input('end date [YYYY-mm-dd]: ') gpa = input('gpa: ') return { 'institution': institution, 'url': url, 'area': area, 'study_type': study_type, 'start_date': start_date, 'end_date': end_date, 'gpa': gpa, } def get_award(self) -> typing.Dict: title = input('award title: ') award_date = input('date [YYYY-mm-dd]: ') awarder = input('awarder: ') summary = input('summary: ') return { 'title': title, 'date': award_date, 'awarder': awarder, 'summary': summary, } def get_publication(self) -> typing.Dict: name = input('publication name: ') publisher = input('publisher: ') release_date = input('release date: ') url = input('url: ') summary = input('summary: ') return { 'name': name, 'publisher': publisher, 'release_date': release_date, 'url': url, 'summary': summary, } def get_skill(self) -> typing.Dict: name = input('skill name: ') level = input('level: ') return { 'name': name, 'level': level, } def get_language(self) -> typing.Dict: language = input('language name: ') fluency = input('fluency: ') return { 'language': language, 'fluency': fluency, } def get_interest(self) -> str: return input('interest name: ') def get_reference(self) -> typing.Dict: name = input('name: ') reference = input('reference: ') return { 'name': name, 'reference': reference, } def get_project(self) -> typing.Dict: project_name = input('project name: ') description = input('description: ') start_date = input('start date [YYYY-mm-dd]: ') end_date = input('end dte [YYYY-mm-dd]: ') url = input('url: ') entity = input('entity: ') project_type = input('type: ') return { 'name': project_name, 'description': description, 'start_date': start_date, 'end_date': end_date, 'url': url, 'entity': entity, 'type': project_type, }
/resume-json-cli-0.3.0.tar.gz/resume-json-cli-0.3.0/resume_json/basic_tui.py
0.688259
0.663696
basic_tui.py
pypi
import json import requests from resume_json import basic_tui from resume_json.resume_init import ResumeCreate from resume_json.resume_validate import ResumeValidate from resume_json.resume_export import ResumeExport from resume_json.resume_serve import ResumeServe class ResumeJson: """ The class that is responsible for all the functionality of this package With this class one can create the json.resume, validate it, export it to files of other types and watch it through a browser. """ def __init__(self, ui=None): """ Creating the object of ResumeJson Assuming ui as the terminal one can use the default implementation of this module but if one want to use their implementation or use some kind of other UI (for example graphical one) one can send their object while using the same API as basic_tui :param ui: """ if ui is None: self.ui = basic_tui else: self.ui = ui def create(self, file_path: str, file_name: str = 'resume.json') -> None: """ Create the resume.json file. :param file_path: the full path (not including the file name and extension) to the file :param file_name: the file name to be created :return: None """ resume_json = ResumeCreate(self.ui) resume_json.create(file_path, file_name) def validate(self, file_to_validate: str, schema: str = None) -> str: """ Validates the correctness of the file according to the schema. :param file_to_validate: the full path and file name to the file one want to validate :param schema: the schema to validate against, if not provided, will be taken from the resume.json file :return: string of the error in the file or None if the file is valid """ with open(file_to_validate) as f: file_validate = json.load(f) if schema is None: schema_url = file_validate['$schema'] res = requests.get(schema_url) schema = json.loads(res.text) validate = ResumeValidate() return validate.validate(file_validate, schema) def export(self, file_path: str, json_name: str = 'resume', file_name: str = 'resume', theme: str = 'even', kind: str = 'html', language: str = 'en', theme_dir: str = None) -> None: """ Export the file to other formats This method exports the json to HTML by default, on the working directory assuming the file name to be resume.json, the theme to be `even` and the language to be English. One can change all those defaults by providing the relevant parameters. :param file_path: the file path where the json will be found, defaults to the working directory :param json_name: the name of the resume.json file one want to work on, defaults to resume :param file_name: the name of the exported file, defaults to resume :param theme: the theme one want the file to be in. can be one of ['even', 'cora', 'macchiato', 'short', 'stackoverflow'] :param kind: The type of file. Can be one of ['pdf', 'html'], defaults to html. :param language: The language of the file as a two letter code, defaults to en. :param theme_dir: the path to theme directory to work with :return: None """ export = ResumeExport(theme_dir) if kind == 'html': export.export_html(file_path, json_name, file_name, theme, language) elif kind == 'pdf': export.export_pdf(file_path, json_name, file_name, theme, language) def serve(self, json_file_path: str, json_file: str, language: str = 'en', theme_dir: str = None) -> None: """ Method to enable serving the file on localhost through the browser This method will create a cherrypy server on the local machine to serve the ones json resume and enable one to see their resume on the browser :param json_file_path: the path to the resume.json :param json_file: the name of the json resume file with extension :param language: the language two letter code to use while serving the html :param theme_dir: the path to theme directory to work with :return: None """ server = ResumeServe() server.serve(json_file_path, json_file, language, theme_dir)
/resume-json-cli-0.3.0.tar.gz/resume-json-cli-0.3.0/resume_json/json_resume.py
0.593727
0.259468
json_resume.py
pypi
from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch FONTSIZE = 10 FONT = 'Helvetica' def draw_long_string(c, x, y, text, width, fontsize = FONTSIZE): """ Draw a long string on the given c, breaking it into multiple lines as needed to fit within the given width. """ words = text.split() current_x = x current_y = y c.setFont(FONT, fontsize) for word in words: if current_x + c.stringWidth(word) > x + width: current_x = x current_y -= 0.20*inch c.drawString(current_x, current_y, word) current_x += c.stringWidth(word) + c.stringWidth(" ") return current_y def draw_skills(c, x, y, text, width): current_x = x current_y = y c.setFont(FONT, FONTSIZE) for word in text: if current_x + c.stringWidth(word.name) > x + width: current_x = x current_y -= 0.20*inch c.drawString(current_x, current_y, f"{word.name},") current_x += c.stringWidth(word.name) + c.stringWidth(" ") return current_y def draw_title_string(c, x, y, title): c.setFillColorRGB(0.5,0.5,0.5) c.setFont(FONT, 20) c.drawString(x, y, title) c.setFont(FONT, FONTSIZE) c.setFillColorRGB(0,0,0) def draw_experience_title(c, x, y, text, date): c.setFont(FONT, 13) c.drawString(x, y, text) x += c.stringWidth(text) c.setFont(FONT, FONTSIZE) c.drawString(x, y, date) def draw_credits(c, y): # ! Dont remove credits below c.setFont(FONT, 7) c.drawString(0.25*inch, y+0.1*inch, "Built with resume-maker python package by Mehmet UZEL") c.setFont(FONT, FONTSIZE) return y - 0.25*inch def draw_profile(c, profile_off, y, resume): c.setFont(FONT, 14) c.drawString(profile_off, y, resume.person.get_full_name()) y -= 0.25*inch c.setFont(FONT, 13) c.drawString(profile_off, y, resume.person.title) y -= 0.25*inch c.setFont(FONT, FONTSIZE) c.drawString(profile_off, y, resume.person.phone) y -= 0.25*inch c.drawString(profile_off, y, resume.person.email) y -= 0.2*inch c.setFont(FONT, 8) c.drawString(profile_off, y, resume.person.linkedin) y -= 0.2*inch c.drawString(profile_off, y, resume.person.github) y -= 0.5*inch c.setFont(FONT, FONTSIZE) return y def draw_skills_section(c, profile_off, y, resume): draw_title_string(c, profile_off, y, 'Skills') y -= 0.25*inch y = draw_skills(c, profile_off, y, resume.skills, 2.75*inch) return y - 0.5*inch def draw_about_section(c, profile_off, y, resume): draw_title_string(c, profile_off, y, 'About') y -= 0.25*inch y = draw_long_string(c, profile_off, y, resume.person.about, 2.75*inch) return y - 0.5*inch def draw_education_section(c, profile_off, y, resume): draw_title_string(c, profile_off, y, 'Education') y -= 0.25*inch for education in resume.educations: c.drawString(profile_off, y, f'{education.name} ({education.start} - {education.end})') y -= 0.25*inch y = draw_long_string(c, profile_off+0.1*inch, y, education.description, 2.75*inch, 8.5) c.setFont(FONT, FONTSIZE) y -= 0.25*inch return y - 0.25*inch def draw_language_section(c, profile_off, y, resume): draw_title_string(c, profile_off, y, 'Languages') y -= 0.25*inch for language in resume.languages: c.drawString(profile_off, y, f'{language.name} ({language.level})') y -= 0.25*inch return y - 0.25*inch def draw_experience_section(c, experience_off, y, resume): draw_title_string(c, experience_off, y, 'Experience') y -= 0.25*inch c.drawString(experience_off, y, f'Total Years of Experience : {resume.total_years_of_experience()} years') y -= 0.25*inch for experience in resume.experiences: draw_experience_title(c,experience_off,y,f'{experience.company} - {experience.title}', f'({experience.start} - {experience.end})') y -= 0.25*inch y = draw_long_string(c, experience_off+0.25*inch, y, experience.description, 4*inch) y -= 0.25*inch for project in experience.projects: c.drawString(experience_off+0.25*inch, y, f'{project.name}') y -= 0.25*inch y = draw_long_string(c, experience_off+0.35*inch, y, project.description, 3.9*inch) y -= 0.25*inch return y - 0.25*inch def draw_projects_section(c, project_off, y, resume): y -= 0.25*inch draw_title_string(c, project_off, y, 'Personal Projects') y -= 0.5*inch for project in resume.projects: c.setFont(FONT, 13) c.drawString(project_off, y, f'{project.name}') c.setFont(FONT, FONTSIZE) y -= 0.25*inch y = draw_long_string(c, project_off+0.25*inch, y, project.description, 7.5*inch) y -= 0.5*inch return y - 0.25*inch def generate_pdf(resume, filename): c = Canvas(filename) INITIAL_Y = 11.25*inch y = INITIAL_Y # start drawing at this y coordinate profile_off = 0.3*inch experience_off = 3.75*inch project_off = 0.3*inch # ! Dont remove credits below y = draw_credits(c,y) # Draw the name and contact information y = draw_profile(c, profile_off, y, resume) # Draw the skills y = draw_skills_section(c, profile_off, y, resume) # Draw the About y = draw_about_section(c, profile_off, y, resume) # Draw the education y = draw_education_section(c, profile_off, y, resume) # Draw the languages y = draw_language_section(c, profile_off, y, resume) y = INITIAL_Y # Draw the experiences y = draw_experience_section(c, experience_off, y, resume) c.showPage() y = INITIAL_Y # Draw the projects y = draw_projects_section(c, project_off, y, resume) c.save()
/resume-maker-0.1.0.tar.gz/resume-maker-0.1.0/resume_maker/pdf_converter.py
0.534127
0.404037
pdf_converter.py
pypi
class ScanResult(object): @property def fileName(self): return self.__fileName @fileName.setter def fileName(self, value): self.__fileName = value @property def personName1(self): return self.__personName1 @personName1.setter def personName1(self, value): self.__personName1 = value @property def personName2(self): return self.__personName2 @personName2.setter def personName2(self, value): self.__personName2 = value @property def phoneNumbers(self): return self.__phoneNumbers @phoneNumbers.setter def phoneNumbers(self, value): self.__phoneNumbers = value @property def emailIDs(self): return self.__emailIDs @emailIDs.setter def emailIDs(self, value): self.__emailIDs = value @property def school1(self): return self.__school1 @school1.setter def school1(self, value): self.__school1 = value @property def school2(self): return self.__school2 @school2.setter def school2(self, value): self.__school2 = value @property def skills(self): return self.__skills @skills.setter def skills(self, value): self.__skills = value @property def qualification(self): return self.__qualification @qualification.setter def qualification(self, value): self.__qualification = value @property def institutes1(self): return self.__institutes1 @institutes1.setter def institutes1(self, value): self.__institutes1 = value @property def institutes2(self): return self.__institutes2 @institutes2.setter def institutes2(self, value): self.__institutes2 = value @property def institutes3(self): return self.__institutes3 @institutes3.setter def institutes3(self, value): self.__institutes3 = value @property def education(self): return self.__education @education.setter def education(self, value): self.__education = value @property def companys1(self): return self.__companys1 @companys1.setter def companys1(self, value): self.__companys1 = value @property def companys2(self): return self.__companys2 @companys2.setter def companys2(self, value): self.__companys2 = value @property def workexp(self): return self.__workexp @workexp.setter def workexp(self, value): self.__workexp = value
/resume_parser_mind-0.0.1-py3-none-any.whl/resume_parser/ScanResult.py
0.575827
0.239416
ScanResult.py
pypi
from dataclasses import dataclass from importlib.resources import files import json from pathlib import Path import typer from . import utils from . import pdf from . import html app = typer.Typer(help="CLI tool to easily setup a new resume.") @dataclass class Options: """Global options.""" resume: dict theme: Path @app.callback() def main( resume: Path = typer.Option( "resume.json", help="Path to the JSON resume.", ), theme: str = typer.Option( "", help="Override the theme.", ), ) -> None: Options.resume = json.loads(resume.read_text()) Options.theme = utils.find_theme(theme or Options.resume.get("theme", "base")) @app.command() def validate( schema: Path = typer.Option( files("resume_pycli").joinpath("schema.json"), exists=True, dir_okay=False, help="Path to a custom schema to validate against.", ), ) -> None: """Validate resume's schema.""" schema_file = json.loads(schema.read_text()) err = utils.validate(Options.resume, schema_file) if err: typer.echo(err, err=True) raise typer.Exit(code=1) @app.command() def serve( host: str = typer.Option( "localhost", help="Bind address.", ), port: int = typer.Option( 4000, help="Bind port.", ), browser: bool = typer.Option( False, help="Open in web browser.", ), debug: bool = typer.Option( False, help="Run in debug mode.", ), ) -> None: """Serve resume.""" if browser: typer.launch(f"http://{host}:{port}/") html.serve( resume=Options.resume, theme=Options.theme, host=host, port=port, debug=debug, ) @app.command() def export( to_pdf: bool = typer.Option( True, "--pdf", "--no-pdf", help="Export to PDF.", ), pdf_backend: pdf.Backend = typer.Option( "playwright", help="Select PDF engine.", ), to_html: bool = typer.Option( True, "--html", "--no-html", help="Export to HTML.", ), output: Path = typer.Option( "public", help="Specify the output directory.", ), ) -> None: """Export to HTML and PDF.""" output.mkdir(parents=True, exist_ok=True) if to_html: html.export( resume=Options.resume, theme=Options.theme, output=output, ) if to_pdf: pdf.export( resume=Options.resume, theme=Options.theme, output=output, engine=pdf_backend, )
/resume_pycli-4.1.1-py3-none-any.whl/resume_pycli/cli.py
0.690872
0.150216
cli.py
pypi
from datetime import datetime from babel.dates import format_date import resumejson_converter.utils.templates as utemplates def dateedit(startDate, endDate): """ Return the date in special format. If only the start date is specified: 2019 - Auj. >>> dateedit("2019-01-01", "") "2019 - Auj." Else if the year of the start date and the year of the end data are the same: 2019 >>> dateedit("2019-01-01", "2019-02-02") "2019" Else if the year of start date are not the same that the year of the end date: 2017 - 2019 >>> datetime("2019-01-01", "2017-05-01") "2019 - 2017" """ startDateTime = datetime.strptime(startDate, '%Y-%m-%d') if endDate == "": return "{:%Y} - Auj.".format(startDateTime) else: endDateTime = datetime.strptime(endDate, '%Y-%m-%d') diffDate = endDateTime - startDateTime if startDateTime.strftime("%Y") == endDateTime.strftime("%Y"): return "{:%Y}".format(startDateTime) else: return "{:%Y} - {:%Y}".format(startDateTime, endDateTime) def datediff(title, startDate, endDate, showDiff=True): """ Return time passed between two dates after a text. >>> datediff("Hello World", "2019-01-02", "2019-06-02") 'Hello World - 5 mois' """ if showDiff and endDate != "": startDateTime = datetime.strptime(startDate, '%Y-%m-%d') endDateTime = datetime.strptime(endDate, '%Y-%m-%d') diffDate = endDateTime - startDateTime period = utemplates.td_format(diffDate).split(',')[0] return "{} - {}".format(title, period) else: return "{}".format(title) def birthday(date): """ Return a date in french format. >>> birthday("1990-10-25") '25 octobre 1990' """ date = datetime.strptime(date, '%Y-%m-%d') return format_date(date, format='long', locale='fr') def clean(phone): """ Return phone number in french format. >>> clean("0011223344") '00 11 22 33 44' """ phone = [phone[num:num+2] for num in range(0, len(phone), 2)] return " ".join(phone)
/resumejson_converter-0.3-py3-none-any.whl/resumejson_converter/filters.py
0.88868
0.362828
filters.py
pypi
import torch from torch import nn import torch.nn.functional as F from tokenizer import Tokenizer class TextCNN(nn.Module): def __init__(self, embedding_feature=128): """ create TextCNN based torch """ super(TextCNN, self).__init__() self.tokenizer = Tokenizer() self.embedding = nn.Embedding(len(self.tokenizer.vocab), embedding_feature) self.kernel_sizes = [2, 3, 4] self.output_channel = 10 # 对文本数据做二维卷积 # input channel always equal 1 in NLP. self.conv2s = nn.ModuleList([nn.Conv2d(1, self.output_channel, kernel_size=(kernel_size, embedding_feature)) for kernel_size in self.kernel_sizes]) self.dropout = nn.Dropout(0.1) # only single item is needed for binary cross entropy. self.fc = nn.Linear(self.output_channel * len(self.kernel_sizes), 1) @staticmethod def conv_and_maxpool(x, conv_layer): """ after embedding, x.shape: (batch_size, seq_len, feature) -> x.unsqueeze(1) -> shape: (batch_size, 1, seq_len, feature) -> nn.Conv2d(x) -> shape: (batch_size, output_channels, seq_len - kernel_size + 1, 1) -> squeeze(3) -> shape: (batch_size, output_channels, seq_len - kernel_size + 1) -> max_pool1d -> shape: (batch_size, output_channels, 1) -> squeeze(2) -> shape: (batch_size, output_channels) """ x = x.unsqueeze(1) x = conv_layer(x) x = x.squeeze(3) x = F.max_pool1d(x, kernel_size=x.shape[2]) x = x.squeeze(2) return x def forward(self, x, labels=None): x = self.embedding(x) x = torch.cat([self.conv_and_maxpool(x, conv_layer=conv) for conv in self.conv2s], dim=1) x = self.dropout(x) logit = torch.sigmoid(self.fc(x).squeeze(1)) if labels is None: return logit else: loss = F.binary_cross_entropy(logit, labels) return loss, logit def predict(self, text, max_len=11, padding=True): """ predict single sample. """ x = self.tokenizer.tokenize(text, max_len=max_len, padding=padding) x = torch.tensor([x], dtype=torch.long) # Batch Computation Format self.eval() with torch.no_grad(): logit = self(x) return round(logit[0].item(), 3) if __name__ == "__main__": x = torch.tensor([list(range(10))], dtype=torch.long) y = torch.tensor([0], dtype=torch.float) cnn = TextCNN() print(cnn(x, y)) # cnn.load_state_dict(torch.load("/home/zhukai/PycharmProjects/ResumeParse/checkpoint/cnn_20742.pt")) print(cnn.predict("电话是有效的姓名。"))
/resumename-1.0.4-py3-none-any.whl/nameparser/model.py
0.912378
0.533094
model.py
pypi
from . import settings from copy import copy class SampleDataConsumer: """ Local class which identifies which consumer registered for what device """ def __init__(self, id, q): self.id = id self.q = q def registerConsumer(id, q): """ Registers a consumer-queue to receive the sample-data of a specific device. This method is called by sample-data-consumers. Args: id: <int> : Unique id of a device <Device.id>. Indicates from which specific device, received sample-data must be put into the registered <queue> q: <queue> The queue into which received sample-data will be put. """ settings._consumer_list.append(SampleDataConsumer(id, q)) def unregisterConsumer(id, q): """ Unregisters a consumer-queue associated with a file-writer or plotter object. This method is called by close-methods of the sample-data-consumers. Args: id: <int> : Unique id of a device <Device.id>. Indicates from which specific device, received sample-data must be put into the registered <queue> q: <queue> The queue object which has to be removed from the global consumer list. """ num_consumers = len(settings._consumer_list) for i in range(num_consumers): if settings._consumer_list[i].id == id: if settings._consumer_list[i].q == q: idx_remove = copy(i) settings._consumer_list.pop(idx_remove) def putSampleData(id, data): """ Puts a <SampleData>-object, coming from device <Device.id> into the queues of registered consumers. This method is called by sample-data-producers. Args: id: <int> : Unique id of the device (<Device>.id), which forwards received sample-data to the sample-data-server. data <SampleData> The sample-data. """ num_consumers = len(settings._consumer_list) for i in range(num_consumers): if (settings._consumer_list[i].id == id): settings._consumer_list[i].q.put(data)
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/sample_data_server.py
0.743447
0.222996
sample_data_server.py
pypi
from enum import Enum from .error import TMSiError, TMSiErrorCode class FileFormat(Enum): none = 0 poly5 = 1 xdf = 2 lsl = 3 class FileWriter: """ <FileWriter> implements a file-writer for writing sample-data, captured during a measurement, to a specific file in a specific data-format. Args: data_format_type : <FileFormat> Specifies the data-format of the file. This can be poly5, gdf+ or gdf. filename : <string> The path and name of the file, into which the measurement-data must be written. """ def __init__(self, data_format_type, filename, add_ch_locs=False): if (data_format_type == FileFormat.poly5): from .file_formats.poly5_file_writer import Poly5Writer self._data_format_type = data_format_type self._file_writer = Poly5Writer(filename) elif (data_format_type == FileFormat.xdf): from .file_formats.xdf_file_writer import XdfWriter self._data_format_type = data_format_type self._file_writer = XdfWriter(filename, add_ch_locs) elif (data_format_type == FileFormat.lsl): from .file_formats.lsl_stream_writer import LSLWriter self._data_format_type = data_format_type self._file_writer = LSLWriter(filename) else: print("Unsupported data format") raise TMSiError(TMSiErrorCode.api_incorrect_argument) def open(self, device): """ Opens a file-writer session. Must be called BEFORE a measurement is started. Links a 'Device' to a 'Filewriter'-instance and prepares for the measurement that will start. In the open-method the file-writer-object will prepare for the receipt of sample-data from the 'Device' as next: - Retrieve the configuration (e.g. channel-list, sample_rate) from the 'Device' to write to the file and to prepare for the receipt of sample-data. - Register at the 'sample_data_server' for receipt of the sample-data. - Create a dedicated sampling-thread, which is responsible to processes during the measurement the incoming sample-data. """ self._file_writer.open(device) def close(self): """ Closes an ongoing file-writer session. Must be called AFTER a measurement is stopped. """ self._file_writer.close()
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/file_writer.py
0.729712
0.302301
file_writer.py
pypi
from enum import Enum, unique @unique class DeviceInterfaceType(Enum): none = 0 usb = 1 network = 2 wifi = 3 docked = 4 optical = 5 bluetooth = 6 @unique class DeviceState(Enum): disconnected = 0 connected = 1 sampling = 2 @unique class ChannelType(Enum): unknown = 0 UNI = 1 BIP = 2 AUX = 3 sensor = 4 status = 5 counter = 6 all_types = 7 @unique class MeasurementType(Enum): normal = 0 impedance = 1 @unique class ReferenceMethod(Enum): common = 0 average = 1 @unique class ReferenceSwitch(Enum): fixed=0 auto=1 class DeviceChannel: """ 'DeviceChannel' represents a device channel. It has the next properties: type : 'ChannelType' Indicates the group-type of a channel. sample_rate : 'int' The curring sampling rate of the channel during a 'normal' measurement. name : 'string' The name of the channel. unit_name : 'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel. enabled : 'bool' Indicates if a channel is enabled for measuring Note: The properties 'name' and 'enabled' can be modified. The other properties are read-only. """ def __init__(self, type, sample_rate, name, unit_name, enabled, sensor = None): self.__type = type self.__sample_rate = sample_rate self.__unit_name = unit_name self.__name = name self.__enabled = enabled self.__sensor = sensor @property def type(self): """'ChannelType' Indicates the group-type of a channel.""" return(self.__type) @property def sample_rate(self): """'int' The curring sampling rate of the channel during a 'normal' measurement.""" return(self.__sample_rate) @property def name(self): """'string' The name of the channel.""" return self.__name @name.setter def name(self, var): """'string' Sets the name of the channel.""" self.__name = var @property def unit_name(self): """'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel.""" return self.__unit_name @property def enabled(self): """'bool' Indicates if a channel is enabled for measuring""" return self.__enabled @enabled.setter def enabled(self, var): """'bool' Enables (True) or disables (False) a channel for measurement""" self.__enabled = var @property def sensor(self): """'DeviceSensor' contains an object if a sensor is attached to the channel.""" return(self.__sensor) class DeviceInfo: """ 'DeviceInfo' holds the static device information. It has the next properties: ds_interface : 'DeviceInterfaceType' Indicates interface-type between the PC and the docking station. dr_interface : 'DeviceInterfaceType' Indicates interface-type between the PC / docking station and the data recorder. ds_serial_number : 'int' The serial number of the docking station. dr_serial_number : 'int' The serial number of the data recorder. """ def __init__(self, ds_interface = DeviceInterfaceType.none, dr_interface = DeviceInterfaceType.none): self.__ds_interface = ds_interface self.__dr_interface = dr_interface self.__ds_serial_number = 0 self.__dr_serial_number = 0 @property def ds_interface(self): """ds_interface : 'DeviceInterfaceType' Indicates interface-type between the PC and the docking station. """ return self.__ds_interface @property def dr_interface(self): """dr_interface : 'DeviceInterfaceType' Indicates interface-type between the PC / docking station and the data recorder. """ return self.__dr_interface @property def ds_serial_number(self): """'int' The serial number of the docking station.""" return self.__ds_serial_number @property def dr_serial_number(self): """'int' The serial number of the data recorder.""" return self.__dr_serial_number class DeviceStatus: """ 'DeviceStatus' holds the runtime device information. It has the next properties: state : 'DeviceState' Indicates the connection-state towards the device which can be : - connected : The connection to the device is open - disconnected : The connection to the device is closed - sampling : The connection to the device is open and the device has an ongoing measurement active. error : 'int' The return-code of the last made call to the device. A '0' indicates that the call was succesfull. """ def __init__(self, state, error): self.__state = state self.__error = error @property def state(self): """'DeviceState' Indicates the connection-state towards the device""" return self.__state @property def error(self): """'int' The return-code of the last made call to the device.""" return self.__error class DeviceSensor: """ 'DeviceSensor' represents the sensor-data of a channel. It has the next properties: channel_list_idx : 'int' Index of the channel in the total channel list. Index starts at 0. The total channel list can be accessed with [Device.config.channels] id : 'int' ID-code of the sensor used to identify BIP-sensors. serial_nr : 'int' Serial number of an attached AUX-sensor. product_id : 'int' Product identified of an attached AUX-sensor. exp : 'int' Exponent for the unit, e.g. milli = -3 this gives for a unit_name V a result mV. name : 'string' The name of the sensor-channel. unit_name : 'string' The name of the unit (e.g. 'Volt) of the sensor-data. """ def __init__(self, channel_list_idx, id, serial_nr, product_id, name, unit_name, exp): self.__channel_list_idx = channel_list_idx self.__id = id self.__serial_nr = serial_nr self.__name = name self.__unit_name = unit_name self.__product_id = product_id self.__exp = exp @property def channel_list_idx(self): """''int' Index of the channel in the total channel list.""" return(self.__channel_list_idx) @property def id(self): """'int' ID-code of the sensor used to identify BIP-sensors.""" return(self.__id) @property def serial_nr(self): """'int' Serial number of an attached AUX-sensor""" return self.__serial_nr @property def product_id(self): """'int' Product identified of an attached AUX-sensor""" return self.__product_id @property def name(self): """'string' The name of the sensor-channel.""" return self.__name @property def unit_name(self): """'string' Exponent for the unit, e.g. milli = -3 this gives for a unit_name V a result mV. """ return self.__unit_name @property def exp(self): """'int' The name of the channel.""" return self.__exp class DeviceConfig: """'DeviceConfig' holds the actual device configuration""" def __init__(self, sample_rate, num_channels): pass @property def num_channels(self): """'int' The total number of channels (enabled and disabled)""" pass @property def channels(self): """'list DeviceChannel' The total list of channels (enabled and disabled)""" pass @channels.setter def channels(self, ch_list): """Updates the channel lists in the device. Args: ch_list : 'list DeviceChannel' The channel-properties 'enabled' and 'name' can be modified. The other channel-properties are read-only. Note: 'ch_list' must contain all channels (enabled and disabled), in the same sequence as retrieved with 'Device.config.channels' It is advised to "refresh" the applications' local "variables" after the channel list has been updated. """ pass @property def base_sample_rate(self): """'int' The active base-sample-rate of the device""" pass @base_sample_rate.setter def base_sample_rate(self, sample_rate): """Sets the base-sample-rate of the device. Args: sample_rate : 'int' new base sample rate Note: Upon a change of the base-sample-rate, automatically the sample-rate of the channel-type-groups (and thus also the sample-rate of every channel) changes. It is advised to "refresh" the applications' local "variables" after the base-sample-rate has been updated. """ pass @property def sample_rate(self): """'int' The rate of the current configuration, with which sample-sets are sent during a measurement. """ pass def get_sample_rate(self, channel_type): """'int' the sample-rate of the specified channel-type-group. Args: channel_type : 'ChannelType' The channel-type-group. """ pass def set_sample_rate(self, channel_type, base_sample_rate_divider): """Sets the sample-rate of the specified channel-type-group. Args: channel_type : 'ChannelType' The channel-type-group of which the sample-rate must be updated. It is possible to set all channels to the same sample-rate within one call. Then 'ChannelType.all_types' must be used. base_sample_rate_divider: 'int' The divider to indicate to what fraction of the active base-sample-rate the sample-rate of the channel-type-group must be set. Only the values 1, 2, 4 and 8 are possible. For example if the base-sample-rate=4000 and base_sample_rate_divider=8, the sample-rate will become 4000/8 = 500 Hz Note: Upon a change of the sample-rate of a channel-type-group, automatically the sample-rate of the channels of that channel-type are updated. It is advised to "refresh" the applications' local "variables" after the sample-rate of a channel-type-group has been updated. """ pass def set_interface_type(self, dr_interface_type): """Changes the configured interface type of the device Args: interface_type: 'DeviceInterfaceType' The interface type that needs to be updated. """ pass @property def reference_method(self): """ 'ReferenceMethod' the reference method applied to the UNI channels""" pass @reference_method.setter def reference_method(self, reference_type): """Sets the reference method for the UNI channels Args: reference_type: 'ReferenceMethod' the type of reference method that should be used for measuring the UNI channels """ class Device: """ 'Device' handles the connection to a TMSi Measurement System like the SAGA. The Device class interfaces with the measurement system to : - open/close a connection to the system - configure the system - forward the received sample data to Python-clients for display and/or storage. Args: ds-interface: The interface-type between the PC and the docking-station. This might be 'usb' or 'network'' dr-interface: The interface-type between the docking-station and data recorder. This might be 'docked', 'optical' or 'wifi' """ @property def id(self): """ 'int' : Unique id within all available devices. The id can be used to register as a client at the 'sample_data_server' for retrieval of sample-data of a specific device """ pass @property def info(self): """ 'class DeviceInfo' : Static information of a device like used interfaces, serial numbers """ pass @property def status(self): """ 'class DeviceStatus' : Runtime information of a device like device state """ pass @property def config(self): """ 'class DeviceConfig' : The configuration of a device which exists out of individual properties (like base-sample-rate) and the total channel list (with enabled and disabled channels) """ pass @property def channels(self): """ 'list of class DeviceChannel' : The list of enabled channels. Enabled channels are active during an 'normal' measurement. """ pass @property def imp_channels(self): """ 'list of class DeviceChannel' : The list of impedance channels. Impedance channels are active during an 'impedance' measurement. """ pass @property def sensors(self): """ 'list of class DeviceSensor' : The complete list of sensor-information for the sensor-type channels : BIP and AUX """ @property def datetime(self): """ 'datetime' Current date and time of the device """ pass @datetime.setter def datetime(self, dt): """ 'datetime' Sets date and time of the device """ pass def open(self): """ Opens the connection to the device. The open-function will first initiate a discovery on attached systems to the PC based on the interface-types which were registered upon the creation of the Device-object. A connection will be established with the first available system. The functionailty a device offers will only be available when a connection to the system has been established. """ pass def close(self): """ Closes the connection to the device. """ pass def start_measurement(self, measurement_type = MeasurementType.normal): """ Starts a measurement on the device. Clients, which want to receive the sample-data of a measurement, must be registered at the 'sample data server' before the measurement is started. Args: measurement_type : - MeasurementType.normal (default), starts a measurement with the 'enabled' channels: 'Device.channels[]'. - MeasurementType.impedance, starts an impedance-measurement with all 'impedance' channels: 'Device.imp_channels[]' """ pass def stop_measurement(self): """ Stops an ongoing measurement on the device.""" pass def set_factory_defaults(self): """ Initiates a factory reset to restore the systems' default configuration.""" pass def load_config(self, filename): """ Loads a device configuration from file into the attached system. 1. The device configuration is read from the specified file. 2. This configuration is uploaded into the attached system. 3. The configuration is downloaded from the system to be sure that the configuration of the Python-interface is in sync with the configuration of the device. Note : It is advised to "refresh" the applications' local "variables" after a new device configuration has been load. Args: filename : path and filename of the file that must be loaded """ pass def save_config(self, filename): """ Saves the current device configuration to file. Args: filename : path and filename of the file to which the current device configuration must be saved. """ pass def update_sensors(self): """ Called when sensors have been attached or detached to/from the device. The complete configuration including the new sensor-configuration is reloaded from the device. Note: It is advised to "refresh" the applications' local "variables" after the the complete configuration has been reloaded. """ pass
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/device.py
0.858822
0.328072
device.py
pypi
from ...device import DeviceInterfaceType, DeviceState, DeviceConfig, ChannelType, DeviceChannel, DeviceSensor, ReferenceMethod, ReferenceSwitch _TMSI_DEVICE_ID_NONE = 0xFFFF class SagaConst: TMSI_DEVICE_ID_NONE = 0xFFFF class SagaInfo(): """ 'DeviceInfo' holds the static device information. It has the next properties: ds_interface : 'DeviceInterfaceType' Indicates interface-type between the PC and the docking station. dr_interface : 'DeviceInterfaceType' Indicates interface-type between the PC / docking station and the data recorder. ds_serial_number : 'int' The serial number of the docking station. dr_serial_number : 'int' The serial number of the data recorder. """ def __init__(self, ds_interface = DeviceInterfaceType.none, dr_interface = DeviceInterfaceType.none): self.ds_interface = ds_interface self.dr_interface = dr_interface self.id = _TMSI_DEVICE_ID_NONE; self.state = DeviceState.disconnected class SagaConfig(DeviceConfig): """'DeviceConfig' holds the actual device configuration""" def __init__(self): self._parent = None self._base_sample_rate = 0 # base sample reate in Hz self._configured_interface = DeviceInterfaceType.none self._triggers = 0 # 0= Disabled, 1= external triggers enabled self._reference_method = 0 # 0= Common reference, 1=average reference self._auto_reference_method = 0 # 0= fixed method, 1= autoswitch to average reference when CREF is out of range self._dr_sync_out_divider = -1 # SetBaseSampleRateHz/SyncOutDiv, -1 = marker button self._dr_sync_out_duty_cycle = 0 # DR Sync dutycycle self._repair_logging = 0 # 0 = Disabled, 1 = BackupLogging enabled, self._num_channels = 0; # Total number of channels : active and inactive self._channels = [] # Total channel list : active and inactive self._sample_rates = [] # List with sample_rate per channel-type self._num_sensors = 0 # Number of sensors for chan_type in ChannelType: self._sample_rates.append(SagaSampleRate(chan_type)) def get_sample_rate(self, chan_type): """'int' the sample-rate of the specified channel-type-group. Args: channel_type : 'ChannelType' The channel-type-group. """ return self._sample_rates[chan_type.value].sample_rate def set_sample_rate(self, chan_type, bsr_div): """Sets the sample-rate of the specified channel-type-group. Args: channel_type : 'ChannelType' The channel-type-group of which the sample-rate must be updated. It is possible to set all channels to the same sample-rate within one call. Then 'ChannelType.all_types' must be used. base_sample_rate_divider: 'int' The divider to indicate to what fraction of the active base-sample-rate the sample-rate of the channel-type-group must be set. Only the values 1, 2, 4 and 8 are possible. For example if the base-sample-rate=4000 and base_sample_rate_divider=8, the sample-rate will become 4000/8 = 500 Hz Note: Upon a change of the sample-rate of a channel-type-group, automatically the sample-rate of the channels of that channel-type are updated. It is advised to "refresh" the applications' local "variables" after the sample-rate of a channel-type-group has been updated. """ if (bsr_div == 1) or (bsr_div == 2) or (bsr_div == 4) or (bsr_div == 8): bsr_shift = 0 while (bsr_div > 1): bsr_shift += 1 bsr_div /= 2 for ch in self._channels: if ((ch.type == chan_type) or (chan_type == ChannelType.all_types) and (ch.chan_divider != -1)): # Only update the chan_divider of active channels if (ch.chan_divider != -1): ch.chan_divider = bsr_shift if (self._parent != None): self._parent._update_config() else: print('\nProvided base_sample_rate_divider is invalid. Sample rate can not be updated.\n') @property def base_sample_rate(self): """'int' The active base-sample-rate of the device""" return self._base_sample_rate @base_sample_rate.setter def base_sample_rate(self, var): """Sets the base-sample-rate of the device. Args: sample_rate : 'int' new base sample rate Note: Upon a change of the base-sample-rate, automatically the sample-rate of the channel-type-groups (and thus also the sample-rate of every channel) changes. It is advised to "refresh" the applications' local "variables" after the base-sample-rate has been updated. """ if (var == 4000) or (var == 4096): if self._base_sample_rate != var: # The device does not support a configuration with different base # sample rates for sample rate and sync out. Hence sync out config # has to be update as well sync_out_freq=(self._base_sample_rate/self._dr_sync_out_divider) self._base_sample_rate = var self.set_sync_out_config(freq=sync_out_freq) else: print('\nProvided base_sample_rate is invalid. Sample rate can not be updated.\n') @property def sample_rate(self): """<int> The rate of the current configuration, with which sample-sets are sent during a measurement. This always equals the sample-rate of the COUNTER-channel. """ return self._sample_rates[ChannelType.counter.value].sample_rate @property def configured_interface(self): return self._configured_interface def set_interface_type(self, dr_interface_type): """Changes the configured interface type of the device. Args: dr_interface_type: 'DeviceInterfaceType' The interface type that needs to be updated. Note: The interface type switch applies to the DR-DS interface type. Interface types that can be configured on SAGA are docked, optical and wifi. """ if dr_interface_type.value != self._configured_interface: print('DR-DS interface is changed to: ') print(dr_interface_type) self._configured_interface = dr_interface_type.value if (self._parent != None): self._parent._update_config() @property def num_channels(self): """'int' The total number of channels (enabled and disabled)""" return self._num_channels @property def channels(self): """'list DeviceChannel' The total list of channels (enabled and disabled)""" chan_list = [] for ch in self._channels: sensor = ch.sensor if (ch.sensor != None): sensor = DeviceSensor(ch.sensor.idx_total_channel_list, ch.sensor.id, ch.sensor.serial_nr, ch.sensor.product_id, ch.sensor.name, ch.sensor.unit_name, ch.sensor.exp) dev_ch = DeviceChannel(ch.type, ch.sample_rate, ch.alt_name, ch.unit_name, (ch.chan_divider != -1), sensor) chan_list.append(dev_ch) return chan_list @channels.setter def channels(self, var): """Updates the channel lists in the device. Args: ch_list : 'list DeviceChannel' The channel-properties 'enabled' and 'name' can be modified. The other channel-properties are read-only. Note: 'ch_list' must contain all channels (enabled and disabled), in the same sequence as retrieved with 'Device.config.channels' It is advised to "refresh" the applications' local "variables" after the channel list has been updated. """ for idx, channel in enumerate(var): if (self._channels[idx].type.value < ChannelType.status.value): self._channels[idx].alt_name = channel.name if (channel.enabled == True): if (self._sample_rates[self._channels[idx].type.value].sample_rate != 0): self._channels[idx].sample_rate = self._sample_rates[self._channels[idx].type.value].sample_rate self._channels[idx].chan_divider = self._sample_rates[self._channels[idx].type.value].chan_divider else: self._sample_rates[self._channels[idx].type.value].sample_rate = self._sample_rates[ChannelType.counter.value].sample_rate self._sample_rates[self._channels[idx].type.value].chan_divider = self._sample_rates[ChannelType.counter.value].chan_divider self._channels[idx].sample_rate = self._sample_rates[self._channels[idx].type.value].sample_rate self._channels[idx].chan_divider = self._sample_rates[self._channels[idx].type.value].chan_divider else: self._channels[idx].chan_divider = -1 if (self._parent != None): self._parent._update_config() @property def reference_method(self): """ 'ReferenceMethod' the reference method applied to the UNI channels, 'ReferenceSwitch' the switching of reference mode when common reference is disconnected""" return ReferenceMethod(self._reference_method).name, ReferenceSwitch(self._auto_reference_method).name @reference_method.setter def reference_method(self, reference_type): """Sets the reference method for the UNI channels Args: reference_type: 'ReferenceMethod' the type of reference method that should be used for measuring the UNI channels 'ReferenceSwitch' the switching of reference mode when common reference is disconnected """ if not type(reference_type) is tuple: if isinstance(reference_type, ReferenceMethod): self._reference_method=reference_type.value elif isinstance(reference_type, ReferenceSwitch): self._auto_reference_method=reference_type.value else: for ind in range(len(reference_type)): if isinstance(reference_type[ind], ReferenceMethod): self._reference_method=reference_type[ind].value elif isinstance(reference_type[ind], ReferenceSwitch): self._auto_reference_method=reference_type[ind].value if (self._parent != None): self._parent._update_config() @property def triggers(self): """'Boolean', true when triggers are enabled or false when disabled""" return bool(self._triggers) @triggers.setter def triggers(self, enable_triggers): """Sets the triggers to enabled or disabled""" self._triggers=enable_triggers if (self._parent != None): self._parent._update_config() @property def repair_logging(self): """Boolean, true in case samples are logged on Recorder for repair in case of data loss""" return self._repair_logging @repair_logging.setter def repair_logging(self, enable_logging): """Sets repair logging to enabled or disabled""" self._repair_logging=enable_logging if (self._parent != None): self._parent._update_config() def get_sync_out_config(self): """Sync out configuration, shows whether sync out is in marker mode or square wave mode with corresponding frequency and duty cycle""" if self._dr_sync_out_divider==-1: freq=-1 else: freq=(self._base_sample_rate/self._dr_sync_out_divider) return self._dr_sync_out_divider==-1, freq, self._dr_sync_out_duty_cycle/10 def set_sync_out_config(self, marker=False, freq=None, duty_cycle=None): """Set sync out to marker mode or square wave mode with corresponding frequency and duty cycle""" if marker: self._dr_sync_out_divider=-1 else: if freq: self._dr_sync_out_divider=round(self._base_sample_rate/freq) if duty_cycle: self._dr_sync_out_duty_cycle=duty_cycle*10 if (self._parent != None): self._parent._update_config() class SagaSensor(): """ <SagaSensor> represents the sensor-data of a channel. It has the next properties: offset : <float> Offset for the seonsor-channel. gain : <float> Value to convert the sensor value to the correct unit value exp : <int> Exponent for the unit, e.g. milli = -3 this gives for a unit_name V a result mV. name : <string> The name of the seonsor-channel. unit_name : <string> The name of the unit (e.g. 'μVolt) of the sensor-data. """ def __init__(self): self.idx_total_channel_list = -1 self.id = -1 self.manufacturer_id = 0 self.serial_nr = 0 self.product_id = 0 self.offset = 0 self.gain =1 self.exp = 0 self.__name = "" self.__unit_name = "" @property def name(self): """'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel.""" return self.__name @name.setter def name(self, bname): self.__name = "" new_name = bytearray() for i in range (len(bname)): if bname[i] > 127: new_name.append(194) #0xC2 new_name.append(bname[i]) if len(new_name) > 0: self.__name = new_name.decode('utf8').rstrip('\x00') @property def unit_name(self): """'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel.""" return self.__unit_name @unit_name.setter def unit_name(self, bname): # A unit-name can start with the micro-character (0xB5). In that case must # the micro-character be converted to it;s utf8-representation : 0xC2B5 self.__unit_name = "" new_name = bytearray() for i in range (len(bname)): if bname[i] > 127: new_name.append(194) #0xC2 new_name.append(bname[i]) if len(new_name) > 0: self.__unit_name = new_name.decode('utf8').rstrip('\x00') class SagaChannel(): """ <DeviceChannel> represents a device channel. It has the next properties: type : <ChannelType> Indicates the group-type of a channel. sample_rate : <int> The curring sampling rate of the channel during a 'normal' measurement. name : <string> The name of the channel. unit_name : <string> The name of the unit (e.g. 'μVolt) of the sample-data of the channel. enabled : <bool> Indicates if a channel is enavled for measuring Note: The properties <name> and <anabled> can be modified. The other properties are read-only. """ def __init__(self): self.type = 0 self.format = 0 self.sample_rate = 0 self.chan_divider = -1 self.imp_divider = -1; self.exp = 1 self.__unit_name = "-" self.def_name = "-" self.alt_name = "-" self.sensor = None @property def unit_name(self): """'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel.""" return self.__unit_name @unit_name.setter def unit_name(self, name): # A unit-name can start with the micro-character (0xB5). In that case must # the micro-character be converted to it;s utf8-representation : 0xC2B5 self.__unit_name = "" bname = name.encode('windows-1252') new_name = bytearray() for i in range (len(bname)): if bname[i] > 127: new_name.append(194) #0xC2 new_name.append(bname[i]) if len(new_name) > 0: self.__unit_name = new_name.decode('utf8') class SagaSampleRate(): def __init__(self, type): self.type = type self.sample_rate = 0 self.chan_divider = -1
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/devices/saga/saga_types.py
0.842507
0.253861
saga_types.py
pypi
import numpy as np import struct import datetime import tkinter as tk from tkinter import filedialog class Poly5Reader: def __init__(self, filename=None, readAll=True): if filename is None: root = tk.Tk() filename = filedialog.askopenfilename() root.withdraw() self.filename = filename self.readAll = readAll print('Reading file', filename) self._readFile(filename) def _readFile(self, filename): self.file_obj = open(filename, 'rb') file_obj = self.file_obj self._readHeader(file_obj) self.channels = self._readSignalDescription(file_obj) self._myfmt = 'f' * self.num_channels*self.num_samples_per_block self._buffer_size = self.num_channels*self.num_samples_per_block if self.readAll: sample_buffer = np.zeros( self.num_samples_per_block * self.num_channels * self.num_data_blocks, ) for i in range(self.num_data_blocks): print( '\rProgress: % 0.1f %%' % (100 * i / self.num_data_blocks), end="\r", ) data_block = self._readSignalBlock( file_obj, self._buffer_size, self._myfmt, ) i1 = i * self.num_samples_per_block * self.num_channels i2 = (i + 1) * self.num_samples_per_block * self.num_channels sample_buffer[i1:i2] = data_block samples = np.transpose(np.reshape( sample_buffer, [self.num_samples_per_block * (i + 1), self.num_channels], )) self.samples = samples print('Done reading data.') self.file_obj.close() def readSamples(self, n_blocks=None): "Function to read a subset of sample blocks from a file" if n_blocks is None: n_blocks = self.num_data_blocks sample_buffer = np.zeros(self.num_channels*n_blocks*self.num_samples_per_block) for i in range(n_blocks): data_block = self._readSignalBlock(self.file_obj, self._buffer_size, self._myfmt) i1 = i * self.num_samples_per_block * self.num_channels i2 = (i+1) * self.num_samples_per_block * self.num_channels sample_buffer[i1:i2] = data_block samples = np.transpose(np.reshape(sample_buffer, [self.num_samples_per_block*(i+1), self.num_channels])) return samples def _readHeader(self, f): header_data=struct.unpack("=31sH81phhBHi4xHHHHHHHiHHH64x", f.read(217)) magic_number=str(header_data[0]) version_number=header_data[1] self.sample_rate=header_data[3] # self.storage_rate=header_data[4] self.num_channels=header_data[6]//2 self.num_samples=header_data[7] self.start_time=datetime.datetime(header_data[8], header_data[9], header_data[10], header_data[12], header_data[13], header_data[14]) self.num_data_blocks=header_data[15] self.num_samples_per_block=header_data[16] if magic_number !="b'POLY SAMPLE FILEversion 2.03\\r\\n\\x1a'": print('This is not a Poly5 file.') elif version_number != 203: print('Version number of file is invalid.') else: print('\t Number of samples: %s ' %self.num_samples) print('\t Number of channels: %s ' % self.num_channels) print('\t Sample rate: %s Hz' %self.sample_rate) def _readSignalDescription(self, f): chan_list = [] for ch in range(self.num_channels): channel_description=struct.unpack("=41p4x11pffffH62x", f.read(136)) name = channel_description[0][5:].decode('ascii') unit_name=channel_description[1].decode('utf-8') ch = Channel(name, unit_name) chan_list.append(ch) f.read(136) return chan_list def _readSignalBlock(self, f, buffer_size, myfmt): f.read(86) sampleData=f.read(buffer_size*4) DataBlock = struct.unpack(myfmt, sampleData) SignalBlock = np.asarray(DataBlock) return SignalBlock def close(self): self.file_obj.close() class Channel: """ 'Channel' represents a device channel. It has the next properties: name : 'string' The name of the channel. unit_name : 'string' The name of the unit (e.g. 'μVolt) of the sample-data of the channel. """ def __init__(self, name, unit_name): self.__unit_name = unit_name self.__name = name if __name__ == "__main__": data=Poly5Reader()
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/file_readers/poly5reader.py
0.46223
0.177597
poly5reader.py
pypi
from os.path import join, dirname, realpath from PySide2 import QtGui, QtCore, QtWidgets import numpy as np import pyqtgraph as pg import time import queue import pandas as pd import math import datetime import sys from .. import tmsi_device from .. import sample_data_server from .. import sample_data from ..device import DeviceInterfaceType, MeasurementType class ImpedancePlot(pg.GraphicsLayoutWidget): """ Class that creates a GUI to display the impedance values in a gridded layout. """ def __init__(self, figurename, device, layout ='normal', file_storage = False): """ Setting up the GUI's elements """ pg.GraphicsLayoutWidget.__init__(self) pg.setConfigOptions(antialias = True) # Pass the device handle to the GUI self.device = device # Update the title of the Impedance plot self.setWindowTitle(figurename) self._save_impedances = file_storage print(layout) # Set up UI and thread self.initUI(layout) self.setupThread() def initUI(self, layout): """ Method responsible for constructing the basic elements in the plot. All viewboxes have a set size so that the information can be displayed correctly. """ # Set view settings self.setBackground('w') self.showMaximized() # Add viewbox for the legend self.vb_legend = self.addViewBox() legend = pg.LegendItem() legend.setParentItem(self.vb_legend) # Add plot window for the channels self.window = self.addPlot() if layout!='head': self.window.getViewBox().invertY(True) if len(self.device.imp_channels) == 34: self.window.setAspectLocked(lock=True, ratio = 0.6) else: self.window.setAspectLocked(lock=True, ratio = 1) else: self.window.setAspectLocked(lock=True, ratio = 1) # Add viewbox for the list of values self.vb_list = self.addViewBox() self.vb_list.setMaximumSize(500,150000) # Generate the legend by using dummy plots self.legend_entries = [] legend_spots = self._generate_legend() for i in range(len(legend_spots)): lg_plt = pg.ScatterPlotItem(pos= [(0,0),(0,0)], size = 20, pen = legend_spots[i]['pen'], brush = legend_spots[i]['brush'], name = legend_spots[i]['name']) legend.addItem(lg_plt, legend_spots[i]['name']) lg_plt.clear() # Ensure legend is displayed in the top left of the viewbox self.vb_legend.setMaximumWidth(legend.boundingRect().width() + 10) legend.anchor((0,0), (0,0)) # Write the ticks to the plot self.window.hideAxis('left') self.window.hideAxis('bottom') # Disable auto-scaling and menu self.window.hideButtons() self.window.setMenuEnabled(False) self.window.setMouseEnabled(x = False, y = False) self.vb_legend.setMouseEnabled(x = False, y = False) self.vb_list.setMouseEnabled(x = False, y = False) # Initialise the standard format for the different indicators self.spots = [{'pos': (0,0), 'size': 20, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(len(self.device.imp_channels))] if layout=='head': #read channel locations chLocs=pd.read_csv('../TMSiSDK/_resources/EEGchannelsTMSi.txt', sep="\t", header=None) chLocs.columns=['name', 'radius', 'theta'] #Plot a circle theta=np.arange(0, 2.02*math.pi, math.pi/50) x_circle = 0.5*np.cos(theta) y_circle = 0.5*np.sin(theta) self.h=pg.PlotCurveItem() self.h.setData(x_circle, y_circle, pen=pg.mkPen((165, 165, 165), width=5)) self.window.addItem(self.h) #Plot a nose y_nose=np.array([x_circle[2], 0.55, x_circle[-3]]) x_nose=np.array([y_circle[2], 0, y_circle[-3]]) self.n=pg.PlotCurveItem() self.n.setData(x_nose, y_nose, pen=pg.mkPen((165, 165, 165), width=5)) self.window.addItem(self.n) #Plot ears x_ears=np.array([0.49, 0.51, 0.52, 0.53, 0.54, 0.54, 0.55, 0.53, 0.51, 0.485]) y_ears=np.array([0.10, 0.1175, 0.1185, 0.1145, 0.0955, -0.0055, -0.0930, -0.1315, -0.1385, -0.12]) self.e=pg.PlotCurveItem() self.e.setData(x_ears, y_ears, pen=pg.mkPen((165, 165, 165), width=5)) self.window.addItem(self.e) self.e=pg.PlotCurveItem() self.e.setData(-x_ears, y_ears, pen=pg.mkPen((165, 165, 165), width=5)) self.window.addItem(self.e) # Initialise the standard format for the different indicators self.spots = [{'pos': (0,0), 'size': 20, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(len(self.device.imp_channels))] # Set the position for each indicator for i in range(len(self.device.imp_channels)): if i == 0: self.spots[i]['pos'] = (-0.05, -0.6) elif i == len(self.device.imp_channels)-1: self.spots[i]['pos'] = (0.05, -0.6) else: x=chLocs['radius'].values[i-1]*np.sin(np.deg2rad(chLocs['theta'].values[i-1])) y=chLocs['radius'].values[i-1]*np.cos(np.deg2rad(chLocs['theta'].values[i-1])) self.spots[i]['pos'] = (x,y) # Place the name of each channel below the respective indicator text = f'{self.device.imp_channels[i].name: ^10}' t_item = pg.TextItem(text, (0, 0, 0), anchor=(0, 0)) t_item.setPos(self.spots[i]['pos'][0] -.03, self.spots[i]['pos'][1] - .02) self.window.addItem(t_item) else: row_count = -1 # Set the position for each indicator for i in range(len(self.device.imp_channels)): if i == 0: if len(self.device.imp_channels)>34: self.spots[i]['pos'] = (3, 8) else: self.spots[i]['pos'] = (3, 4) elif i == len(self.device.imp_channels)-1: if len(self.device.imp_channels) > 34: self.spots[i]['pos'] = (4, 8) else: self.spots[i]['pos'] = (4, 4) elif (i-1) % 8 == 0: row_count += 1 self.spots[i]['pos'] = (((i-1)%8), row_count) else: self.spots[i]['pos'] = (((i-1)%8), row_count) # Place the name of each channel below the respective indicator text = f'{self.device.imp_channels[i].name: ^10}' t_item = pg.TextItem(text, (128, 128, 128), anchor=(0, 0)) t_item.setPos(self.spots[i]['pos'][0] -.25, self.spots[i]['pos'][1] + .1) self.window.addItem(t_item) # Add all indicators to the plot self.c = pg.ScatterPlotItem(self.spots) self.window.addItem(self.c) # Create a list with impedance values to display next to the plot self.text_items = [] for i in range(len(self.device.imp_channels)): # Display 33 names per list (66 impedance channels in SAGA64+) list_split_idx = 33 num_column = np.floor(i/list_split_idx) value = 5000 text = f'{self.device.imp_channels[i].name}\t{value:>4}\t{self.device.imp_channels[i].unit_name}' t_item = pg.TextItem(text, (0, 0, 0), anchor = (-num_column *1.2,-i*0.95 + list_split_idx * 0.95 * np.floor(i/list_split_idx))) self.text_items.append(t_item) self.vb_list.addItem(t_item) @QtCore.Slot(object) def update_plot(self, data): """ Method that updates the indicators according to the measured impedance values """ for i in range(len(self.spots)): self.spots[i]['brush'] = QtGui.QBrush(self._lookup_table(data[i])) text = f"{self.device.imp_channels[i].name}\t{data[i]:>4}\t{self.device.imp_channels[i].unit_name}" self.text_items[i].setText(text) self.c.setData(self.spots) def _lookup_table(self, value): """Look up table to convert impedances to color coding""" if value < 5: color_code = QtGui.QColor(0, 255, 0) elif value >= 5 and value < 10: color_code = QtGui.QColor(0, 204, 0) elif value >= 10 and value < 30: color_code = QtGui.QColor(0, 153, 0) elif value >= 30 and value < 50: color_code = QtGui.QColor(0, 102, 0) elif value >= 50 and value < 100: color_code = QtGui.QColor(255, 255, 0) elif value >= 100 and value < 200: color_code = QtGui.QColor(204, 128, 0) elif value >= 200 and value < 400: color_code = QtGui.QColor(255, 0, 0) elif value >= 400 and value < 500: color_code = QtGui.QColor(153, 0, 0) elif value == 500: color_code = QtGui.QColor(102, 66, 33) elif value == 5000: color_code = QtGui.QColor(128, 128, 128) elif value == 5100: color_code = QtGui.QColor(204, 0, 102) elif value == 5200: color_code = QtGui.QColor(0, 0, 179) return color_code def _generate_legend(self): """ Method that generates the dummy samples needed to plot the legend """ legend_spots = [{'pos': (0,0), 'size': 10, 'pen': 'k', 'brush': QtGui.QBrush() , 'name': ''} for i in range(12)] legend_spots[0]['name'] = '0 - 5 k\u03A9' legend_spots[0]['brush'] = QtGui.QBrush(QtGui.QColor(0, 255, 0)) legend_spots[1]['name'] = '5 - 10 k\u03A9' legend_spots[1]['brush'] = QtGui.QBrush(QtGui.QColor(0, 204, 0)) legend_spots[2]['name'] = '10 - 30 k\u03A9' legend_spots[2]['brush'] = QtGui.QBrush(QtGui.QColor(0, 153, 0)) legend_spots[3]['name'] = '30 - 50 k\u03A9' legend_spots[3]['brush'] = QtGui.QBrush(QtGui.QColor(0, 102, 0)) legend_spots[4]['name'] = '50 - 100 k\u03A9' legend_spots[4]['brush'] = QtGui.QBrush(QtGui.QColor(255, 255, 0)) legend_spots[5]['name'] = '100 - 200 k\u03A9' legend_spots[5]['brush'] = QtGui.QBrush(QtGui.QColor(204, 128, 0)) legend_spots[6]['name'] = '200 - 400 k\u03A9' legend_spots[6]['brush'] = QtGui.QBrush(QtGui.QColor(255, 0, 0)) legend_spots[7]['name'] = '400 - 500 k\u03A9' legend_spots[7]['brush'] = QtGui.QBrush(QtGui.QColor(153, 0, 0)) legend_spots[8]['name'] = '≥ 500 k\u03A9 / Not connected' legend_spots[8]['brush'] = QtGui.QBrush(QtGui.QColor(102, 66, 33)) legend_spots[9]['name'] = 'Disabled' legend_spots[9]['brush'] = QtGui.QBrush(QtGui.QColor(128, 128, 128)) legend_spots[10]['name'] = 'Odd/Even error' legend_spots[10]['brush'] = QtGui.QBrush(QtGui.QColor(204, 0, 102)) legend_spots[11]['name'] = 'PGND disconnected' legend_spots[11]['brush'] = QtGui.QBrush(QtGui.QColor(0, 0, 179)) return legend_spots def setupThread(self): """ Method that initialises the sampling thread of the device """ # Create a Thread self.thread = QtCore.QThread() # Instantiate the worker class self.worker = SamplingThread(self) # Move the worker to a Thread self.worker.moveToThread(self.thread) # Connect signals to slots self.thread.started.connect(self.worker.update_samples) self.worker.output.connect(self.update_plot) # Start the thread self.thread.start() def closeEvent(self,event): """ Method that redefines the default close event of the GUI. This is needed to close the sampling thread when the figure is closed. """ # Stop the worker and the thread self.worker.stop() self.thread.terminate() self.thread.wait() sample_data_server.unregisterConsumer(self.device.id, self.worker.q_sample_sets) QtWidgets.QApplication.quit() class SamplingThread(QtCore.QObject): """ Class responsible for sampling the data from the device """ # Initialise the ouptut object output = QtCore.Signal(object) def __init__(self, main_class): QtCore.QObject.__init__(self) # Access initialised values from the GUI class self.device = main_class.device self._save_impedances = main_class._save_impedances # Prepare Queue self.q_sample_sets = queue.Queue(1000) # Register the consumer to the sample server sample_data_server.registerConsumer(self.device.id, self.q_sample_sets) # Start measurement self.device.start_measurement(MeasurementType.impedance) self.sampling = True @QtCore.Slot() def update_samples(self): """ Method that retrieves the sample data from the device. The method gives the impedance value as output """ while self.sampling: while not self.q_sample_sets.empty(): sd = self.q_sample_sets.get() self.q_sample_sets.task_done() # Retrieve the data from the queue and write it to a SampleSet object for i in range(sd.num_sample_sets): sample_set = sample_data.SampleSet(sd.num_samples_per_sample_set, sd.samples[i*sd.num_samples_per_sample_set:(i+1)*sd.num_samples_per_sample_set]) # Use the final measured impedance value and convert to integer value impedance_values = [int(x) for x in sample_set.samples] self.impedance_values = impedance_values # Output sample data self.output.emit(impedance_values) # Pause the thread so that the update does not happen too fast time.sleep(1) def stop(self): """ Method that is executed when the thread is terminated. This stop event stops the measurement and closes the connection to the device. """ self.device.stop_measurement() self.sampling = False if self._save_impedances: store_imp = [] for i in range(len(self.impedance_values)): store_imp.append(f"{self.device.imp_channels[i].name}\t{self.impedance_values[i]}\t{self.device.imp_channels[i].unit_name}") now = datetime.datetime.now() filetime = now.strftime("%Y%m%d_%H%M%S") filename = 'Impedances_' + filetime with open('../measurements/' + filename + '.txt', 'w') as f: for item in store_imp: f.write(item + "\n") if __name__ == "__main__": # Initialise the TMSi-SDK first before starting using it tmsi_device.initialize() # Create the device object to interface with the SAGA-system. dev = tmsi_device.create(tmsi_device.DeviceType.saga, DeviceInterfaceType.docked, DeviceInterfaceType.usb) # Find and open a connection to the SAGA-system and print its serial number dev.open() print("handle 1 " + str(dev.info.ds_serial_number)) # Initialise the application app = QtGui.QApplication(sys.argv) # Define the GUI object and show it window = ImpedancePlot(figurename = 'An Impedance Plot', device = dev, layout='normal') window.show() # Enter the event loop # sys.exit(app.exec_()) app.exec_() dev.close()
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/plotters/impedance_plotter.py
0.434941
0.210279
impedance_plotter.py
pypi
from PySide2 import QtGui, QtCore, QtWidgets import numpy as np import pyqtgraph as pg import time import queue from scipy import signal, interpolate import sys from .. import tmsi_device from .. import sample_data_server from ..device import DeviceInterfaceType, ChannelType class HDEMGPlot(pg.GraphicsLayoutWidget): """ Class that creates a GUI to display the impedance values in a gridded layout. """ def __init__(self, figurename, device, tail_orientation, signal_lim): """ Setting up the GUI's elements """ if sys.platform == "linux" or sys.platform == "linux2": print('This plotter is not compatible with the current version of the TMSi Python Interface on Linux (Ubuntu 18.04 LTS)\n') return pg.GraphicsLayoutWidget.__init__(self) pg.setConfigOptions(antialias = True) # Pass the device handle to the GUI self.device = device ### ADD SOMETHING TO DETERMINE REFERENCE METHOD / NUMBER OF HW CHANNELS if self.device.config.num_channels > 64: self._EMG_chans = 64 else: self._EMG_chans = 32 if self.device.config.reference_method[0] == 'common': self._chan_offset = 1 else: self._chan_offset = 0 self.sample_rate = self.device.config.get_sample_rate(ChannelType.counter) # Update the title of the HD EMG plot self.setWindowTitle(figurename) self.setMinimumSize(600, 500) # Orientation of the grid on the body self.tail_orientation = tail_orientation # Upper limit colorbar self.signal_lim = signal_lim # Set up UI and thread self.initUI() self.setupThread() def initUI(self): """ Method responsible for constructing the basic elements in the plot. All viewboxes have a set size so that the information can be displayed correctly. """ # Set view settings self.setBackground('w') # self.showMaximized() # Add plot window for the channels self.window = self.addPlot() self.window.setAspectLocked(lock=True, ratio = 1) # Write the ticks to the plot self.window.hideAxis('left') self.window.hideAxis('bottom') # Disable auto-scaling and menu self.window.hideButtons() self.window.setMenuEnabled(False) self.window.setMouseEnabled(x = False, y = False) # Ratio is slightly different between 32/64 channel setup if self._EMG_chans == 32: self._x_interpolate = np.arange(0, int((len(self.device.channels)-2 - self._chan_offset)/8) - 1 + .1, 0.1) self._y_interpolate = np.arange(0, int((len(self.device.channels)-2 - self._chan_offset)/(self._EMG_chans/8)) - 1 + .2, 0.1) else: self._x_interpolate = np.arange(0, int((len(self.device.channels)-2 - self._chan_offset)/8) - 1 + .2, 0.1) self._y_interpolate = np.arange(0, int((len(self.device.channels)-2 - self._chan_offset)/(self._EMG_chans/8)) - 1 + .2, 0.1) self._dummy_val = np.zeros((len(self._x_interpolate), len(self._y_interpolate))) if self.tail_orientation == 'Right' or self.tail_orientation == 'right': self._dummy_val = np.rot90(self._dummy_val, 1) elif self.tail_orientation == 'Left' or self.tail_orientation == 'left': self._dummy_val = np.rot90(self._dummy_val, 3) # Create image item self.img = pg.ImageItem(image = self._dummy_val) self.window.addItem(self.img) # Prepare a linear color map cm = pg.colormap.get('CET-R4') # Insert a Colorbar, non-interactive with a label self.bar = pg.ColorBarItem(values = (0, self.signal_lim), colorMap=cm, interactive = False, label = 'RMS (\u03BCVolt)', ) self.bar.setImageItem(self.img, insert_in = self.window) # Scale factor (number of interpolation points to cover a width of 3 or 7 columns) corr_x = len(self._x_interpolate) / (int((len(self.device.channels)-2-self._chan_offset)/8)-1) # Scale factor (number of interpolation points to cover a width of 7 rows) corr_y = len(self._y_interpolate) / 7 # Initialise the standard format for the different indicators if self.tail_orientation == 'Left' or self.tail_orientation == 'left': self.spots = [{'pos': ((i%8) * corr_y, int(i/8) * corr_x), 'size': 5, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(self._EMG_chans)] elif self.tail_orientation == 'Up' or self.tail_orientation == 'up': self.spots = [{'pos': (int((-i + (self._EMG_chans-1))/8) * corr_y, i%8 * corr_x), 'size': 5, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(self._EMG_chans)] elif self.tail_orientation == 'Right' or self.tail_orientation == 'right': self.spots = [{'pos': ((-i + (self._EMG_chans - 1))%8 * corr_y, int((-i + (self._EMG_chans-1))/8) * corr_x), 'size': 5, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(self._EMG_chans)] elif self.tail_orientation == 'Down' or self.tail_orientation == 'down': self.spots = [{'pos': (int(i/8) * corr_y, (-i + (self._EMG_chans-1))%8 * corr_x), 'size': 5, 'pen': 'k', 'brush': QtGui.QBrush(QtGui.QColor(128, 128, 128))} \ for i in range(self._EMG_chans)] # Set the position for each indicator for i in range(len(self.device.channels)): if i > self._EMG_chans-1: break # Place the name of each channel below the respective indicator text = f'{self.device.channels[i+self._chan_offset].name: ^10}' t_item = pg.TextItem(text, (128, 128, 128), anchor=(0, 0)) t_item.setPos(self.spots[i]['pos'][0] -.25, self.spots[i]['pos'][1] + .1) self.window.addItem(t_item) # Add all indicators to the plot self.c = pg.ScatterPlotItem(self.spots) self.window.addItem(self.c) self.window.invertY(True) @QtCore.Slot(object) def update_plot(self, data): """ Method that updates the indicators according to the measured impedance values """ self.img.setImage(data, autoRange=False, autoLevels=False) def setupThread(self): """ Method that initialises the sampling thread of the device """ # Create a Thread self.thread = QtCore.QThread() # Instantiate the worker class self.worker = SamplingThread(self) # Move the worker to a Thread self.worker.moveToThread(self.thread) # Connect signals to slots self.thread.started.connect(self.worker.update_samples) self.worker.output.connect(self.update_plot) # Start the thread self.thread.start() def closeEvent(self,event): """ Method that redefines the default close event of the GUI. This is needed to close the sampling thread when the figure is closed. """ # Stop the worker and the thread self.worker.stop() self.thread.terminate() self.thread.wait() sample_data_server.unregisterConsumer(self.device.id, self.worker.q_sample_sets) class SamplingThread(QtCore.QObject): """ Class responsible for sampling the data from the device """ # Initialise the ouptut object output = QtCore.Signal(object) def __init__(self, main_class): QtCore.QObject.__init__(self) # Access initialised values from the GUI class self.device = main_class.device self.sample_rate = main_class.sample_rate self._EMG_chans = main_class._EMG_chans self._chan_offset = main_class._chan_offset self.window_buffer = np.zeros((len(self.device.channels)-2-self._chan_offset, self.sample_rate * 5)) self.window_rms_size = self.sample_rate // 4 self._add_final = 0 self.sos = signal.butter(2, 10, 'highpass', fs=self.sample_rate, output='sos') z_sos0 = signal.sosfilt_zi(self.sos) self.z_sos = np.repeat(z_sos0[:, np.newaxis, :], len(self.device.channels)-2-self._chan_offset, axis=1) self._x_grid = np.arange(0, self._EMG_chans/8, dtype=int) self._y_grid = np.arange(0, 8, dtype=int) self._x_interpolate = main_class._x_interpolate self._y_interpolate = main_class._y_interpolate self.tail_orientation = main_class.tail_orientation # Prepare Queue self.q_sample_sets = queue.Queue(1000) # Register the consumer to the sample server sample_data_server.registerConsumer(self.device.id, self.q_sample_sets) # Start measurement self.device.start_measurement() self.sampling = True @QtCore.Slot() def update_samples(self): """ Method that retrieves the sample data from the device. The method gives the impedance value as output """ while self.sampling: while not self.q_sample_sets.empty(): # Retrieve sample data from the sample_data_server queue sd = self.q_sample_sets.get() self.q_sample_sets.task_done() # Reshape the samples retrieved from the queue samples = np.reshape(sd.samples, (sd.num_samples_per_sample_set, sd.num_sample_sets), order = 'F') self.new_samples = sd.num_sample_sets self.window_buffer[:, self._add_final:(self._add_final + self.new_samples)] = samples[self._chan_offset:-2,:] if self._add_final + self.new_samples > self.window_rms_size: filt_data, self.z_sos = signal.sosfilt(self.sos, self.window_buffer[:, 0:self.window_rms_size], zi = self.z_sos) rms_data = np.sqrt(np.mean(filt_data**2, axis = 1)) if self.tail_orientation == 'Left' or self.tail_orientation == 'left': rms_data = np.reshape(rms_data, (int(self._EMG_chans/8),8)).T f = interpolate.interp2d(self._x_grid, self._y_grid, rms_data, kind='linear') output_heatmap = f(self._x_interpolate, self._y_interpolate) elif self.tail_orientation == 'Up' or self.tail_orientation == 'up': rms_data = np.rot90(np.reshape(rms_data, (int(self._EMG_chans/8),8)).T, 1) f = interpolate.interp2d(self._y_grid, self._x_grid, rms_data, kind='linear') output_heatmap = f(self._y_interpolate, self._x_interpolate) elif self.tail_orientation == 'Right' or self.tail_orientation == 'right': rms_data = np.rot90(np.reshape(rms_data, (int(self._EMG_chans/8),8)).T, 2) f = interpolate.interp2d(self._x_grid, self._y_grid, rms_data, kind='linear') output_heatmap = f(self._x_interpolate, self._y_interpolate) elif self.tail_orientation == 'Down' or self.tail_orientation == 'down': rms_data = np.rot90(np.reshape(rms_data, (int(self._EMG_chans/8),8)).T, 3) f = interpolate.interp2d(self._y_grid, self._x_grid, rms_data, kind='linear') output_heatmap = f(self._y_interpolate, self._x_interpolate) self._add_final = 0 self.window_buffer = np.hstack((self.window_buffer[:,self.window_rms_size:], np.zeros((len(self.device.channels)-2-self._chan_offset, self.window_rms_size)) )) self.output.emit(output_heatmap) else: self._add_final += self.new_samples # Pause the thread so that the update does not happen too fast time.sleep(0.01) def stop(self): """ Method that is executed when the thread is terminated. This stop event stops the measurement and closes the connection to the device. """ self.device.stop_measurement() self.sampling = False if __name__ == "__main__": # Initialise the TMSi-SDK first before starting using it tmsi_device.initialize() # Create the device object to interface with the SAGA-system. dev = tmsi_device.create(tmsi_device.DeviceType.saga, DeviceInterfaceType.docked, DeviceInterfaceType.usb) # Find and open a connection to the SAGA-system and print its serial number dev.open() print("handle 1 " + str(dev.info.ds_serial_number)) # Initialise the application app = QtWidgets.QApplication(sys.argv) # Define the GUI object and show it window = HDEMGPlot(figurename = 'An HDEMG Heatmap Plot', device = dev, tail_orientation='up') window.show() # Enter the event loop # sys.exit(app.exec_()) app.exec_() dev.close()
/resurfemg-0.0.5-py3-none-any.whl/TMSiSDK/plotters/plotter_hd_emg.py
0.504883
0.181807
plotter_hd_emg.py
pypi
class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" class ApiTypeError(OpenApiException, TypeError): def __init__(self, msg, path_to_item=None, valid_classes=None, key_type=None): """ Raises an exception for TypeErrors Args: msg (str): the exception message Keyword Args: path_to_item (list): a list of keys an indices to get to the current_item None if unset valid_classes (tuple): the primitive classes that current item should be an instance of None if unset key_type (bool): False if our value is a value in a dict True if it is a key in a dict False if our item is an item in a list None if unset """ self.path_to_item = path_to_item self.valid_classes = valid_classes self.key_type = key_type full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiTypeError, self).__init__(full_msg) class ApiValueError(OpenApiException, ValueError): def __init__(self, msg, path_to_item=None): """ Args: msg (str): the exception message Keyword Args: path_to_item (list) the path to the exception in the received_data dict. None if unset """ self.path_to_item = path_to_item full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiValueError, self).__init__(full_msg) class ApiAttributeError(OpenApiException, AttributeError): def __init__(self, msg, path_to_item=None): """ Raised when an attribute reference or assignment fails. Args: msg (str): the exception message Keyword Args: path_to_item (None/list) the path to the exception in the received_data dict """ self.path_to_item = path_to_item full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiAttributeError, self).__init__(full_msg) class ApiKeyError(OpenApiException, KeyError): def __init__(self, msg, path_to_item=None): """ Args: msg (str): the exception message Keyword Args: path_to_item (None/list) the path to the exception in the received_data dict """ self.path_to_item = path_to_item full_msg = msg if path_to_item: full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) super(ApiKeyError, self).__init__(full_msg) class ApiException(OpenApiException): def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: self.status = status self.reason = reason self.body = None self.headers = None def __str__(self): """Custom error messages for exception""" error_message = "Status Code: {0}\n"\ "Reason: {1}\n".format(self.status, self.reason) if self.headers: error_message += "HTTP response headers: {0}\n".format( self.headers) if self.body: error_message += "HTTP response body: {0}\n".format(self.body) return error_message class NotFoundException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(NotFoundException, self).__init__(status, reason, http_resp) class UnauthorizedException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(UnauthorizedException, self).__init__(status, reason, http_resp) class ForbiddenException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(ForbiddenException, self).__init__(status, reason, http_resp) class ServiceException(ApiException): def __init__(self, status=None, reason=None, http_resp=None): super(ServiceException, self).__init__(status, reason, http_resp) def render_path(path_to_item): """Returns a string representation of a path""" result = "" for pth in path_to_item: if isinstance(pth, int): result += "[{0}]".format(pth) else: result += "['{0}']".format(pth) return result
/resview-client-python-0.2.0.tar.gz/resview-client-python-0.2.0/resview_client/exceptions.py
0.766468
0.278324
exceptions.py
pypi
import re # noqa: F401 import sys # noqa: F401 from resview_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from resview_client.exceptions import ApiAttributeError class ReservationBatchGetRequest(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { 'ids': ([str],), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'ids': 'ids', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, ids, *args, **kwargs): # noqa: E501 """ReservationBatchGetRequest - a model defined in OpenAPI Args: ids ([str]): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.ids = ids for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, ids, *args, **kwargs): # noqa: E501 """ReservationBatchGetRequest - a model defined in OpenAPI Args: ids ([str]): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.ids = ids for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
/resview-client-python-0.2.0.tar.gz/resview-client-python-0.2.0/resview_client/model/reservation_batch_get_request.py
0.570331
0.22093
reservation_batch_get_request.py
pypi
import re # noqa: F401 import sys # noqa: F401 from resview_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from resview_client.exceptions import ApiAttributeError class LocationInner(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ return { } @cached_property def discriminator(): return None attribute_map = { } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """LocationInner - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """LocationInner - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
/resview-client-python-0.2.0.tar.gz/resview-client-python-0.2.0/resview_client/model/location_inner.py
0.522933
0.254636
location_inner.py
pypi
import re # noqa: F401 import sys # noqa: F401 from resview_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from resview_client.exceptions import ApiAttributeError def lazy_import(): from resview_client.model.location_inner import LocationInner globals()['LocationInner'] = LocationInner class ValidationError(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'loc': ([LocationInner],), # noqa: E501 'msg': (str,), # noqa: E501 'type': (str,), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'loc': 'loc', # noqa: E501 'msg': 'msg', # noqa: E501 'type': 'type', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, loc, msg, type, *args, **kwargs): # noqa: E501 """ValidationError - a model defined in OpenAPI Args: loc ([LocationInner]): msg (str): type (str): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.loc = loc self.msg = msg self.type = type for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, loc, msg, type, *args, **kwargs): # noqa: E501 """ValidationError - a model defined in OpenAPI Args: loc ([LocationInner]): msg (str): type (str): Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) self.loc = loc self.msg = msg self.type = type for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
/resview-client-python-0.2.0.tar.gz/resview-client-python-0.2.0/resview_client/model/validation_error.py
0.547222
0.179064
validation_error.py
pypi
import re # noqa: F401 import sys # noqa: F401 from resview_client.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from resview_client.exceptions import ApiAttributeError def lazy_import(): from resview_client.model.validation_error import ValidationError globals()['ValidationError'] = ValidationError class HTTPValidationError(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = { } validations = { } @cached_property def additional_properties_type(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded """ lazy_import() return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { 'detail': ([ValidationError],), # noqa: E501 } @cached_property def discriminator(): return None attribute_map = { 'detail': 'detail', # noqa: E501 } read_only_vars = { } _composed_schemas = {} @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """HTTPValidationError - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) detail ([ValidationError]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', True) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) self = super(OpenApiModel, cls).__new__(cls) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) return self required_properties = set([ '_data_store', '_check_type', '_spec_property_naming', '_path_to_item', '_configuration', '_visited_composed_classes', ]) @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """HTTPValidationError - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) detail ([ValidationError]): [optional] # noqa: E501 """ _check_type = kwargs.pop('_check_type', True) _spec_property_naming = kwargs.pop('_spec_property_naming', False) _path_to_item = kwargs.pop('_path_to_item', ()) _configuration = kwargs.pop('_configuration', None) _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) if args: for arg in args: if isinstance(arg, dict): kwargs.update(arg) else: raise ApiTypeError( "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( args, self.__class__.__name__, ), path_to_item=_path_to_item, valid_classes=(self.__class__,), ) self._data_store = {} self._check_type = _check_type self._spec_property_naming = _spec_property_naming self._path_to_item = _path_to_item self._configuration = _configuration self._visited_composed_classes = _visited_composed_classes + (self.__class__,) for var_name, var_value in kwargs.items(): if var_name not in self.attribute_map and \ self._configuration is not None and \ self._configuration.discard_unknown_keys and \ self.additional_properties_type is None: # discard variable. continue setattr(self, var_name, var_value) if var_name in self.read_only_vars: raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " f"class with read only attributes.")
/resview-client-python-0.2.0.tar.gz/resview-client-python-0.2.0/resview_client/model/http_validation_error.py
0.543833
0.189053
http_validation_error.py
pypi
from typing import NamedTuple, Mapping, Dict, Any, List, Optional from resync.fields import Field, ForeignKeyField, ReverseForeignKeyField from resync.manager import Manager from resync.utils import RegistryPatternMetaclass from resync.diff import DiffObject ModelMeta = NamedTuple( 'Meta', [('table', str), ('fields', Mapping['str', Field]), ('reverse_relations', Mapping[str, ReverseForeignKeyField])] ) class DocumentBase(type): def __new__(mcs, name, bases, attrs): fields = {} for base in bases: fields.update(base._meta.fields) non_field_attrs = {} for key, value in attrs.items(): if isinstance(value, Field): value.name = key fields[key] = value else: non_field_attrs[key] = value new_class = super(DocumentBase, mcs).__new__(mcs, name, bases, non_field_attrs) new_class._meta = ModelMeta(None, fields, {}) return new_class class ModelBase(DocumentBase, RegistryPatternMetaclass): def __new__(mcs, name, bases, attrs): table_name = attrs.pop('table', name.lower()) foreign_key_fields = {} for key, value in attrs.items(): if isinstance(value, ForeignKeyField): foreign_key_fields[key] = value new_class = super(ModelBase, mcs).__new__(mcs, name, bases, attrs) new_class._meta = ModelMeta(table_name, new_class._meta.fields, {}) for foreign_key_field_name, field in foreign_key_fields.items(): related_model = field.model reverse_relation_name = field.related_name or name.lower() + '_set' related_model._meta.reverse_relations[reverse_relation_name] = ReverseForeignKeyField(new_class, foreign_key_field_name) return new_class @property def table(cls): return cls._meta.table class NestedDocument(metaclass=DocumentBase): def __init__(self, **kwargs): fields = frozenset(self._meta.fields.keys()) for field_name, value in kwargs.items(): if field_name not in fields: raise AttributeError( '{} received unexpected keyword argument {}.'.format(self.__class__.__name__, field_name)) setattr(self, field_name, value) for field_name in fields.difference(frozenset(kwargs.keys())): setattr(self, field_name, self._meta.fields[field_name].default) def to_db(self) -> Dict[str, Any]: """ Converts itself into a plain Python dictionary of values serialized into a form suitable for the database. This method is called by parent/container models when they are serialized. """ field_data = self._get_field_data() return self.serialize_fields(field_data) @classmethod def from_db(cls, data_dict: Mapping[str, Any]): """ Deserializes the data from its db representation into Python values and returns a """ transformed_data = {} for field_name, field in cls._meta.fields.items(): value = data_dict.get(field_name, field.default) transformed_data[field_name] = field.from_db(value) return cls(**transformed_data) @classmethod def serialize_fields(cls, data_dict: Mapping[str, Any]) -> Dict[str, Any]: """ Converts a dictionary with the Python values of this model's fields into their db forms. Throws KeyError if any keys in the dictionary are not fields on this model. Return value doesn't include fields missing from the input dictionary. """ transformed_data = {} for field_name, value in data_dict.items(): field = cls._meta.fields[field_name] transformed_data[field_name] = field.to_db(value) return transformed_data def _get_field_data(self): """ Get the instance's field data as a plain Python dictionary. """ return {field_name: getattr(self, field_name) for field_name in self._meta.fields.keys()} class Model(NestedDocument, metaclass=ModelBase): class DoesNotExist(Exception): pass def __init__(self, **kwargs): super(Model, self).__init__(**kwargs) if self.id is not None: for related_name, field in self._meta.reverse_relations.items(): setattr(self, related_name, field.get_queryset(self.id)) async def save(self) -> Optional[List[DiffObject]]: field_data = self._get_field_data() create = self.id is None if create: field_data.pop('id') new_obj = await self.objects.create(**field_data) self.id = new_obj.id changes = None else: changes = await self.objects.update(self, **field_data) return changes def to_db(self): serialized_data = super(Model, self).to_db() if self.id is None: serialized_data.pop('id') return serialized_data def setup(): for subclass in RegistryPatternMetaclass.REGISTRY: if subclass is Model: continue if not hasattr(subclass, 'objects'): subclass.objects = Manager() subclass.objects.attach_model(subclass)
/resync-orm-0.2.2.tar.gz/resync-orm-0.2.2/resync/models.py
0.907252
0.151624
models.py
pypi
from collections import MutableSequence, MutableMapping import arrow class Field: """ I experimented with making this class a data-descriptor, to be attached to instances of the model. However, it felt like misdirection with no real upside. In the end, instances of this class are limited to only dealing with setting the default value on new Model instances and converting between db and python representations, which means they only need to exist as class-level attributes in `Model._meta.fields`. """ MUTABLE_DEFAULT_ERR = 'Try not to use mutable default arguments. You probably want a NestedDocument or ListField' def __init__(self, default=None): assert not isinstance(default, (MutableSequence, MutableMapping)), self.MUTABLE_DEFAULT_ERR self._default = default self.name = None @property def default(self): try: return self._default() except TypeError: return self._default @staticmethod def to_db(value): return value @staticmethod def from_db(value): return value class ForeignKeyField(Field): """ Used to reference objects in another table. """ def __init__(self, model, related_name=None): super(ForeignKeyField, self).__init__() self.model = model self.related_name = related_name @staticmethod def to_db(value): return value.id if value is not None else None def from_db(self, value): return RelatedObjectProxy(self.model, value) class RelatedObjectProxy: """ With this proxy, users can get the id of the object synchronously without a db query, or they can await it to get the whole object. """ def __init__(self, model, id): self.model = model self.id = id self._cache = None async def _get_instance(self): if self.id is None: return None if self._cache is None: self._cache = await self.model.objects.get(id=self.id) return self._cache def __await__(self): return self._get_instance().__await__() def __str__(self): return '{} object, id: {}'.format(self.model, self.id) class NestedDocumentField(Field): """ Used to nest data structures in documents. 'inner' should be an subclass of NestedDocument """ def __init__(self, inner): super(NestedDocumentField, self).__init__() self.inner = inner def to_db(self, value): """ Cover the None case here to avoid complicating the NestedDocument to_db implementation. """ return self.inner.to_db(value) if value is not None else None def from_db(self, value): return self.inner.from_db(value) if value is not None else None class ListField(Field): """ Represents a collection of 'inner' fields. """ def __init__(self, inner): super(ListField, self).__init__(default=list) self.inner = inner def to_db(self, value): return [self.inner.to_db(inner_obj) for inner_obj in value] def from_db(self, value): return [self.inner.from_db(inner_obj) for inner_obj in value] class DictField(Field): """ Used for arbitrary unstructured data. """ def __init__(self): super(DictField, self).__init__(default=dict) def field_factory(name, to_db, from_db): field_class = type(name, (Field,), {}) field_class.to_db = staticmethod(lambda x: to_db(x) if x is not None else None) field_class.from_db = staticmethod(lambda x: from_db(x) if x is not None else None) return field_class StrField = field_factory('StrField', str, str) IntField = field_factory('IntField', int, int) FloatField = field_factory('FloatField', float, float) BooleanField = field_factory('BooleanField', bool, bool) class DateTimeField(Field): @staticmethod def to_db(value): return value.isoformat() if value is not None else None @staticmethod def from_db(value): return arrow.get(value) if value is not None else None class IntEnumField(Field): def __init__(self, enum_class, **kwargs): self.enum_class = enum_class super(IntEnumField, self).__init__(**kwargs) @staticmethod def to_db(value): try: value = value.value except AttributeError: if not isinstance(value, (int, type(None))): # Allow null values until I add a `required` kwarg to fields raise TypeError('Only `IntEnum`s and `int`s can be saved to an IntEnumField, got {}'.format(value)) return value def from_db(self, value): return self.enum_class(int(value)) if value is not None else None class ReverseForeignKeyField: """ Created automatically as a counterpart to ForeignKeyField on the related model. Should not be instantiated by user code. """ def __init__(self, target_model, field_name): self.target_model = target_model self.field_name = field_name def get_queryset(self, id): return self.target_model.objects.filter(**{self.field_name: id})
/resync-orm-0.2.2.tar.gz/resync-orm-0.2.2/resync/fields.py
0.894936
0.473657
fields.py
pypi
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Gaussian(Distribution): """ Gaussian distribution class for calculating and visualizing a Gaussian distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats extracted from the data file """ def __init__(self, mu=0, sigma=1): Distribution.__init__(self, mu, sigma) def calculate_mean(self): """Function to calculate the mean of the data set. Args: None Returns: float: mean of the data set """ avg = 1.0 * sum(self.data) / len(self.data) self.mean = avg return self.mean def calculate_stdev(self, sample=True): """Function to calculate the standard deviation of the data set. Args: sample (bool): whether the data represents a sample or population Returns: float: standard deviation of the data set """ if sample: n = len(self.data) - 1 else: n = len(self.data) mean = self.calculate_mean() sigma = 0 for d in self.data: sigma += (d - mean) ** 2 sigma = math.sqrt(sigma / n) self.stdev = sigma return self.stdev def plot_histogram(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.hist(self.data) plt.title('Histogram of Data') plt.xlabel('data') plt.ylabel('count') def pdf(self, x): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2) def plot_histogram_pdf(self, n_spaces = 50): """Function to plot the normalized histogram of the data and a plot of the probability density function along the same range Args: n_spaces (int): number of data points Returns: list: x values for the pdf plot list: y values for the pdf plot """ mu = self.mean sigma = self.stdev min_range = min(self.data) max_range = max(self.data) # calculates the interval between x values interval = 1.0 * (max_range - min_range) / n_spaces x = [] y = [] # calculate the x values to visualize for i in range(n_spaces): tmp = min_range + interval*i x.append(tmp) y.append(self.pdf(tmp)) # make the plots fig, axes = plt.subplots(2,sharex=True) fig.subplots_adjust(hspace=.5) axes[0].hist(self.data, density=True) axes[0].set_title('Normed Histogram of Data') axes[0].set_ylabel('Density') axes[1].plot(x, y) axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation') axes[0].set_ylabel('Density') plt.show() return x, y def __add__(self, other): """Function to add together two Gaussian distributions Args: other (Gaussian): Gaussian instance Returns: Gaussian: Gaussian distribution """ result = Gaussian() result.mean = self.mean + other.mean result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2) return result def __repr__(self): """Function to output the characteristics of the Gaussian instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}".format(self.mean, self.stdev)
/ret_distributions-0.1.tar.gz/ret_distributions-0.1/ret_distributions/Gaussiandistribution.py
0.688364
0.853058
Gaussiandistribution.py
pypi
from typing import TypedDict INTERPUNCT = "\u00b7" SPACE = "\u00b7" SPACE = " " SEP = " | " class ParsingReference(TypedDict): print: str pattern: list[str] tag_parse_patterns: dict[str, str] = { "featuring": r"(.*?)\s*[\(\[\ ][fF]eat.?\s+(.+)[\)\]]*\s*(.*)", "remaster": r"(.*?)\s*\((\d{0,4}\s*[rR]emaster.*)\)\s*(.*)", "remaster2": r"(.*?)\s*-\s*(\d{0,4}\s*[Rr]emaster.*)(.*)", "live": r"(.*?)\s*[\(\[]([lL]ive.*)[\)\]]\s*(.*)", "instrumental": r"(.*?)\s*[\(\[]([iI]nstrumental.*)[\)\]]\s*(.*)", "remix": r"(.*?)\s*\((.*[rR]emix.*)\)\s*(.*)", } all_tags: dict[str, ParsingReference] = { "title": {"print": "Title", "pattern": [r".*“(.*)” by .* from ‘.*’"]}, "album": {"print": "Album", "pattern": [r".*“.*” by .* from ‘(.*)’"]}, "albumartist": {"print": "Album Artist", "pattern": []}, "artist": { "print": "Artist(s)", "pattern": [ r"^(?!.*(https?|[mM]akeup|[fF]inishing)).*[aA]rtist.*:\s*(.+)\s*", r".*\([fF]eat. (.+?)\)", r".*“.*” by (.*) from ‘.*’", ], }, "date": {"print": "Date", "pattern": [r"Released on:\s*(\d\d\d\d-\d\d-\d\d)"]}, "genre": {"print": "Genre", "pattern": []}, "version": {"print": "Version", "pattern": []}, "performer": {"print": "Performer", "pattern": [r".*[pP]erformer.*:\s*(.+)\s*"]}, "organization": {"print": "Organization", "pattern": [r"Provided to YouTube by (.+)\s*"]}, "copyright": {"print": "Copyright", "pattern": [r"\u2117 (.+)\s*"]}, "composer": {"print": "Composer", "pattern": [r".*?[cC]omposer.*:\s*(.+)\s*"]}, "conductor": {"print": "Conductor", "pattern": [r".*[cC]onductor.*:\s*(.+)\s*"]}, "arranger": { "print": "Arranger", "pattern": [r".*?[aA]rranged\s+[bB]y.*:\s*(.+)\s*", r".*?[aA]rranger.*:\s*(.+)\s*"], }, "author": {"print": "Author", "pattern": [r"(.*, )?[aA]uthor.*:\s*(.+)\s*"]}, "producer": {"print": "Producer", "pattern": [r"(.*, )?[pP]roducer.*:\s*(.+)\s*"]}, "publisher": {"print": "Publisher", "pattern": [r"(.*, )?[pP]ublisher.*:\s*(.+)\s*"]}, "lyricist": { "print": "Lyricist", "pattern": [ r"(.*, )?[wW]riter.*:\s*(.+)\s*", r"(.*, )?[wW]ritten\s+[bB]y.*:\s*(.+)\s*", r".*[lL]yricist.*:\s*(.+)\s*", ], }, } performer_tags: dict[str, ParsingReference] = { "performer:vocals": {"print": "- Vocals", "pattern": [r"(.*, )?(Lead\s+)?[vV]ocal(?!.*[eE]ngineer).*:\s*(.+)\s*"]}, "performer:background vocals": { "print": "- Background Vocals", "pattern": [r"(.*, )?[bB]ackground\s+[vV]ocal.*:\s*(.+)\s*"], }, "performer:drums": {"print": "- Drums", "pattern": [r"(.*, )?[dD]rum.*:\s*(.+)\s*"]}, "performer:percussion": {"print": "- Percussion", "pattern": [r".*[pP]ercussion.*:\s*(.+)\s*"]}, "performer:keyboard": {"print": "- Keyboard", "pattern": [r"(.*, )?[kK]eyboard.*:\s*(.+)\s*"]}, "performer:piano": {"print": "- Piano", "pattern": [r"(.*, )?[pP]iano.*:\s*(.+)\s*"]}, "performer:synthesizer": {"print": "- Synthesizer", "pattern": [r".*[sS]ynth.*:\s*(.+)\s*"]}, "performer:guitar": { "print": "- Guitar", "pattern": [r"(.*, )?[gG]uitar.*:\s*(.+)\s*" r".*[eE]lectric\s+[gG]uitar.*:\s*(.+)\s*"], }, "performer:electric guitar": {"print": "- Electric guitar", "pattern": []}, "performer:bass guitar": {"print": "- Bass guitar", "pattern": [r".*[bB]ass\s+[gG]uitar.*:\s*(.+)\s*"]}, "performer:acoustic guitar": {"print": "- Acoustic guitar", "pattern": [r".*[aA]coustic\s+[gG]uitar.*:\s*(.+)\s*"]}, "performer:ukulele": {"print": "- Ukulele", "pattern": [r".*[uU]kulele.*:\s*(.+)\s*"]}, "performer:violin": {"print": "- Violin", "pattern": [r"(.*, )?[vV]iolin.*:\s*(.+)\s*"]}, "performer:double bass": {"print": "- Double bass", "pattern": [r".*[dD]ouble\s+[bB]ass.*:\s*(.+)\s*"]}, "performer:cello": {"print": "- Cello", "pattern": [r"(.*, )?[cC]ello.*:\s*(.+)\s*"]}, "performer:programming": {"print": "- Programming", "pattern": [r"(.*, )?[pP]rogramm(er|ing).*:\s*(.+)\s*"]}, "performer:saxophone": {"print": "- Saxophone", "pattern": [r"(.*, )?[sS]axophone.*:\s*(.+)\s*"]}, "performer:flute": {"print": "- Flute", "pattern": [r"(.*, )?[fF]lute.*:\s*(.+)\s*"]}, }
/retag_opus-0.3.0.tar.gz/retag_opus-0.3.0/retag_opus/constants.py
0.472197
0.518241
constants.py
pypi
import re from colorama import Fore from mutagen.oggopus import OggOpus from simple_term_menu import TerminalMenu from retag_opus import colors, constants from retag_opus.utils import Utils Tags = dict[str, list[str]] class MusicTags: """ Stores tags for one song as a dictionary on the same format as the one provided by the OggOpus object. """ def __init__(self) -> None: self.original: Tags = {} self.youtube: Tags = {} self.fromtags: Tags = {} self.fromdesc: Tags = {} self.resolved: Tags = {} def print_metadata_key(self, key_type: str, key: str, key_col: str, data: Tags) -> None: value = constants.SEP.join(data.get(key, [Fore.BLACK + "Not found"])).replace(" ", constants.SPACE) print(" " + key_type + ": " + key_col + value) def print_metadata(self, data: Tags, col: str) -> None: if "performer:" in " ".join(data.keys()): print(" Performers:") for tag_id, tag_data in constants.performer_tags.items(): if tag_id in data and data[tag_id] is not None: self.print_metadata_key(tag_data["print"], tag_id, col, data) for tag_id, tag_data in constants.all_tags.items(): self.print_metadata_key(tag_data["print"], tag_id, col, data) print("") def get_tag_data(self, tag_id: str) -> list[str]: """ Returns a list of all values for a specific tag from various sources with color depending on source. :param tag_id: The tag name for which data should be returned :return: List with strings containing the value the given tag has in different sources with color codes that differ between sources. If no source contains the tag, an empty list is returned. """ print_data: list[str] = [] original = self.original.get(tag_id) youtube = self.youtube.get(tag_id) fromdesc = self.fromdesc.get(tag_id) fromtags = self.fromtags.get(tag_id) if original: print_data.append(colors.md_col + " | ".join(original)) if youtube and original != youtube: print_data.append(colors.yt_col + " | ".join(youtube)) if fromtags and fromtags != original: print_data.append(Fore.YELLOW + " | ".join(fromtags)) if fromdesc and fromdesc != original: print_data.append(Fore.GREEN + " | ".join(fromdesc)) return print_data def print_all(self) -> None: performer_block = [] for tag_id, tag_data in constants.performer_tags.items(): tag_all_values = self.get_tag_data(tag_id) if len(tag_all_values) > 0: performer_block.append(Fore.WHITE + tag_data["print"] + ": " + f"{Fore.WHITE} | ".join(tag_all_values)) main_block = [] for tag_id, tag_data in constants.all_tags.items(): tag_all_values = self.get_tag_data(tag_id) if len(tag_all_values) > 0: main_block.append(Fore.WHITE + tag_data["print"] + ": " + f"{Fore.WHITE} | ".join(tag_all_values)) else: main_block.append(Fore.WHITE + tag_data["print"] + ": " + Fore.BLACK + "Not set") if len(performer_block + main_block) > 0: if len(performer_block) > 0: print(Fore.BLUE + "Performers:") print("\n".join(performer_block)) print("\n".join(main_block) + "\n") else: print(Fore.RED + "There's no data to be printed") def print_youtube(self) -> None: if self.youtube: self.print_metadata(self.youtube, colors.yt_col) else: print(Fore.RED + "No new data parsed from description") def print_original(self) -> None: if self.original: self.print_metadata(self.original, colors.md_col) else: print(Fore.RED + "There were no pre-existing tags for this file") def print_from_tags(self) -> None: if self.fromtags: self.print_metadata(self.fromtags, Fore.YELLOW) else: print(Fore.RED + "No new data parsed from tags") def print_from_desc(self) -> None: if self.fromdesc: self.print_metadata(self.fromdesc, Fore.GREEN) else: print(Fore.RED + "No new data parsed from tags parsed from description") def print_resolved(self, print_all: bool = False) -> None: if "performer:" in " ".join(self.resolved.keys()): print(" Performers:") for tag_id, tag_data in constants.performer_tags.items(): resolved_tag = self.resolved.get(tag_id) all_sources_tag = self.get_tag_data(tag_id) if resolved_tag == ["[Removed]"]: self.print_metadata_key(tag_data["print"], tag_id, Fore.RED, self.resolved) elif resolved_tag != self.original.get(tag_id): self.print_metadata_key(tag_data["print"], tag_id, Fore.GREEN, self.resolved) elif len(all_sources_tag) > 0 and print_all: print(" " + Fore.WHITE + tag_data["print"] + ": " + f"{Fore.WHITE} | ".join(all_sources_tag)) else: self.print_metadata_key(tag_data["print"], tag_id, colors.md_col, self.resolved) for tag_id, tag_data in constants.all_tags.items(): resolved_tag = self.resolved.get(tag_id) all_sources_tag = self.get_tag_data(tag_id) if resolved_tag == ["[Removed]"]: self.print_metadata_key(tag_data["print"], tag_id, Fore.RED, self.resolved) elif resolved_tag != self.original.get(tag_id): self.print_metadata_key(tag_data["print"], tag_id, Fore.GREEN, self.resolved) elif len(all_sources_tag) > 0 and print_all: print(" " + Fore.WHITE + tag_data["print"] + ": " + f"{Fore.WHITE} | ".join(all_sources_tag)) else: self.print_metadata_key(tag_data["print"], tag_id, colors.md_col, self.resolved) print("") def switch_album_to_disc_subtitle(self, manual_album_name: str) -> None: """ Switches the original album tag to the discsubtitle tag so that it will be used in the comparison for that tag, rather than album, which is not used when the album is set manually. """ original_album = self.original.pop("album", None) if original_album is not None and original_album != [manual_album_name]: self.original["discsubtitle"] = original_album def discard_upload_date(self) -> None: """ If the date is just the upload date, discard it """ if self.original.get("date") and re.match(r"\d\d\d\d\d\d\d\d", self.original["date"][0]): self.original.pop("date", None) def merge_original_metadata(self, original_metadata: OggOpus) -> None: for key, value in original_metadata.values(): self.original[key] = value def set_youtube_tags(self, youtube_tags: Tags) -> None: self.youtube = youtube_tags def set_original_tags(self, original_tags: Tags) -> None: self.original = original_tags def set_tags_from_description(self, from_desc_tags: Tags) -> None: self.fromdesc = from_desc_tags def set_tags_from_old_tags(self, tags_from_old_tags: Tags) -> None: self.fromtags = tags_from_old_tags def set_resolved_tags(self, resolved: Tags) -> None: self.resolved = resolved def prune_final_metadata(self) -> None: self.resolved["language"] = ["[Removed]"] self.resolved["compatible_brands"] = ["[Removed]"] self.resolved["minor_version"] = ["[Removed]"] self.resolved["major_brand"] = ["[Removed]"] self.resolved["vendor_id"] = ["[Removed]"] def add_source_tag(self) -> None: self.resolved["comment"] = ["youtube-dl"] def get_field(self, field: str, only_new: bool = False) -> list[str]: old_value = self.original.get(field, []) yt_value = self.youtube.get(field, []) from_desc_value = self.fromdesc.get(field, []) from_tags_value = self.fromtags.get(field, []) if only_new: return Utils().remove_duplicates(yt_value + from_desc_value + from_tags_value) else: return Utils().remove_duplicates(old_value + yt_value + from_desc_value + from_tags_value) def adjust_metadata(self) -> None: # Date should be safe to get from description date = self.youtube.get("date", None) if date and date != self.original.get("date"): self.resolved["date"] = date md_artist = self.original.get("artist") yt_artist = self.youtube.get("artist") if md_artist is not None and len(md_artist) == 1 and Utils().split_tag(md_artist[0]) == yt_artist: if yt_artist is not None: self.resolved["artist"] = yt_artist # Compare all fields all_new_fields = [key for key in self.youtube.keys()] all_new_fields += [key for key in self.fromdesc.keys()] all_new_fields += [key for key in self.fromtags.keys()] all_new_fields = Utils.remove_duplicates(all_new_fields) for field in all_new_fields: old_value = self.original.get(field, []) yt_value = self.youtube.get(field, []) from_desc_value = self.fromdesc.get(field, []) from_tags_value = self.fromtags.get(field, []) all_new_sources = self.get_field(field, only_new=True) if old_value is None and len(all_new_sources) > 0 and field != "albumartist": if len(yt_value) > 0: self.resolved[field] = yt_value elif len(from_tags_value) > 0: self.resolved[field] = from_tags_value elif len(from_desc_value) > 0: self.resolved[field] = from_desc_value else: continue print( Fore.YELLOW + f"{field.title()}: No value exists in metadata. Using parsed data: " f"{self.resolved[field]}." ) elif yt_value == old_value and len(old_value) > 0: print(Fore.GREEN + f"{field.title()}: Metadata matches YouTube description.") elif from_desc_value == old_value and len(old_value) > 0: print(Fore.GREEN + f"{field.title()}: Metadata matches parsed YouTube tags.") else: redo = True print("-----------------------------------------------") self.print_resolved(print_all=True) while redo: redo = False candidates = [] print(Fore.RED + f"{field.title()}: Mismatch between values in description and metadata:") if len(old_value) > 0: print("Exisiting metadata: " + colors.md_col + " | ".join(old_value)) candidates.append("Existing metadata") if len(yt_value) > 0: print("YouTube description: " + colors.yt_col + " | ".join(yt_value)) candidates.append("YouTube description") if len(from_tags_value) > 0: print("Parsed from original tags: " + Fore.YELLOW + " | ".join(from_tags_value)) candidates.append("Parsed from original tags") if len(from_desc_value) > 0: print("Parsed from YouTube tags: " + Fore.GREEN + " | ".join(from_desc_value)) candidates.append("Parsed from Youtube tags") # There have to be choices available for it to make sense to stay in the loop if len(candidates) == 0: break candidates.append("Other action") candidates.append("Quit") candidate_menu = TerminalMenu(candidates) choice = candidate_menu.show() if choice is None: print(Fore.YELLOW + "Skipping this and all later songs") Utils().exit_now() elif isinstance(choice, tuple): continue match candidates[choice]: case "Other action": default_action = "[g] Go back" other_choices = [ "[s] Select items from a list", "[m] Manually fill in tag", "[p] Print description metadata", "[r] Remove field", default_action, ] other_choice_menu = TerminalMenu(other_choices, title="Choose the source you want to use:") choice = other_choice_menu.show() action = default_action if choice is not None and not isinstance(choice, tuple): action = other_choices[choice] match action: case "[m] Manually fill in tag": self.resolved[field] = [input("Value: ")] case "[p] Print description metadata": print("-----------------------------------------------") self.print_youtube() redo = True case "[s] Select items from a list": available_tags = self.get_field(field) tag_selection_menu = TerminalMenu( available_tags, title="Select the items you want in this tag", multi_select=True, show_multi_select_hint=True, multi_select_empty_ok=True, multi_select_select_on_accept=False, ) items = tag_selection_menu.show() if isinstance(items, int): items = [items] elif items is None: print(Fore.RED + "Invalid choice, try again") redo = True break self.resolved[field] = [] for item in items: self.resolved[field].append(available_tags[item]) case "[r] Remove field": self.resolved[field] = ["[Removed]"] case "[g] Go back": redo = True case _: print(Fore.RED + "Invalid choice, try again") redo = True case "Existing metadata": self.resolved[field] = self.original.get(field, []) case "YouTube description": if yt_value is not None: self.resolved[field] = yt_value case "Parsed from original tags": if from_tags_value is not None: self.resolved[field] = from_tags_value case "Parsed from Youtube tags": if from_desc_value is not None: self.resolved[field] = from_desc_value case "Quit": print(Fore.YELLOW + "Skipping this and all later songs") Utils().exit_now() all_artists = self.get_field("artist") resolved_artist = self.resolved.get("artist") original_artist = self.original.get("artist") if len(all_artists) > 1: print(Fore.BLUE + "Select the album artist:") one_artist = Utils().select_single_tag(all_artists) if len(one_artist) > 0: self.resolved["albumartist"] = one_artist elif not self.original.get("albumartist"): if resolved_artist: self.resolved["albumartist"] = resolved_artist elif original_artist: self.resolved["albumartist"] = original_artist def modify_resolved_field(self) -> None: key = " " val = " " while key and val: print("Enter key and value (newline cancels):") key = input(" Key: ") val = input(" Value: ") if key and val: self.resolved[key] = [val] else: break def delete_tag_item(self) -> None: tags_in_resolved = [] for tag in self.resolved.keys(): if tag in constants.all_tags.keys() or tag in constants.performer_tags.keys(): tags_in_resolved.append(tag) tags_in_resolved.append("Quit") removal_menu = TerminalMenu(tags_in_resolved, title="Which field do you want to delete items from?") tag_index = removal_menu.show() if tag_index is None or isinstance(tag_index, tuple) or tags_in_resolved[tag_index] == "Quit": print(Fore.YELLOW + "Returning without removing anything") else: selected_tag = tags_in_resolved[tag_index] items_in_tag = self.resolved.get(selected_tag, []).copy() item_removal_menu = TerminalMenu( items_in_tag, title=f"Which field should be removed from the '{selected_tag}' tag?", multi_select=True, show_multi_select_hint=True, multi_select_empty_ok=True, multi_select_select_on_accept=False, ) items_to_remove = item_removal_menu.show() if isinstance(items_to_remove, int): items_to_remove = [items_to_remove] elif items_to_remove is None or len(items_to_remove) == 0: print(Fore.YELLOW + "Returning without removing anything") return for item in items_to_remove: self.resolved[selected_tag].remove(items_in_tag[item]) if len(self.resolved[selected_tag]) == 0: self.resolved.pop(selected_tag) def check_any_new_data_exists(self) -> bool: new_content_exists = False all_new_fields = [key for key in self.youtube.keys()] all_new_fields += [key for key in self.fromdesc.keys()] all_new_fields += [key for key in self.fromtags.keys()] all_new_fields = Utils.remove_duplicates(all_new_fields) for tag in all_new_fields: all_sources = set(self.get_field(tag)) original_tags = set(self.original.get(tag, [])) if not original_tags.issuperset(all_sources): # If there are no new tags, the set of all tags should not contain anything that is not already in the # original tags. new_content_exists = True for tag in self.resolved.keys(): original_tags = set(self.original.get(tag, [])) resolved_tags = set(self.resolved.get(tag, [])) if not original_tags.issuperset(resolved_tags): # There may be some automatically added tags in resolved. Check that resolved doesn't contain any tag # that doesn't already exist in the original tags. new_content_exists = True return new_content_exists
/retag_opus-0.3.0.tar.gz/retag_opus-0.3.0/retag_opus/music_tags.py
0.55917
0.191328
music_tags.py
pypi
import re import sys from pathlib import Path from typing import List from colorama import Fore from simple_term_menu import TerminalMenu from retag_opus import constants class Utils: @staticmethod def remove_duplicates(duplicates: list[str]) -> list[str]: return list(dict.fromkeys(duplicates)) @staticmethod def prune_title(original_title: str) -> str: pruned = original_title for pattern in constants.tag_parse_patterns.values(): pruned = re.sub(pattern, r"\1 \3", pruned) return pruned.strip() @staticmethod def split_tag(input: str) -> List[str]: return re.split(", | and | & |; ", input) @staticmethod def file_path_to_song_data(file_path: Path) -> str: file_name = str(file_path) basename = re.match(".*/(.*)", file_name) if basename: match = basename.groups()[0] file_name = match name_playlist = re.match("<(.*)> - <(.*)> - <(.*)> - <(.*)>.opus", file_name) name_single = re.match("<(.*)> - <(.*)>.opus", file_name) if name_playlist: file_name = name_playlist.groups()[1] + " - " + name_playlist.groups()[2] elif name_single: file_name = name_single.groups()[0] + " - " + name_single.groups()[1] return file_name @staticmethod def select_single_tag(candidates: list[str]) -> list[str]: """ Let's the user select one out of the candidate tags and returns a list with that as the only item. The user can also choose to skip with q, escape, or choosing the --No change-- item. :param candidates: The list of tags to choose between. :return: A list with the selected candidate or an empty list if none is selected. """ candidates.append("--No change--") choose_one_tag_menu = TerminalMenu(candidates, title="Choose one tag to use") choice = choose_one_tag_menu.show() if choice is None: print(Fore.YELLOW + "No tag selected") elif isinstance(choice, int) and choice != len(candidates) - 1: print(Fore.BLUE + f"Using {candidates[choice]} as tag for this song") return [candidates[choice]] return [] @staticmethod def exit_now() -> None: sys.exit(0)
/retag_opus-0.3.0.tar.gz/retag_opus-0.3.0/retag_opus/utils.py
0.477067
0.208098
utils.py
pypi
import re from typing import Dict, List from retag_opus import constants from retag_opus.utils import Utils INTERPUNCT = "\u00b7" class TagsParser: def __init__(self, tags: Dict[str, List[str]]): self.tags: Dict[str, List[str]] = {} self.original_tags = tags def standard_pattern(self, field_name: str, regex: str, line: str) -> None: pattern = re.compile(regex) pattern_match = re.match(pattern, line) if pattern_match: field_value = pattern_match.groups()[len(pattern_match.groups()) - 1] field_value = field_value.strip() if self.tags.get(field_name): self.tags[field_name].append(field_value) self.tags[field_name] = Utils().remove_duplicates(self.tags[field_name]) else: self.tags[field_name] = [field_value] def parse_tags(self) -> None: old_title = self.original_tags.get("title", []) old_artist = self.original_tags.get("artist", []) if len(old_artist) == 1: old_artist = Utils.split_tag(old_artist[0]) new_artist = [] old_version = self.original_tags.get("version", []) new_version = [] old_genre = self.original_tags.get("genre", []) new_genre = [] for title in old_title: featuring_regex = constants.tag_parse_patterns["featuring"] pattern_match = re.match(featuring_regex, title) if pattern_match: new_artist += Utils().split_tag(pattern_match.groups()[1].strip()) live_regex = constants.tag_parse_patterns["live"] live_match = re.match(live_regex, title) if live_match: new_version.append(live_match.groups()[1].strip()) instrumental_regex = constants.tag_parse_patterns["instrumental"] instrumental_match = re.match(instrumental_regex, title) if instrumental_match: new_genre.append("Instrumental") remix_regex = constants.tag_parse_patterns["remix"] remix_match = re.match(remix_regex, title) if remix_match: new_version.append(remix_match.groups()[1].strip()) remaster_regex = constants.tag_parse_patterns["remaster"] remaster_match = re.match(remaster_regex, title) if remaster_match: new_version.append(remaster_match.groups()[1].strip()) remaster2_regex = constants.tag_parse_patterns["remaster2"] remaster2_match = re.match(remaster2_regex, title) if remaster2_match: new_version.append(remaster2_match.groups()[1].strip()) if set(new_version) != set(old_version) and len(new_version) > 0: self.tags["version"] = Utils().remove_duplicates(old_version + new_version) if set(new_artist) != set(old_artist) and len(new_artist) > 0: self.tags["artist"] = Utils().remove_duplicates(old_artist + new_artist) if set(new_genre) != set(old_genre) and len(new_genre) > 0: self.tags["genre"] = Utils().remove_duplicates(old_genre + new_genre) if len(old_title) > 0: pruned_title = Utils().prune_title(old_title[0]) if old_title[0] != pruned_title: self.tags["title"] = [pruned_title] def process_existing_tags(self) -> None: """ Analyze existing tags for information that can be moved into new tags. """ # If the date is just the upload date, discard it if self.original_tags.get("date") and re.match(r"\d\d\d\d\d\d\d\d", self.original_tags["date"][0]): self.original_tags.pop("date", None) tags_to_split = ["genre", "artist"] for tag in tags_to_split: tags_tag = self.original_tags.get(tag) if tags_tag is not None and not len(tags_tag) > 1: new_tag = Utils().split_tag(tags_tag[0]) if new_tag != tags_tag: self.tags[tag] = new_tag def get_tags(self) -> Dict[str, List[str]]: return self.tags
/retag_opus-0.3.0.tar.gz/retag_opus-0.3.0/retag_opus/tags_parser.py
0.512205
0.205157
tags_parser.py
pypi
import re from retag_opus import constants from retag_opus.utils import Utils INTERPUNCT = "\u00b7" Tags = dict[str, list[str]] class DescriptionParser: def __init__(self) -> None: self.tags: Tags = {} def parse_artist_and_title(self, source_line: str) -> tuple[list[str], str]: artist_and_title = source_line.split(" " + constants.INTERPUNCT + " ") title = Utils().prune_title(artist_and_title[0]) artist: list[str] = artist_and_title[1:] if len(artist) < 2 and ", " in artist[0]: artist = Utils().split_tag(artist[0]) return artist, title def standard_pattern(self, field_name: str, regex: str, line: str) -> None: pattern = re.compile(regex) pattern_match = re.match(pattern, line) if pattern_match: field_value = pattern_match.groups()[len(pattern_match.groups()) - 1] field_value = field_value.strip() if self.tags.get(field_name): self.tags[field_name].append(field_value) self.tags[field_name] = Utils().remove_duplicates(self.tags[field_name]) else: self.tags[field_name] = [field_value] def parse(self, description_tag_full: str) -> None: lines_since_title_artist: int = 1000 description_tag_lines: list[str] = description_tag_full.splitlines(False) for description_line in description_tag_lines: description_line = description_line.replace("\n", "") description_line = re.sub("\n", "", description_line) lines_since_title_artist = lines_since_title_artist + 1 # Artist and title if INTERPUNCT in description_line: lines_since_title_artist = 0 youtube_artist, youtube_title = self.parse_artist_and_title(description_line) if youtube_artist: self.tags["artist"] = Utils().remove_duplicates(youtube_artist) self.tags["title"] = [youtube_title] if lines_since_title_artist == 1: if "discsubtitle" in constants.all_tags: self.tags["discsubtitle"] = [description_line.strip()] else: self.tags["album"] = [description_line.strip()] for tag_id, tag_data in constants.all_tags.items(): for pattern in tag_data["pattern"]: self.standard_pattern(tag_id, pattern, description_line) for tag_id, tag_data in constants.performer_tags.items(): for pattern in tag_data["pattern"]: self.standard_pattern(tag_id, pattern, description_line) title = self.tags.pop("title", None) if title: self.tags["title"] = [Utils().prune_title(title[0])] artist = self.tags.get("artist") if artist: self.tags["albumartist"] = [artist[0]] if len(artist) > 1: many_artist: list[str] = [] for a in artist: many_artist = many_artist + Utils().split_tag(a) artist = many_artist else: artist = Utils().split_tag(artist[0]) artist = Utils().remove_duplicates(artist) self.tags["artist"] = artist for key, value in self.tags.items(): if value == []: self.tags.pop(key) # Basic pattern: # r".*[ ] .*:\s*(.*)\s*" # Custom patterns for description_line in description_tag_lines: description_line = description_line.replace("\n", "") description_line = re.sub("\n", "", description_line) self.standard_pattern("copyright_date", r"\u2117 (\d\d\d\d)\s", description_line) copyright_date = self.tags.pop("copyright_date", None) date = self.tags.get("date") if copyright_date and not date: self.tags["date"] = copyright_date def get_tags(self) -> Tags: return self.tags
/retag_opus-0.3.0.tar.gz/retag_opus-0.3.0/retag_opus/description_parser.py
0.411111
0.237079
description_parser.py
pypi
import numpy as np def calculate_cross_elasticity(original_quantities: object, new_quantities: object, original_prices: object, new_prices: object) -> np.ndarray: """Calculate cross elasticity of two items. Pass in single values (for a single pair of products) or arrays where the products are linked by the same index. When calculating the percentage change, instead of simply taking the base value, the average of the original and new value is used. For example, when the original value is 100 and the new value is 110, instead of calculating the % change using 100 as the base value, 105 is used. Instead of % change being = 10 / 100 it is 10 /105. This is done so that the % change is valid both when going from the original value to the new value and the new value to the original value. See https://www.youtube.com/watch?v=Ngv0Be9NxAw. Simple Usage: The cross elasticity can be calculated by executing: calculate_cross_elasticity(original_quantities=200, new_quantities=400, original_prices=1000, new_prices=1050) which will return a value of approx `13.67`. Batch Usage: Cross elasticities can also be calculated in a batch by passing in arrays of values. Consider two pairs of products, A, B and C, D. They have the following values: A goes from 200 units to 400 units when the price of B increases from 1000 to 1050. C goes from 1000 units to 1100 units when the price of D drops from 100 to 80. Their cross elasticities can be calculated as a batch using: calculate_cross_elasticity(original_quantities=[200, 1000], new_quantities=[400, 1100], original_prices=[1000, 100], new_prices=[1050, 80]) which will return an array `[13.667, -0.429]`. Args: original_quantities: numpy array or scalar value of original quantity sold new_quantities: numpy array or scalar value of the new quantity sold original_prices: numpy array or scalar value of the original price new_prices: numpy array or scalar value of the new price Returns: np.ndarray: shape (M,) where M is len(original_quantity) storing cross elasticities. """ if not isinstance(original_quantities, np.ndarray): original_quantities = np.asarray([original_quantities]) if not isinstance(new_quantities, np.ndarray): new_quantities = np.asarray([new_quantities]) if not isinstance(original_prices, np.ndarray): original_prices = np.asarray([original_prices]) if not isinstance(new_prices, np.ndarray): new_prices = np.asarray([new_prices]) __check_shape_of_arrays(original_quantities, new_quantities, original_prices, new_prices) cross_elasticity = __cross_elasticity_calc(new_prices, new_quantities, original_prices, original_quantities) return cross_elasticity def __cross_elasticity_calc(new_prices, new_quantities, original_prices, original_quantities): quantity_base_value = np.mean([original_quantities, new_quantities], axis=0) price_base_value = np.mean([original_prices, new_prices], axis=0) change_in_quantity = new_quantities - original_quantities percent_change_in_quantity = change_in_quantity / quantity_base_value change_in_price = new_prices - original_prices percent_change_in_price = change_in_price / price_base_value return np.divide(percent_change_in_quantity, percent_change_in_price, out=np.zeros_like(percent_change_in_quantity), where=percent_change_in_price != 0) def get_all_cross_elasticities(original_quantities, new_quantities, original_prices, new_prices): """Calculate cross elasticities for all products against each other. For example, given 5 products, this function will calculate the cross elasticity values for all possible pairings of the products = (n-1)^n. In this case, 5 products results in a 5x5 matrix where the rows and columns are the products in order. The 2nd row 3rd column stores the cross elasticity of the 2nd product and the 3rd product. As the underlying calculations are performed using Numpy's vectorised code, cross elasticities for 5000 products can be calculated in ~600ms ±250ms on a modern laptop with an i7 processor and Cython installed. Args: original_quantities: numpy array of original quantities sold new_quantities: numpy array of the new quantities sold original_prices: numpy array of the original prices new_prices: numpy array of the new prices Returns: np.ndarray: shape (M,M) where M is len(original_quantities) storing the cross elasticities of all the products against each other. dtype=float32 """ if not isinstance(original_quantities, np.ndarray): original_quantities = np.asarray(original_quantities) if not isinstance(new_quantities, np.ndarray): new_quantities = np.asarray(new_quantities) if not isinstance(original_prices, np.ndarray): original_prices = np.asarray(original_prices) if not isinstance(new_prices, np.ndarray): new_prices = np.asarray(new_prices) __check_shape_of_arrays(original_quantities, new_quantities, original_prices, new_prices) num_skus = original_quantities.shape[0] ceds = np.zeros((num_skus, num_skus), dtype=np.float32) for i in np.arange(num_skus): ceds[i] = calculate_cross_elasticity(original_quantities=np.repeat(original_quantities[i], num_skus), new_quantities=np.repeat(new_quantities[i], num_skus), original_prices=original_prices, new_prices=new_prices) return ceds def __check_shape_of_arrays(original_quantities, new_quantities, original_prices, new_prices): if new_quantities.shape != original_quantities.shape: raise ValueError(f"Expected 'new_quantities' to have the same shape as " f"'original_quantities'." f" 'new_quantities' is {new_quantities.shape} and " f" 'original_quantities' is {original_quantities.shape}.") if original_prices.shape != original_quantities.shape: raise ValueError(f"Expected 'original_prices' to have the same shape as " f"'original_quantities'." f" 'original_prices' is {original_prices.shape} and " f" 'original_quantities' is {original_quantities.shape}.") if new_prices.shape != original_quantities.shape: raise ValueError(f"Expected 'new_prices' to have the same shape as " f"'original_quantities'." f" 'new_prices' is {new_prices.shape} and " f" 'original_quantities' is {original_quantities.shape}.")
/retail-stats-0.0.2.post1.tar.gz/retail-stats-0.0.2.post1/retail_stats/elasticity.py
0.926512
0.82425
elasticity.py
pypi
import logging import warnings from typing import Callable, List, Set import sqlalchemy as sa from sqlalchemy.dialects.postgresql import array from sqlalchemy.dialects.postgresql.base import PGDDLCompiler from sqlalchemy.ext import compiler from sqlalchemy.schema import DDLElement from sqlalchemy.sql.selectable import Select from .constants import DEFAULT_SCHEMA, MATERIALIZED_VIEW logger = logging.getLogger(__name__) class CreateView(DDLElement): def __init__( self, schema: str, name: str, selectable: Select, materialized: bool = True, ): self.schema: str = schema self.name: str = name self.selectable: Select = selectable self.materialized: bool = materialized @compiler.compiles(CreateView) def compile_create_view( element: CreateView, compiler: PGDDLCompiler, **kwargs ) -> str: statement: str = compiler.sql_compiler.process( element.selectable, literal_binds=True, ) materialized: str = "MATERIALIZED" if element.materialized else "" return ( f'CREATE {materialized} VIEW "{element.schema}"."{element.name}" AS ' f"{statement}" ) class DropView(DDLElement): def __init__( self, schema: str, name: str, materialized: bool = True, cascade: bool = True, ): self.schema: str = schema self.name: str = name self.materialized: bool = materialized self.cascade: bool = cascade @compiler.compiles(DropView) def compile_drop_view( element: DropView, compiler: PGDDLCompiler, **kwargs ) -> str: cascade: str = "CASCADE" if element.cascade else "" materialized: str = "MATERIALIZED" if element.materialized else "" return ( f"DROP {materialized} VIEW IF EXISTS " f'"{element.schema}"."{element.name}" {cascade}' ) class RefreshView(DDLElement): def __init__( self, schema: str, name: str, concurrently: bool = False, ): self.schema: str = schema self.name: str = name self.concurrently: bool = concurrently @compiler.compiles(RefreshView) def compile_refresh_view( element: RefreshView, compiler: PGDDLCompiler, **kwargs ) -> str: concurrently: str = "CONCURRENTLY" if element.concurrently else "" return ( f"REFRESH MATERIALIZED VIEW {concurrently} " f'"{element.schema}"."{element.name}"' ) class CreateIndex(DDLElement): def __init__(self, name: str, schema: str, entity: str, columns: list): self.schema: str = schema self.name: str = name self.entity: str = entity self.columns: list = columns @compiler.compiles(CreateIndex) def compile_create_index( element: CreateIndex, compiler: PGDDLCompiler, **kwargs ) -> str: return ( f"CREATE UNIQUE INDEX {element.name} ON " f'"{element.schema}"."{element.entity}" ({", ".join(element.columns)})' ) class DropIndex(DDLElement): def __init__(self, name: str): self.name: str = name @compiler.compiles(DropIndex) def compile_drop_index( element: DropIndex, compiler: PGDDLCompiler, **kwargs ) -> str: return f"DROP INDEX IF EXISTS {element.name}" def _get_constraints( models: Callable, schema: str, tables: Set[str], label: str, constraint_type: str, ) -> sa.sql.Select: with warnings.catch_warnings(): warnings.simplefilter("ignore", category=sa.exc.SAWarning) table_constraints = models("table_constraints", "information_schema") key_column_usage = models("key_column_usage", "information_schema") return ( sa.select( [ table_constraints.c.table_name, sa.func.ARRAY_AGG( sa.cast( key_column_usage.c.column_name, sa.TEXT, ) ).label(label), ] ) .join( key_column_usage, sa.and_( key_column_usage.c.constraint_name == table_constraints.c.constraint_name, key_column_usage.c.table_schema == table_constraints.c.table_schema, key_column_usage.c.table_schema == schema, ), ) .where( *[ table_constraints.c.table_name.in_(tables), table_constraints.c.constraint_type == constraint_type, ] ) .group_by(table_constraints.c.table_name) ) def _primary_keys( models: Callable, schema: str, tables: Set[str] ) -> sa.sql.Select: return _get_constraints( models, schema, tables, label="primary_keys", constraint_type="PRIMARY KEY", ) def _foreign_keys( models: Callable, schema: str, tables: Set[str] ) -> sa.sql.Select: return _get_constraints( models, schema, tables, label="foreign_keys", constraint_type="FOREIGN KEY", ) def create_view( engine: sa.engine.Engine, models: Callable, fetchall: Callable, index: str, schema: str, tables: Set, user_defined_fkey_tables: dict, views: List[str], ) -> None: """ View describing primary_keys and foreign_keys for each table with an index on table_name This is only called once on bootstrap. It is used within the trigger function to determine what payload values to send to pg_notify. Since views cannot be modified, we query the existing view for exiting rows and union this to the next query. So if 'specie' was the only row before, and the next query returns 'unit' and 'structure', we want to end up with the result below. table_name | primary_keys | foreign_keys | indices ------------+--------------+------------------+------------ specie | {id} | {id, user_id} | {foo, bar} unit | {id} | {id, profile_id} | {foo, bar} structure | {id} | {id} | {foo, bar} unit | {id} | {id, profile_id} | {foo, bar} structure | {id} | {id} | {foo, bar} """ rows: dict = {} if MATERIALIZED_VIEW in views: for table_name, primary_keys, foreign_keys, indices in fetchall( sa.select(["*"]).select_from( sa.text(f"{schema}.{MATERIALIZED_VIEW}") ) ): rows.setdefault( table_name, { "primary_keys": set(), "foreign_keys": set(), "indices": set(), }, ) if primary_keys: rows[table_name]["primary_keys"] = set(primary_keys) if foreign_keys: rows[table_name]["foreign_keys"] = set(foreign_keys) if indices: rows[table_name]["indices"] = set(indices) engine.execute(DropView(schema, MATERIALIZED_VIEW)) if schema != DEFAULT_SCHEMA: for table in set(tables): tables.add(f"{schema}.{table}") for table_name, columns in fetchall(_primary_keys(models, schema, tables)): rows.setdefault( table_name, {"primary_keys": set(), "foreign_keys": set(), "indices": set()}, ) if columns: rows[table_name]["primary_keys"] |= set(columns) rows[table_name]["indices"] |= set([index]) for table_name, columns in fetchall(_foreign_keys(models, schema, tables)): rows.setdefault( table_name, {"primary_keys": set(), "foreign_keys": set(), "indices": set()}, ) if columns: rows[table_name]["foreign_keys"] |= set(columns) rows[table_name]["indices"] |= set([index]) if user_defined_fkey_tables: for table_name, columns in user_defined_fkey_tables.items(): rows.setdefault( table_name, { "primary_keys": set(), "foreign_keys": set(), "indices": set(), }, ) if columns: rows[table_name]["foreign_keys"] |= set(columns) rows[table_name]["indices"] |= set([index]) if not rows: rows.setdefault( None, {"primary_keys": set(), "foreign_keys": set(), "indices": set()}, ) statement = sa.select( sa.sql.Values( sa.column("table_name"), sa.column("primary_keys"), sa.column("foreign_keys"), sa.column("indices"), ) .data( [ ( table_name, array(fields["primary_keys"]) if fields.get("primary_keys") else None, array(fields.get("foreign_keys")) if fields.get("foreign_keys") else None, array(fields.get("indices")) if fields.get("indices") else None, ) for table_name, fields in rows.items() ] ) .alias("t") ) logger.debug(f"Creating view: {schema}.{MATERIALIZED_VIEW}") engine.execute(CreateView(schema, MATERIALIZED_VIEW, statement)) engine.execute(DropIndex("_idx")) engine.execute( CreateIndex( "_idx", schema, MATERIALIZED_VIEW, ["table_name"], ) ) logger.debug(f"Created view: {schema}.{MATERIALIZED_VIEW}") def is_view( engine: sa.engine.Engine, schema: str, table: str, materialized: bool = True, ) -> bool: column: str = "matviewname" if materialized else "viewname" pg_table: str = "pg_matviews" if materialized else "pg_views" with engine.connect() as conn: return ( conn.execute( sa.select([sa.column(column)]) .select_from(sa.text(pg_table)) .where( sa.and_( *[ sa.column(column) == table, sa.column("schemaname") == schema, ] ) ) .with_only_columns([sa.func.COUNT()]) .order_by(None) ).scalar() > 0 )
/retake_pgsync-2.5.4-py3-none-any.whl/pgsync/view.py
0.747247
0.158077
view.py
pypi
import re # Relationship types ONE_TO_ONE = "one_to_one" ONE_TO_MANY = "one_to_many" RELATIONSHIP_TYPES = [ ONE_TO_MANY, ONE_TO_ONE, ] # Relationship variants SCALAR = "scalar" OBJECT = "object" RELATIONSHIP_VARIANTS = [ SCALAR, OBJECT, ] # Node attributes NODE_ATTRIBUTES = [ "base_tables", "children", "columns", "label", "primary_key", "relationship", "schema", "table", "transform", ] # Relationship attributes RELATIONSHIP_ATTRIBUTES = [ "foreign_key", "through_tables", "type", "variant", ] # Relationship foreign keys RELATIONSHIP_FOREIGN_KEYS = [ "child", "parent", ] # tg_op UPDATE = "UPDATE" INSERT = "INSERT" DELETE = "DELETE" TRUNCATE = "TRUNCATE" TG_OP = [ DELETE, INSERT, TRUNCATE, UPDATE, ] # https://www.postgresql.org/docs/current/functions-json.html JSONB_OPERATORS = [ "->", "->>", "#>", "#>>", ] # https://www.elastic.co/guide/en/elasticsearch/reference/current/sql-data-types.html ELASTICSEARCH_TYPES = [ "binary", "boolean", "byte", "completion", "constant_keyword", "date", "date_range", "double", "double_range", "flattened", "float", "float_range", "geo_point", "geo_shape", "half_float", "integer", "integer_range", "interval_day", "interval_day_to_hour", "interval_day_to_minute", "interval_day_to_second", "interval_hour", "interval_hour_to_minute", "interval_hour_to_second", "interval_minute", "interval_minute_to_second", "interval_month", "interval_second", "interval_year", "interval_year_to_month", "ip", "keyword", "knn_vector", "long", "long_range", "nested", "null", "object", "scaled_float", "search_as_you_type", "shape", "short", "text", "time", ] # https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-params.html ELASTICSEARCH_MAPPING_PARAMETERS = [ "analyzer", "boost", "coerce", "copy_to", "doc_values", "dynamic", "eager_global_ordinals", "enabled", "fielddata", "fielddata_frequency_filter", "fields", "format", "ignore_above", "ignore_malformed", "index", "index_options", "index_phrases", "index_prefixes", "meta", "normalizer", "norms", "null_value", "position_increment_gap", "properties", "search_analyzer", "similarity", "store", "term_vector", ] CONCAT_TRANSFORM = "concat" MAPPING_TRANSFORM = "mapping" MOVE_TRANSFORM = "move" RENAME_TRANSFORM = "rename" REPLACE_TRANSFORM = "replace" TRANSFORM_TYPES = [ CONCAT_TRANSFORM, MAPPING_TRANSFORM, MOVE_TRANSFORM, RENAME_TRANSFORM, REPLACE_TRANSFORM, ] # default postgres schema DEFAULT_SCHEMA = "public" BUILTIN_SCHEMAS = ["information_schema"] # Primary key identifier META = "_meta" # Logical decoding output plugin PLUGIN = "test_decoding" # Trigger function TRIGGER_FUNC = "table_notify" # Views # added underscore to reduce chance of collisions MATERIALIZED_VIEW = "_view" MATERIALIZED_VIEW_COLUMNS = [ "foreign_keys", "indices", "primary_keys", "table_name", ] # Primary key delimiter PRIMARY_KEY_DELIMITER = "|" # Replication slot patterns LOGICAL_SLOT_PREFIX = re.compile( r"table\s\"?(?P<schema>[\w-]+)\"?.\"?(?P<table>[\w-]+)\"?:\s(?P<tg_op>[A-Z]+):" # noqa E501 ) LOGICAL_SLOT_SUFFIX = re.compile( '\s(?P<key>"?\w+"?)\[(?P<type>[\w\s]+)\]:(?P<value>[\w\'"\-]+)' )
/retake_pgsync-2.5.4-py3-none-any.whl/pgsync/constants.py
0.488283
0.263318
constants.py
pypi
from __future__ import annotations import re from dataclasses import dataclass from typing import Callable, Dict, Generator, List, Optional, Set, Tuple import sqlalchemy as sa from .constants import ( DEFAULT_SCHEMA, JSONB_OPERATORS, NODE_ATTRIBUTES, RELATIONSHIP_ATTRIBUTES, RELATIONSHIP_FOREIGN_KEYS, RELATIONSHIP_TYPES, RELATIONSHIP_VARIANTS, ) from .exc import ( ColumnNotFoundError, MultipleThroughTablesError, NodeAttributeError, RelationshipAttributeError, RelationshipError, RelationshipForeignKeyError, RelationshipTypeError, RelationshipVariantError, SchemaError, TableNotInNodeError, ) @dataclass class ForeignKey: foreign_key: Optional[dict] = None def __post_init__(self): """Foreignkey constructor.""" self.foreign_key: str = self.foreign_key or dict() self.parent: str = self.foreign_key.get("parent") self.child: str = self.foreign_key.get("child") if self.foreign_key: if sorted(self.foreign_key.keys()) != sorted( RELATIONSHIP_FOREIGN_KEYS ): raise RelationshipForeignKeyError( "ForeignKey Relationship must contain a parent and child." ) self.parent = self.foreign_key.get("parent") self.child = self.foreign_key.get("child") def __str__(self): return f"foreign_key: {self.parent}:{self.child}" @dataclass class Relationship: relationship: Optional[dict] = None def __post_init__(self): """Relationship constructor.""" self.relationship: dict = self.relationship or dict() self.type: str = self.relationship.get("type") self.variant: str = self.relationship.get("variant") self.tables: List[str] = self.relationship.get("through_tables", []) self.throughs: List[Node] = [] if not set(self.relationship.keys()).issubset( set(RELATIONSHIP_ATTRIBUTES) ): attrs = set(self.relationship.keys()).difference( set(RELATIONSHIP_ATTRIBUTES) ) raise RelationshipAttributeError( f"Relationship attribute {attrs} is invalid." ) if self.type and self.type not in RELATIONSHIP_TYPES: raise RelationshipTypeError( f'Relationship type "{self.type}" is invalid.' ) if self.variant and self.variant not in RELATIONSHIP_VARIANTS: raise RelationshipVariantError( f'Relationship variant "{self.variant}" is invalid.' ) if len(self.tables) > 1: raise MultipleThroughTablesError( f"Multiple through tables: {self.tables}" ) if self.type: self.type = self.type.lower() if self.variant: self.variant = self.variant.lower() self.foreign_key: ForeignKey = ForeignKey( self.relationship.get("foreign_key") ) def __str__(self): return f"relationship: {self.variant}.{self.type}:{self.tables}" @dataclass class Node(object): models: Callable table: str schema: str primary_key: Optional[list] = None label: Optional[str] = None transform: Optional[dict] = None columns: Optional[list] = None relationship: Optional[dict] = None parent: Optional[Node] = None base_tables: Optional[list] = None def __post_init__(self): self.model: sa.sql.Alias = self.models(self.table, self.schema) self.columns = self.columns or [] self.children: List[Node] = [] self.table_columns: List[str] = self.model.columns.keys() if not self.model.primary_keys: setattr(self.model, "primary_keys", self.primary_key) # columns to fetch self.column_names: List[str] = [ column for column in self.columns if isinstance(column, str) ] if not self.column_names: self.column_names = [str(column) for column in self.table_columns] for name in ("ctid", "oid", "xmin"): self.column_names.remove(name) if self.label is None: self.label = self.table self.setup() self.relationship: Relationship = Relationship(self.relationship) self._subquery = None self._filters: list = [] self._mapping: dict = {} for through_table in self.relationship.tables: self.relationship.throughs.append( Node( models=self.models, table=through_table, schema=self.schema, parent=self, primary_key=[], ) ) def __str__(self): return f"Node: {self.schema}.{self.label}" def __repr__(self): return self.__str__() def __hash__(self): return hash(self.name) def setup(self): self.columns = [] for column_name in self.column_names: tokens: Optional[list] = None if any(op in column_name for op in JSONB_OPERATORS): tokens = re.split( f"({'|'.join(JSONB_OPERATORS)})", column_name, ) if tokens: tokenized = self.model.c[tokens[0]] for token in tokens[1:]: if token in JSONB_OPERATORS: tokenized = tokenized.op(token) continue if token.isdigit(): token = int(token) tokenized = tokenized(token) self.columns.append( "_".join( [ x.replace("{", "").replace("}", "") for x in tokens if x not in JSONB_OPERATORS ] ) ) self.columns.append(tokenized) # compiled_query(self.columns[-1], 'JSONB Query') else: if column_name not in self.table_columns: raise ColumnNotFoundError( f'Column "{column_name}" not present on ' f'table "{self.table}"' ) self.columns.append(column_name) self.columns.append(self.model.c[column_name]) @property def primary_keys(self): return [ self.model.c[str(sa.text(primary_key))] for primary_key in self.model.primary_keys ] @property def is_root(self) -> bool: return self.parent is None @property def name(self) -> str: """Returns a fully qualified node name.""" return f"{self.schema}.{self.table}" def add_child(self, node: Node) -> None: """All nodes except the root node must have a relationship defined.""" node.parent: Node = self if not node.is_root and ( not node.relationship.type or not node.relationship.variant ): raise RelationshipError( f'Relationship not present on "{node.name}"' ) if node not in self.children: self.children.append(node) def display(self, prefix: str = "", leaf: bool = True) -> None: print( prefix, " - " if leaf else "|- ", f"{self.schema}.{self.label}", sep="", ) # noqa T001 prefix += " " if leaf else "| " for i, child in enumerate(self.children): leaf = i == (len(self.children) - 1) child.display(prefix, leaf) def traverse_breadth_first(self) -> Generator: stack: List[Node] = [self] while stack: node: Node = stack.pop(0) yield node for child in node.children: stack.append(child) def traverse_post_order(self) -> Generator: for child in self.children: yield from child.traverse_post_order() yield self @dataclass class Tree: models: Callable def __post_init__(self): self.tables: Set[str] = set() self.__nodes: Dict[Node] = {} self.root: Optional[Node] = None def display(self) -> None: self.root.display() def traverse_breadth_first(self) -> Generator: return self.root.traverse_breadth_first() def traverse_post_order(self) -> Generator: return self.root.traverse_post_order() def build(self, data: dict) -> Node: if not isinstance(data, dict): raise SchemaError( "Incompatible schema. Please run v2 schema migration" ) table: str = data.get("table") schema: str = data.get("schema", DEFAULT_SCHEMA) key: Tuple[str, str] = (schema, table) if table is None: raise TableNotInNodeError(f"Table not specified in node: {data}") if not set(data.keys()).issubset(set(NODE_ATTRIBUTES)): attrs = set(data.keys()).difference(set(NODE_ATTRIBUTES)) raise NodeAttributeError(f"Unknown node attribute(s): {attrs}") node: Node = Node( models=self.models, table=table, schema=schema, primary_key=data.get("primary_key", []), label=data.get("label", table), transform=data.get("transform", {}), columns=data.get("columns", []), relationship=data.get("relationship", {}), base_tables=data.get("base_tables", []), ) if self.root is None: self.root = node self.tables.add(node.table) for through in node.relationship.throughs: self.tables.add(through.table) for child in data.get("children", []): node.add_child(self.build(child)) self.__nodes[key] = node return node def get_node(self, table: str, schema: str) -> Node: """Get node by name.""" key: Tuple[str, str] = (schema, table) if key not in self.__nodes: for node in self.traverse_post_order(): if table == node.table and schema == node.schema: self.__nodes[key] = node return self.__nodes[key] else: for through in node.relationship.throughs: if table == through.table and schema == through.schema: self.__nodes[key] = through return self.__nodes[key] else: raise RuntimeError(f"Node for {schema}.{table} not found") return self.__nodes[key]
/retake_pgsync-2.5.4-py3-none-any.whl/pgsync/node.py
0.913614
0.152663
node.py
pypi