edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
import re import sys import copy import types import inspect import keyword import builtins import functools import _thread __all__ = ['dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING', # Helper functions. 'fields', 'asdict', 'astuple', 'make_dataclass', 'replace', 'is_dataclass', ] # Conditions for adding methods. The boxes indicate what action the # dataclass decorator takes. For all of these tables, when I talk # about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm # referring to the arguments to the @dataclass decorator. When # checking if a dunder method already exists, I mean check for an # entry in the class's __dict__. I never check to see if an attribute # is defined in a base class. # Key: # +=========+=========================================+ # + Value | Meaning | # +=========+=========================================+ # | <blank> | No action: no method is added. | # +---------+-----------------------------------------+ # | add | Generated method is added. | # +---------+-----------------------------------------+ # | raise | TypeError is raised. | # +---------+-----------------------------------------+ # | None | Attribute is set to None. | # +=========+=========================================+ # __init__ # # +--- init= parameter # | # v | | | # | no | yes | <--- class has __init__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __repr__ # # +--- repr= parameter # | # v | | | # | no | yes | <--- class has __repr__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __setattr__ # __delattr__ # # +--- frozen= parameter # | # v | | | # | no | yes | <--- class has __setattr__ or __delattr__ in __dict__? # +=======+=======+=======+ # | False | | | <- the default # +-------+-------+-------+ # | True | add | raise | # +=======+=======+=======+ # Raise because not adding these methods would break the "frozen-ness" # of the class. # __eq__ # # +--- eq= parameter # | # v | | | # | no | yes | <--- class has __eq__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __lt__ # __le__ # __gt__ # __ge__ # # +--- order= parameter # | # v | | | # | no | yes | <--- class has any comparison method in __dict__? # +=======+=======+=======+ # | False | | | <- the default # +-------+-------+-------+ # | True | add | raise | # +=======+=======+=======+ # Raise because to allow this case would interfere with using # functools.total_ordering. # __hash__ # +------------------- unsafe_hash= parameter # | +----------- eq= parameter # | | +--- frozen= parameter # | | | # v v v | | | # | no | yes | <--- class has explicitly defined __hash__ # +=======+=======+=======+========+========+ # | False | False | False | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | False | True | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | True | False | None | | <-- the default, not hashable # +-------+-------+-------+--------+--------+ # | False | True | True | add | | Frozen, so hashable, allows override # +-------+-------+-------+--------+--------+ # | True | False | False | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | False | True | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | True | False | add | raise | Not frozen, but hashable # +-------+-------+-------+--------+--------+ # | True | True | True | add | raise | Frozen, so hashable # +=======+=======+=======+========+========+ # For boxes that are blank, __hash__ is untouched and therefore # inherited from the base class. If the base is object, then # id-based hashing is used. # # Note that a class may already have __hash__=None if it specified an # __eq__ method in the class body (not one that was created by # @dataclass). # # See _hash_action (below) for a coded version of this table. # Raised when an attempt is made to modify a frozen class. class FrozenInstanceError(AttributeError): pass # A sentinel object for default values to signal that a default # factory will be used. This is given a nice repr() which will appear # in the function signature of dataclasses' constructors. class _HAS_DEFAULT_FACTORY_CLASS: def __repr__(self): return '<factory>' _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS() # A sentinel object to detect if a parameter is supplied or not. Use # a class to give it a better repr. class _MISSING_TYPE: pass MISSING = _MISSING_TYPE() # Since most per-field metadata will be unused, create an empty # read-only proxy that can be shared among all fields. _EMPTY_METADATA = types.MappingProxyType({}) # Markers for the various kinds of fields and pseudo-fields. class _FIELD_BASE: def __init__(self, name): self.name = name def __repr__(self): return self.name _FIELD = _FIELD_BASE('_FIELD') _FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR') _FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR') # The name of an attribute on the class where we store the Field # objects. Also used to check if a class is a Data Class. _FIELDS = '__dataclass_fields__' # The name of an attribute on the class that stores the parameters to # @dataclass. _PARAMS = '__dataclass_params__' # The name of the function, that if it exists, is called at the end of # __init__. _POST_INIT_NAME = '__post_init__' # String regex that string annotations for ClassVar or InitVar must match. # Allows "identifier.identifier[" or "identifier[". # https://bugs.python.org/issue33453 for details. _MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)') class _InitVarMeta(type): def __getitem__(self, params): return InitVar(params) class InitVar(metaclass=_InitVarMeta): __slots__ = ('type', ) def __init__(self, type): self.type = type def __repr__(self): return f'dataclasses.InitVar[{self.type.__name__}]' # Instances of Field are only ever created from within this module, # and only from the field() function, although Field instances are # exposed externally as (conceptually) read-only objects. # # name and type are filled in after the fact, not in __init__. # They're not known at the time this class is instantiated, but it's # convenient if they're available later. # # When cls._FIELDS is filled in with a list of Field objects, the name # and type fields will have been populated. class Field: __slots__ = ('name', 'type', 'default', 'default_factory', 'repr', 'hash', 'init', 'compare', 'metadata', '_field_type', # Private: not to be used by user code. ) def __init__(self, default, default_factory, init, repr, hash, compare, metadata): self.name = None self.type = None self.default = default self.default_factory = default_factory self.init = init self.repr = repr self.hash = hash self.compare = compare self.metadata = (_EMPTY_METADATA if metadata is None else types.MappingProxyType(metadata)) self._field_type = None def __repr__(self): return ('Field(' f'name={self.name!r},' f'type={self.type!r},' f'default={self.default!r},' f'default_factory={self.default_factory!r},' f'init={self.init!r},' f'repr={self.repr!r},' f'hash={self.hash!r},' f'compare={self.compare!r},' f'metadata={self.metadata!r},' f'_field_type={self._field_type}' ')') # This is used to support the PEP 487 __set_name__ protocol in the # case where we're using a field that contains a descriptor as a # default value. For details on __set_name__, see # https://www.python.org/dev/peps/pep-0487/#implementation-details. # # Note that in _process_class, this Field object is overwritten # with the default value, so the end result is a descriptor that # had __set_name__ called on it at the right time. def __set_name__(self, owner, name): func = getattr(type(self.default), '__set_name__', None) if func: # There is a __set_name__ method on the descriptor, call # it. func(self.default, owner, name) class _DataclassParams: __slots__ = ('init', 'repr', 'eq', 'order', 'unsafe_hash', 'frozen', ) def __init__(self, init, repr, eq, order, unsafe_hash, frozen): self.init = init self.repr = repr self.eq = eq self.order = order self.unsafe_hash = unsafe_hash self.frozen = frozen def __repr__(self): return ('_DataclassParams(' f'init={self.init!r},' f'repr={self.repr!r},' f'eq={self.eq!r},' f'order={self.order!r},' f'unsafe_hash={self.unsafe_hash!r},' f'frozen={self.frozen!r}' ')') # This function is used instead of exposing Field creation directly, # so that a type checker can be told (via overloads) that this is a # function whose type depends on its parameters. def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None): """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init is True, the field will be a parameter to the class's __init__() function. If repr is True, the field will be included in the object's repr(). If hash is True, the field will be included in the object's hash(). If compare is True, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. It is an error to specify both default and default_factory. """ if default is not MISSING and default_factory is not MISSING: raise ValueError('cannot specify both default and default_factory') return Field(default, default_factory, init, repr, hash, compare, metadata) def _tuple_str(obj_name, fields): # Return a string representing each field of obj_name as a tuple # member. So, if fields is ['x', 'y'] and obj_name is "self", # return "(self.x,self.y)". # Special case for the 0-tuple. if not fields: return '()' # Note the trailing comma, needed if this turns out to be a 1-tuple. return f'({','.join([f'{obj_name}.{f.name}" for f in fields])},)' # This function's logic is copied from "recursive_repr" function in # reprlib module to avoid dependency. def _recursive_repr(user_function): # Decorator to make a repr function return "..." for a recursive # call. repr_running = set() @functools.wraps(user_function) def wrapper(self): key = id(self), _thread.get_ident() if key in repr_running: return '...' repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper def _create_fn(name, args, body, *, globals=None, locals=None, return_type=MISSING): # Note that we mutate locals when exec() is called. Caller # beware! The only callers are internal to this module, so no # worries about external callers. if locals is None: locals = {} # __builtins__ may be the "builtins" module or # the value of its "__dict__", # so make sure "__builtins__" is the module. if globals is not None and '__builtins__' not in globals: globals['__builtins__'] = builtins return_annotation = '' if return_type is not MISSING: locals['_return_type'] = return_type return_annotation = '->_return_type' args = ','.join(args) body = '\n'.join(f' {b}' for b in body) # Compute the text of the entire function. txt = f'def {name}({args}){return_annotation}:\n{body}' exec(txt, globals, locals) return locals[name] def _field_assign(frozen, name, value, self_name): # If we're a frozen class, then assign to our fields in __init__ # via object.__setattr__. Otherwise, just use a simple # assignment. # # self_name is what "self" is called in this function: don't # hard-code "self", since that might be a field name. if frozen: return f'__builtins__.object.__setattr__({self_name},{name!r},{value})' return f'{self_name}.{name}={value}' def _field_init(f, frozen, globals, self_name): # Return the text of the line in the body of __init__ that will # initialize this field. default_name = f'_dflt_{f.name}' if f.default_factory is not MISSING: if f.init: # This field has a default factory. If a parameter is # given, use it. If not, call the factory. globals[default_name] = f.default_factory value = (f'{default_name}() ' f'if {f.name} is _HAS_DEFAULT_FACTORY ' f'else {f.name}') else: # This is a field that's not in the __init__ params, but # has a default factory function. It needs to be # initialized here by calling the factory function, # because there's no other way to initialize it. # For a field initialized with a default=defaultvalue, the # class dict just has the default value # (cls.fieldname=defaultvalue). But that won't work for a # default factory, the factory must be called in __init__ # and we must assign that to self.fieldname. We can't # fall back to the class dict's value, both because it's # not set, and because it might be different per-class # (which, after all, is why we have a factory function!). globals[default_name] = f.default_factory value = f'{default_name}()' else: # No default factory. if f.init: if f.default is MISSING: # There's no default, just do an assignment. value = f.name elif f.default is not MISSING: globals[default_name] = f.default value = f.name else: # This field does not need initialization. Signify that # to the caller by returning None. return None # Only test this now, so that we can create variables for the # default. However, return None to signify that we're not going # to actually do the assignment statement for InitVars. if f._field_type is _FIELD_INITVAR: return None # Now, actually generate the field assignment. return _field_assign(frozen, f.name, value, self_name) def _init_param(f): # Return the __init__ parameter string for this field. For # example, the equivalent of 'x:int=3' (except instead of 'int', # reference a variable set to int, and instead of '3', reference a # variable set to 3). if f.default is MISSING and f.default_factory is MISSING: # There's no default, and no default_factory, just output the # variable name and type. default = '' elif f.default is not MISSING: # There's a default, this will be the name that's used to look # it up. default = f'=_dflt_{f.name}' elif f.default_factory is not MISSING: # There's a factory function. Set a marker. default = '=_HAS_DEFAULT_FACTORY' return f'{f.name}:_type_{f.name}{default}' def _init_fn(fields, frozen, has_post_init, self_name): # fields contains both real fields and InitVar pseudo-fields. # Make sure we don't have fields without defaults following fields # with defaults. This actually would be caught when exec-ing the # function source code, but catching it here gives a better error # message, and future-proofs us in case we build up the function # using ast. seen_default = False for f in fields: # Only consider fields in the __init__ call. if f.init: if not (f.default is MISSING and f.default_factory is MISSING): seen_default = True elif seen_default: raise TypeError(f'non-default argument {f.name!r} ' 'follows default argument') globals = {'MISSING': MISSING, '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY} body_lines = [] for f in fields: line = _field_init(f, frozen, globals, self_name) # line is None means that this field doesn't require # initialization (it's a pseudo-field). Just skip it. if line: body_lines.append(line) # Does this class have a post-init function? if has_post_init: params_str = ','.join(f.name for f in fields if f._field_type is _FIELD_INITVAR) body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})') # If no body lines, use 'pass'. if not body_lines: body_lines = ['pass'] locals = {f'_type_{f.name}': f.type for f in fields} return _create_fn('__init__', [self_name] + [_init_param(f) for f in fields if f.init], body_lines, locals=locals, globals=globals, return_type=None) def _repr_fn(fields): fn = _create_fn('__repr__', ('self',), ['return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}" for f in fields]) + ')"']) return _recursive_repr(fn) def _frozen_get_del_attr(cls, fields): # XXX: globals is modified on the first call to _create_fn, then # the modified version is used in the second call. Is this okay? globals = {'cls': cls, 'FrozenInstanceError': FrozenInstanceError} if fields: fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)' else: # Special case for the zero-length tuple. fields_str = '()' return (_create_fn('__setattr__', ('self', 'name', 'value'), (f'if type(self) is cls or name in {fields_str}:', ' raise FrozenInstanceError(f"cannot assign to field {name!r}")', f'super(cls, self).__setattr__(name, value)'), globals=globals), _create_fn('__delattr__', ('self', 'name'), (f'if type(self) is cls or name in {fields_str}:', ' raise FrozenInstanceError(f"cannot delete field {name!r}")', f'super(cls, self).__delattr__(name)'), globals=globals), ) def _cmp_fn(name, op, self_tuple, other_tuple): # Create a comparison function. If the fields in the object are # named 'x' and 'y', then self_tuple is the string # '(self.x,self.y)' and other_tuple is the string # '(other.x,other.y)'. return _create_fn(name, ('self', 'other'), [ 'if other.__class__ is self.__class__:', f' return {self_tuple}{op}{other_tuple}', 'return NotImplemented']) def _hash_fn(fields): self_tuple = _tuple_str('self', fields) return _create_fn('__hash__', ('self',), [f'return hash({self_tuple})']) def _is_classvar(a_type, typing): # This test uses a typing internal class, but it's the best way to # test if this is a ClassVar. return (a_type is typing.ClassVar or (type(a_type) is typing._GenericAlias and a_type.__origin__ is typing.ClassVar)) def _is_initvar(a_type, dataclasses): # The module we're checking against is the module we're # currently in (dataclasses.py). return (a_type is dataclasses.InitVar or type(a_type) is dataclasses.InitVar) def _is_type(annotation, cls, a_module, a_type, is_type_predicate): # Given a type annotation string, does it refer to a_type in # a_module? For example, when checking that annotation denotes a # ClassVar, then a_module is typing, and a_type is # typing.ClassVar. # It's possible to look up a_module given a_type, but it involves # looking in sys.modules (again!), and seems like a waste since # the caller already knows a_module. # - annotation is a string type annotation # - cls is the class that this annotation was found in # - a_module is the module we want to match # - a_type is the type in that module we want to match # - is_type_predicate is a function called with (obj, a_module) # that determines if obj is of the desired type. # Since this test does not do a local namespace lookup (and # instead only a module (global) lookup), there are some things it # gets wrong. # With string annotations, cv0 will be detected as a ClassVar: # CV = ClassVar # @dataclass # class C0: # cv0: CV # But in this example cv1 will not be detected as a ClassVar: # @dataclass # class C1: # CV = ClassVar # cv1: CV # In C1, the code in this function (_is_type) will look up "CV" in # the module and not find it, so it will not consider cv1 as a # ClassVar. This is a fairly obscure corner case, and the best # way to fix it would be to eval() the string "CV" with the # correct global and local namespaces. However that would involve # a eval() penalty for every single field of every dataclass # that's defined. It was judged not worth it. match = _MODULE_IDENTIFIER_RE.match(annotation) if match: ns = None module_name = match.group(1) if not module_name: # No module name, assume the class's module did # "from dataclasses import InitVar". ns = sys.modules.get(cls.__module__).__dict__ else: # Look up module_name in the class's module. module = sys.modules.get(cls.__module__) if module and module.__dict__.get(module_name) is a_module: ns = sys.modules.get(a_type.__module__).__dict__ if ns and is_type_predicate(ns.get(match.group(2)), a_module): return True return False def _get_field(cls, a_name, a_type): # Return a Field object for this field name and type. ClassVars # and InitVars are also returned, but marked as such (see # f._field_type). # If the default value isn't derived from Field, then it's only a # normal default value. Convert it to a Field(). default = getattr(cls, a_name, MISSING) if isinstance(default, Field): f = default else: if isinstance(default, types.MemberDescriptorType): # This is a field in __slots__, so it has no default value. default = MISSING f = field(default=default) # Only at this point do we know the name and the type. Set them. f.name = a_name f.type = a_type # Assume it's a normal field until proven otherwise. We're next # going to decide if it's a ClassVar or InitVar, everything else # is just a normal field. f._field_type = _FIELD # In addition to checking for actual types here, also check for # string annotations. get_type_hints() won't always work for us # (see https://github.com/python/typing/issues/508 for example), # plus it's expensive and would require an eval for every stirng # annotation. So, make a best effort to see if this is a ClassVar # or InitVar using regex's and checking that the thing referenced # is actually of the correct type. # For the complete discussion, see https://bugs.python.org/issue33453 # If typing has not been imported, then it's impossible for any # annotation to be a ClassVar. So, only look for ClassVar if # typing has been imported by any module (not necessarily cls's # module). typing = sys.modules.get('typing') if typing: if (_is_classvar(a_type, typing) or (isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar))): f._field_type = _FIELD_CLASSVAR # If the type is InitVar, or if it's a matching string annotation, # then it's an InitVar. if f._field_type is _FIELD: # The module we're checking against is the module we're # currently in (dataclasses.py). dataclasses = sys.modules[__name__] if (_is_initvar(a_type, dataclasses) or (isinstance(f.type, str) and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, _is_initvar))): f._field_type = _FIELD_INITVAR # Validations for individual fields. This is delayed until now, # instead of in the Field() constructor, since only here do we # know the field name, which allows for better error reporting. # Special restrictions for ClassVar and InitVar. if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR): if f.default_factory is not MISSING: raise TypeError(f'field {f.name} cannot have a ' 'default factory') # Should I check for other field settings? default_factory # seems the most serious to check for. Maybe add others. For # example, how about init=False (or really, # init=<not-the-default-init-value>)? It makes no sense for # ClassVar and InitVar to specify init=<anything>. # For real fields, disallow mutable defaults for known types. if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)): raise ValueError(f'mutable default {type(f.default)} for field ' f'{f.name} is not allowed: use default_factory') return f def _set_new_attribute(cls, name, value): # Never overwrites an existing attribute. Returns True if the # attribute already exists. if name in cls.__dict__: return True setattr(cls, name, value) return False # Decide if/how we're going to create a hash function. Key is # (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to # take. The common case is to do nothing, so instead of providing a # function that is a no-op, use None to signify that. def _hash_set_none(cls, fields): return None def _hash_add(cls, fields): flds = [f for f in fields if (f.compare if f.hash is None else f.hash)] return _hash_fn(flds) def _hash_exception(cls, fields): # Raise an exception. raise TypeError(f'Cannot overwrite attribute __hash__ ' f'in class {cls.__name__}') # # +-------------------------------------- unsafe_hash? # | +------------------------------- eq? # | | +------------------------ frozen? # | | | +---------------- has-explicit-hash? # | | | | # | | | | +------- action # | | | | | # v v v v v _hash_action = {(False, False, False, False): None, (False, False, False, True ): None, (False, False, True, False): None, (False, False, True, True ): None, (False, True, False, False): _hash_set_none, (False, True, False, True ): None, (False, True, True, False): _hash_add, (False, True, True, True ): None, (True, False, False, False): _hash_add, (True, False, False, True ): _hash_exception, (True, False, True, False): _hash_add, (True, False, True, True ): _hash_exception, (True, True, False, False): _hash_add, (True, True, False, True ): _hash_exception, (True, True, True, False): _hash_add, (True, True, True, True ): _hash_exception, } # See https://bugs.python.org/issue32929#msg312829 for an if-statement # version of this table. def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): # Now that dicts retain insertion order, there's no reason to use # an ordered dict. I am leveraging that ordering here, because # derived class fields overwrite base class fields, but the order # is defined by the base class, which is found first. fields = {} setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen)) # Find our base classes in reverse MRO order, and exclude # ourselves. In reversed order so that more derived classes # override earlier field definitions in base classes. As long as # we're iterating over them, see if any are frozen. any_frozen_base = False has_dataclass_bases = False for b in cls.__mro__[-1:0:-1]: # Only process classes that have been processed by our # decorator. That is, they have a _FIELDS attribute. base_fields = getattr(b, _FIELDS, None) if base_fields: has_dataclass_bases = True for f in base_fields.values(): fields[f.name] = f if getattr(b, _PARAMS).frozen: any_frozen_base = True # Annotations that are defined in this class (not in base # classes). If __annotations__ isn't present, then this class # adds no new annotations. We use this to compute fields that are # added by this class. # # Fields are found from cls_annotations, which is guaranteed to be # ordered. Default values are from class attributes, if a field # has a default. If the default value is a Field(), then it # contains additional info beyond (and possibly including) the # actual default value. Pseudo-fields ClassVars and InitVars are # included, despite the fact that they're not real fields. That's # dealt with later. cls_annotations = cls.__dict__.get('__annotations__', {}) # Now find fields in our class. While doing so, validate some # things, and set the default values (as class attributes) where # we can. cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()] for f in cls_fields: fields[f.name] = f # If the class attribute (which is the default value for this # field) exists and is of type 'Field', replace it with the # real default. This is so that normal class introspection # sees a real default value, not a Field. if isinstance(getattr(cls, f.name, None), Field): if f.default is MISSING: # If there's no default, delete the class attribute. # This happens if we specify field(repr=False), for # example (that is, we specified a field object, but # no default value). Also if we're using a default # factory. The class attribute should not be set at # all in the post-processed class. delattr(cls, f.name) else: setattr(cls, f.name, f.default) # Do we have any Field members that don't also have annotations? for name, value in cls.__dict__.items(): if isinstance(value, Field) and not name in cls_annotations: raise TypeError(f'{name!r} is a field but has no type annotation') # Check rules that apply if we are derived from any dataclasses. if has_dataclass_bases: # Raise an exception if any of our bases are frozen, but we're not. if any_frozen_base and not frozen: raise TypeError('cannot inherit non-frozen dataclass from a ' 'frozen one') # Raise an exception if we're frozen, but none of our bases are. if not any_frozen_base and frozen: raise TypeError('cannot inherit frozen dataclass from a ' 'non-frozen one') # Remember all of the fields on our class (including bases). This # also marks this class as being a dataclass. setattr(cls, _FIELDS, fields) # Was this class defined with an explicit __hash__? Note that if # __eq__ is defined in this class, then python will automatically # set __hash__ to None. This is a heuristic, as it's possible # that such a __hash__ == None was not auto-generated, but it # close enough. class_hash = cls.__dict__.get('__hash__', MISSING) has_explicit_hash = not (class_hash is MISSING or (class_hash is None and '__eq__' in cls.__dict__)) # If we're generating ordering methods, we must be generating the # eq methods. if order and not eq: raise ValueError('eq must be true if order is true') if init: # Does this class have a post-init function? has_post_init = hasattr(cls, _POST_INIT_NAME) # Include InitVars and regular fields (so, not ClassVars). flds = [f for f in fields.values() if f._field_type in (_FIELD, _FIELD_INITVAR)] _set_new_attribute(cls, '__init__', _init_fn(flds, frozen, has_post_init, # The name to use for the "self" # param in __init__. Use "self" # if possible. '__dataclass_self__' if 'self' in fields else 'self', )) # Get the fields as a list, and include only real fields. This is # used in all of the following methods. field_list = [f for f in fields.values() if f._field_type is _FIELD] if repr: flds = [f for f in field_list if f.repr] _set_new_attribute(cls, '__repr__', _repr_fn(flds)) if eq: # Create _eq__ method. There's no need for a __ne__ method, # since python will call __eq__ and negate it. flds = [f for f in field_list if f.compare] self_tuple = _tuple_str('self', flds) other_tuple = _tuple_str('other', flds) _set_new_attribute(cls, '__eq__', _cmp_fn('__eq__', '==', self_tuple, other_tuple)) if order: # Create and set the ordering methods. flds = [f for f in field_list if f.compare] self_tuple = _tuple_str('self', flds) other_tuple = _tuple_str('other', flds) for name, op in [('__lt__', '<'), ('__le__', '<='), ('__gt__', '>'), ('__ge__', '>='), ]: if _set_new_attribute(cls, name, _cmp_fn(name, op, self_tuple, other_tuple)): raise TypeError(f'Cannot overwrite attribute {name} ' f'in class {cls.__name__}. Consider using ' 'functools.total_ordering') if frozen: for fn in _frozen_get_del_attr(cls, field_list): if _set_new_attribute(cls, fn.__name__, fn): raise TypeError(f'Cannot overwrite attribute {fn.__name__} ' f'in class {cls.__name__}') # Decide if/how we're going to create a hash function. hash_action = _hash_action[bool(unsafe_hash), bool(eq), bool(frozen), has_explicit_hash] if hash_action: # No need to call _set_new_attribute here, since by the time # we're here the overwriting is unconditional. cls.__hash__ = hash_action(cls, field_list) if not getattr(cls, '__doc__'): # Create a class doc-string. cls.__doc__ = (cls.__name__ + str(inspect.signature(cls)).replace(' -> None', '')) return cls def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): """Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method function is added. If frozen is true, fields may not be assigned to after instance creation. """ def wrap(cls): return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen) # See if we're being called as @dataclass or @dataclass(). if cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(cls) def fields(class_or_instance): """Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field. """ # Might it be worth caching this, per class? try: fields = getattr(class_or_instance, _FIELDS) except AttributeError: raise TypeError('must be called with a dataclass type or instance') # Exclude pseudo-fields. Note that fields is sorted by insertion # order, so the order of the tuple is as the fields were defined. return tuple(f for f in fields.values() if f._field_type is _FIELD) def _is_dataclass_instance(obj): """Returns True if obj is an instance of a dataclass.""" return not isinstance(obj, type) and hasattr(obj, _FIELDS) def is_dataclass(obj): """Returns True if obj is a dataclass or an instance of a dataclass.""" return hasattr(obj, _FIELDS) def asdict(obj, *, dict_factory=dict): """Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage: @dataclass class C: x: int y: int c = C(1, 2) assert asdict(c) == {'x': 1, 'y': 2} If given, 'dict_factory' will be used instead of built-in dict. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts. """ if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") return _asdict_inner(obj, dict_factory) def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) return dict_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): # obj is a namedtuple. Recurse into it, but the returned # object is another namedtuple of the same type. This is # similar to how other list- or tuple-derived classes are # treated (see below), but we just need to create them # differently because a namedtuple's __init__ needs to be # called differently (see bpo-34363). # I'm not using namedtuple's _asdict() # method, because: # - it does not recurse in to the namedtuple fields and # convert them to dicts (using dict_factory). # - I don't actually want to return a dict here. The the main # use case here is json.dumps, and it handles converting # namedtuples to lists. Admittedly we're losing some # information here when we produce a json list instead of a # dict. Note that if we returned dicts here instead of # namedtuples, we could no longer call asdict() on a data # structure where a namedtuple was used as a dict key. return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj]) elif isinstance(obj, (list, tuple)): # Assume we can create an object of this type by passing in a # generator (which is not true for namedtuples, handled # above). return type(obj)(_asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) def astuple(obj, *, tuple_factory=tuple): """Return the fields of a dataclass instance as a new tuple of field values. Example usage:: @dataclass class C: x: int y: int c = C(1, 2) assert astuple(c) == (1, 2) If given, 'tuple_factory' will be used instead of built-in tuple. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts. """ if not _is_dataclass_instance(obj): raise TypeError("astuple() should be called on dataclass instances") return _astuple_inner(obj, tuple_factory) def _astuple_inner(obj, tuple_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _astuple_inner(getattr(obj, f.name), tuple_factory) result.append(value) return tuple_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): # obj is a namedtuple. Recurse into it, but the returned # object is another namedtuple of the same type. This is # similar to how other list- or tuple-derived classes are # treated (see below), but we just need to create them # differently because a namedtuple's __init__ needs to be # called differently (see bpo-34363). return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj]) elif isinstance(obj, (list, tuple)): # Assume we can create an object of this type by passing in a # generator (which is not true for namedtuples, handled # above). return type(obj)(_astuple_inner(v, tuple_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is omitted, use the string 'typing.Any'. Field objects are created by the equivalent of calling 'field(name, type [, Field-info])'. C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,)) is equivalent to: @dataclass class C(Base): x: 'typing.Any' y: int z: int = field(init=False) For the bases and namespace parameters, see the builtin type() function. The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to dataclass(). """ if namespace is None: namespace = {} else: # Copy namespace since we're going to mutate it. namespace = namespace.copy() # While we're looking through the field names, validate that they # are identifiers, are not keywords, and not duplicates. seen = set() anns = {} for item in fields: if isinstance(item, str): name = item tp = 'typing.Any' elif len(item) == 2: name, tp, = item elif len(item) == 3: name, tp, spec = item namespace[name] = spec else: raise TypeError(f'Invalid field: {item!r}') if not isinstance(name, str) or not name.isidentifier(): raise TypeError(f'Field names must be valid identifiers: {name!r}') if keyword.iskeyword(name): raise TypeError(f'Field names must not be keywords: {name!r}') if name in seen: raise TypeError(f'Field name duplicated: {name!r}') seen.add(name) anns[name] = tp namespace['__annotations__'] = anns # We use `types.new_class()` instead of simply `type()` to allow dynamic creation # of generic dataclassses. cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace)) return dataclass(cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen) def replace(obj, /, **changes): """Return a new object replacing specified fields with new values. This is especially useful for frozen classes. Example usage: @dataclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = replace(c, x=3) assert c1.x == 3 and c1.y == 2 """ # We're going to mutate 'changes', but that's okay because it's a # new dict, even if called with 'replace(obj, **my_changes)'. if not _is_dataclass_instance(obj): raise TypeError("replace() should be called on dataclass instances") # It's an error to have init=False fields in 'changes'. # If a field is not in 'changes', read its value from the provided obj. for f in getattr(obj, _FIELDS).values(): # Only consider normal fields or InitVars. if f._field_type is _FIELD_CLASSVAR: continue if not f.init: # Error if this field is specified in changes. if f.name in changes: raise ValueError(f'field {f.name} is declared with ' 'init=False, it cannot be specified with ' 'replace()') continue if f.name not in changes: if f._field_type is _FIELD_INITVAR: raise ValueError(f"InitVar {f.name!r} " 'must be specified with replace()') changes[f.name] = getattr(obj, f.name) # Create the new object, which calls __init__() and # __post_init__() (if defined), using all of the init fields we've # added and/or left in 'changes'. If there are values supplied in # changes that aren't fields, this will correctly raise a # TypeError. return obj.__class__(**changes)
import re import sys import copy import types import inspect import keyword import builtins import functools import _thread __all__ = ['dataclass', 'field', 'Field', 'FrozenInstanceError', 'InitVar', 'MISSING', # Helper functions. 'fields', 'asdict', 'astuple', 'make_dataclass', 'replace', 'is_dataclass', ] # Conditions for adding methods. The boxes indicate what action the # dataclass decorator takes. For all of these tables, when I talk # about init=, repr=, eq=, order=, unsafe_hash=, or frozen=, I'm # referring to the arguments to the @dataclass decorator. When # checking if a dunder method already exists, I mean check for an # entry in the class's __dict__. I never check to see if an attribute # is defined in a base class. # Key: # +=========+=========================================+ # + Value | Meaning | # +=========+=========================================+ # | <blank> | No action: no method is added. | # +---------+-----------------------------------------+ # | add | Generated method is added. | # +---------+-----------------------------------------+ # | raise | TypeError is raised. | # +---------+-----------------------------------------+ # | None | Attribute is set to None. | # +=========+=========================================+ # __init__ # # +--- init= parameter # | # v | | | # | no | yes | <--- class has __init__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __repr__ # # +--- repr= parameter # | # v | | | # | no | yes | <--- class has __repr__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __setattr__ # __delattr__ # # +--- frozen= parameter # | # v | | | # | no | yes | <--- class has __setattr__ or __delattr__ in __dict__? # +=======+=======+=======+ # | False | | | <- the default # +-------+-------+-------+ # | True | add | raise | # +=======+=======+=======+ # Raise because not adding these methods would break the "frozen-ness" # of the class. # __eq__ # # +--- eq= parameter # | # v | | | # | no | yes | <--- class has __eq__ in __dict__? # +=======+=======+=======+ # | False | | | # +-------+-------+-------+ # | True | add | | <- the default # +=======+=======+=======+ # __lt__ # __le__ # __gt__ # __ge__ # # +--- order= parameter # | # v | | | # | no | yes | <--- class has any comparison method in __dict__? # +=======+=======+=======+ # | False | | | <- the default # +-------+-------+-------+ # | True | add | raise | # +=======+=======+=======+ # Raise because to allow this case would interfere with using # functools.total_ordering. # __hash__ # +------------------- unsafe_hash= parameter # | +----------- eq= parameter # | | +--- frozen= parameter # | | | # v v v | | | # | no | yes | <--- class has explicitly defined __hash__ # +=======+=======+=======+========+========+ # | False | False | False | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | False | True | | | No __eq__, use the base class __hash__ # +-------+-------+-------+--------+--------+ # | False | True | False | None | | <-- the default, not hashable # +-------+-------+-------+--------+--------+ # | False | True | True | add | | Frozen, so hashable, allows override # +-------+-------+-------+--------+--------+ # | True | False | False | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | False | True | add | raise | Has no __eq__, but hashable # +-------+-------+-------+--------+--------+ # | True | True | False | add | raise | Not frozen, but hashable # +-------+-------+-------+--------+--------+ # | True | True | True | add | raise | Frozen, so hashable # +=======+=======+=======+========+========+ # For boxes that are blank, __hash__ is untouched and therefore # inherited from the base class. If the base is object, then # id-based hashing is used. # # Note that a class may already have __hash__=None if it specified an # __eq__ method in the class body (not one that was created by # @dataclass). # # See _hash_action (below) for a coded version of this table. # Raised when an attempt is made to modify a frozen class. class FrozenInstanceError(AttributeError): pass # A sentinel object for default values to signal that a default # factory will be used. This is given a nice repr() which will appear # in the function signature of dataclasses' constructors. class _HAS_DEFAULT_FACTORY_CLASS: def __repr__(self): return '<factory>' _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS() # A sentinel object to detect if a parameter is supplied or not. Use # a class to give it a better repr. class _MISSING_TYPE: pass MISSING = _MISSING_TYPE() # Since most per-field metadata will be unused, create an empty # read-only proxy that can be shared among all fields. _EMPTY_METADATA = types.MappingProxyType({}) # Markers for the various kinds of fields and pseudo-fields. class _FIELD_BASE: def __init__(self, name): self.name = name def __repr__(self): return self.name _FIELD = _FIELD_BASE('_FIELD') _FIELD_CLASSVAR = _FIELD_BASE('_FIELD_CLASSVAR') _FIELD_INITVAR = _FIELD_BASE('_FIELD_INITVAR') # The name of an attribute on the class where we store the Field # objects. Also used to check if a class is a Data Class. _FIELDS = '__dataclass_fields__' # The name of an attribute on the class that stores the parameters to # @dataclass. _PARAMS = '__dataclass_params__' # The name of the function, that if it exists, is called at the end of # __init__. _POST_INIT_NAME = '__post_init__' # String regex that string annotations for ClassVar or InitVar must match. # Allows "identifier.identifier[" or "identifier[". # https://bugs.python.org/issue33453 for details. _MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)') class _InitVarMeta(type): def __getitem__(self, params): return InitVar(params) class InitVar(metaclass=_InitVarMeta): __slots__ = ('type', ) def __init__(self, type): self.type = type def __repr__(self): return f'dataclasses.InitVar[{self.type.__name__}]' # Instances of Field are only ever created from within this module, # and only from the field() function, although Field instances are # exposed externally as (conceptually) read-only objects. # # name and type are filled in after the fact, not in __init__. # They're not known at the time this class is instantiated, but it's # convenient if they're available later. # # When cls._FIELDS is filled in with a list of Field objects, the name # and type fields will have been populated. class Field: __slots__ = ('name', 'type', 'default', 'default_factory', 'repr', 'hash', 'init', 'compare', 'metadata', '_field_type', # Private: not to be used by user code. ) def __init__(self, default, default_factory, init, repr, hash, compare, metadata): self.name = None self.type = None self.default = default self.default_factory = default_factory self.init = init self.repr = repr self.hash = hash self.compare = compare self.metadata = (_EMPTY_METADATA if metadata is None else types.MappingProxyType(metadata)) self._field_type = None def __repr__(self): return ('Field(' f'name={self.name!r},' f'type={self.type!r},' f'default={self.default!r},' f'default_factory={self.default_factory!r},' f'init={self.init!r},' f'repr={self.repr!r},' f'hash={self.hash!r},' f'compare={self.compare!r},' f'metadata={self.metadata!r},' f'_field_type={self._field_type}' ')') # This is used to support the PEP 487 __set_name__ protocol in the # case where we're using a field that contains a descriptor as a # default value. For details on __set_name__, see # https://www.python.org/dev/peps/pep-0487/#implementation-details. # # Note that in _process_class, this Field object is overwritten # with the default value, so the end result is a descriptor that # had __set_name__ called on it at the right time. def __set_name__(self, owner, name): func = getattr(type(self.default), '__set_name__', None) if func: # There is a __set_name__ method on the descriptor, call # it. func(self.default, owner, name) class _DataclassParams: __slots__ = ('init', 'repr', 'eq', 'order', 'unsafe_hash', 'frozen', ) def __init__(self, init, repr, eq, order, unsafe_hash, frozen): self.init = init self.repr = repr self.eq = eq self.order = order self.unsafe_hash = unsafe_hash self.frozen = frozen def __repr__(self): return ('_DataclassParams(' f'init={self.init!r},' f'repr={self.repr!r},' f'eq={self.eq!r},' f'order={self.order!r},' f'unsafe_hash={self.unsafe_hash!r},' f'frozen={self.frozen!r}' ')') # This function is used instead of exposing Field creation directly, # so that a type checker can be told (via overloads) that this is a # function whose type depends on its parameters. def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None): """Return an object to identify dataclass fields. default is the default value of the field. default_factory is a 0-argument function called to initialize a field's value. If init is True, the field will be a parameter to the class's __init__() function. If repr is True, the field will be included in the object's repr(). If hash is True, the field will be included in the object's hash(). If compare is True, the field will be used in comparison functions. metadata, if specified, must be a mapping which is stored but not otherwise examined by dataclass. It is an error to specify both default and default_factory. """ if default is not MISSING and default_factory is not MISSING: raise ValueError('cannot specify both default and default_factory') return Field(default, default_factory, init, repr, hash, compare, metadata) def _tuple_str(obj_name, fields): # Return a string representing each field of obj_name as a tuple # member. So, if fields is ['x', 'y'] and obj_name is "self", # return "(self.x,self.y)". # Special case for the 0-tuple. if not fields: return '()' # Note the trailing comma, needed if this turns out to be a 1-tuple. return f'({",".join([f"{obj_name}.{f.name}" for f in fields])},)' # This function's logic is copied from "recursive_repr" function in # reprlib module to avoid dependency. def _recursive_repr(user_function): # Decorator to make a repr function return "..." for a recursive # call. repr_running = set() @functools.wraps(user_function) def wrapper(self): key = id(self), _thread.get_ident() if key in repr_running: return '...' repr_running.add(key) try: result = user_function(self) finally: repr_running.discard(key) return result return wrapper def _create_fn(name, args, body, *, globals=None, locals=None, return_type=MISSING): # Note that we mutate locals when exec() is called. Caller # beware! The only callers are internal to this module, so no # worries about external callers. if locals is None: locals = {} # __builtins__ may be the "builtins" module or # the value of its "__dict__", # so make sure "__builtins__" is the module. if globals is not None and '__builtins__' not in globals: globals['__builtins__'] = builtins return_annotation = '' if return_type is not MISSING: locals['_return_type'] = return_type return_annotation = '->_return_type' args = ','.join(args) body = '\n'.join(f' {b}' for b in body) # Compute the text of the entire function. txt = f'def {name}({args}){return_annotation}:\n{body}' exec(txt, globals, locals) return locals[name] def _field_assign(frozen, name, value, self_name): # If we're a frozen class, then assign to our fields in __init__ # via object.__setattr__. Otherwise, just use a simple # assignment. # # self_name is what "self" is called in this function: don't # hard-code "self", since that might be a field name. if frozen: return f'__builtins__.object.__setattr__({self_name},{name!r},{value})' return f'{self_name}.{name}={value}' def _field_init(f, frozen, globals, self_name): # Return the text of the line in the body of __init__ that will # initialize this field. default_name = f'_dflt_{f.name}' if f.default_factory is not MISSING: if f.init: # This field has a default factory. If a parameter is # given, use it. If not, call the factory. globals[default_name] = f.default_factory value = (f'{default_name}() ' f'if {f.name} is _HAS_DEFAULT_FACTORY ' f'else {f.name}') else: # This is a field that's not in the __init__ params, but # has a default factory function. It needs to be # initialized here by calling the factory function, # because there's no other way to initialize it. # For a field initialized with a default=defaultvalue, the # class dict just has the default value # (cls.fieldname=defaultvalue). But that won't work for a # default factory, the factory must be called in __init__ # and we must assign that to self.fieldname. We can't # fall back to the class dict's value, both because it's # not set, and because it might be different per-class # (which, after all, is why we have a factory function!). globals[default_name] = f.default_factory value = f'{default_name}()' else: # No default factory. if f.init: if f.default is MISSING: # There's no default, just do an assignment. value = f.name elif f.default is not MISSING: globals[default_name] = f.default value = f.name else: # This field does not need initialization. Signify that # to the caller by returning None. return None # Only test this now, so that we can create variables for the # default. However, return None to signify that we're not going # to actually do the assignment statement for InitVars. if f._field_type is _FIELD_INITVAR: return None # Now, actually generate the field assignment. return _field_assign(frozen, f.name, value, self_name) def _init_param(f): # Return the __init__ parameter string for this field. For # example, the equivalent of 'x:int=3' (except instead of 'int', # reference a variable set to int, and instead of '3', reference a # variable set to 3). if f.default is MISSING and f.default_factory is MISSING: # There's no default, and no default_factory, just output the # variable name and type. default = '' elif f.default is not MISSING: # There's a default, this will be the name that's used to look # it up. default = f'=_dflt_{f.name}' elif f.default_factory is not MISSING: # There's a factory function. Set a marker. default = '=_HAS_DEFAULT_FACTORY' return f'{f.name}:_type_{f.name}{default}' def _init_fn(fields, frozen, has_post_init, self_name): # fields contains both real fields and InitVar pseudo-fields. # Make sure we don't have fields without defaults following fields # with defaults. This actually would be caught when exec-ing the # function source code, but catching it here gives a better error # message, and future-proofs us in case we build up the function # using ast. seen_default = False for f in fields: # Only consider fields in the __init__ call. if f.init: if not (f.default is MISSING and f.default_factory is MISSING): seen_default = True elif seen_default: raise TypeError(f'non-default argument {f.name!r} ' 'follows default argument') globals = {'MISSING': MISSING, '_HAS_DEFAULT_FACTORY': _HAS_DEFAULT_FACTORY} body_lines = [] for f in fields: line = _field_init(f, frozen, globals, self_name) # line is None means that this field doesn't require # initialization (it's a pseudo-field). Just skip it. if line: body_lines.append(line) # Does this class have a post-init function? if has_post_init: params_str = ','.join(f.name for f in fields if f._field_type is _FIELD_INITVAR) body_lines.append(f'{self_name}.{_POST_INIT_NAME}({params_str})') # If no body lines, use 'pass'. if not body_lines: body_lines = ['pass'] locals = {f'_type_{f.name}': f.type for f in fields} return _create_fn('__init__', [self_name] + [_init_param(f) for f in fields if f.init], body_lines, locals=locals, globals=globals, return_type=None) def _repr_fn(fields): fn = _create_fn('__repr__', ('self',), ['return self.__class__.__qualname__ + f"(' + ', '.join([f"{f.name}={{self.{f.name}!r}}" for f in fields]) + ')"']) return _recursive_repr(fn) def _frozen_get_del_attr(cls, fields): # XXX: globals is modified on the first call to _create_fn, then # the modified version is used in the second call. Is this okay? globals = {'cls': cls, 'FrozenInstanceError': FrozenInstanceError} if fields: fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)' else: # Special case for the zero-length tuple. fields_str = '()' return (_create_fn('__setattr__', ('self', 'name', 'value'), (f'if type(self) is cls or name in {fields_str}:', ' raise FrozenInstanceError(f"cannot assign to field {name!r}")', f'super(cls, self).__setattr__(name, value)'), globals=globals), _create_fn('__delattr__', ('self', 'name'), (f'if type(self) is cls or name in {fields_str}:', ' raise FrozenInstanceError(f"cannot delete field {name!r}")', f'super(cls, self).__delattr__(name)'), globals=globals), ) def _cmp_fn(name, op, self_tuple, other_tuple): # Create a comparison function. If the fields in the object are # named 'x' and 'y', then self_tuple is the string # '(self.x,self.y)' and other_tuple is the string # '(other.x,other.y)'. return _create_fn(name, ('self', 'other'), [ 'if other.__class__ is self.__class__:', f' return {self_tuple}{op}{other_tuple}', 'return NotImplemented']) def _hash_fn(fields): self_tuple = _tuple_str('self', fields) return _create_fn('__hash__', ('self',), [f'return hash({self_tuple})']) def _is_classvar(a_type, typing): # This test uses a typing internal class, but it's the best way to # test if this is a ClassVar. return (a_type is typing.ClassVar or (type(a_type) is typing._GenericAlias and a_type.__origin__ is typing.ClassVar)) def _is_initvar(a_type, dataclasses): # The module we're checking against is the module we're # currently in (dataclasses.py). return (a_type is dataclasses.InitVar or type(a_type) is dataclasses.InitVar) def _is_type(annotation, cls, a_module, a_type, is_type_predicate): # Given a type annotation string, does it refer to a_type in # a_module? For example, when checking that annotation denotes a # ClassVar, then a_module is typing, and a_type is # typing.ClassVar. # It's possible to look up a_module given a_type, but it involves # looking in sys.modules (again!), and seems like a waste since # the caller already knows a_module. # - annotation is a string type annotation # - cls is the class that this annotation was found in # - a_module is the module we want to match # - a_type is the type in that module we want to match # - is_type_predicate is a function called with (obj, a_module) # that determines if obj is of the desired type. # Since this test does not do a local namespace lookup (and # instead only a module (global) lookup), there are some things it # gets wrong. # With string annotations, cv0 will be detected as a ClassVar: # CV = ClassVar # @dataclass # class C0: # cv0: CV # But in this example cv1 will not be detected as a ClassVar: # @dataclass # class C1: # CV = ClassVar # cv1: CV # In C1, the code in this function (_is_type) will look up "CV" in # the module and not find it, so it will not consider cv1 as a # ClassVar. This is a fairly obscure corner case, and the best # way to fix it would be to eval() the string "CV" with the # correct global and local namespaces. However that would involve # a eval() penalty for every single field of every dataclass # that's defined. It was judged not worth it. match = _MODULE_IDENTIFIER_RE.match(annotation) if match: ns = None module_name = match.group(1) if not module_name: # No module name, assume the class's module did # "from dataclasses import InitVar". ns = sys.modules.get(cls.__module__).__dict__ else: # Look up module_name in the class's module. module = sys.modules.get(cls.__module__) if module and module.__dict__.get(module_name) is a_module: ns = sys.modules.get(a_type.__module__).__dict__ if ns and is_type_predicate(ns.get(match.group(2)), a_module): return True return False def _get_field(cls, a_name, a_type): # Return a Field object for this field name and type. ClassVars # and InitVars are also returned, but marked as such (see # f._field_type). # If the default value isn't derived from Field, then it's only a # normal default value. Convert it to a Field(). default = getattr(cls, a_name, MISSING) if isinstance(default, Field): f = default else: if isinstance(default, types.MemberDescriptorType): # This is a field in __slots__, so it has no default value. default = MISSING f = field(default=default) # Only at this point do we know the name and the type. Set them. f.name = a_name f.type = a_type # Assume it's a normal field until proven otherwise. We're next # going to decide if it's a ClassVar or InitVar, everything else # is just a normal field. f._field_type = _FIELD # In addition to checking for actual types here, also check for # string annotations. get_type_hints() won't always work for us # (see https://github.com/python/typing/issues/508 for example), # plus it's expensive and would require an eval for every stirng # annotation. So, make a best effort to see if this is a ClassVar # or InitVar using regex's and checking that the thing referenced # is actually of the correct type. # For the complete discussion, see https://bugs.python.org/issue33453 # If typing has not been imported, then it's impossible for any # annotation to be a ClassVar. So, only look for ClassVar if # typing has been imported by any module (not necessarily cls's # module). typing = sys.modules.get('typing') if typing: if (_is_classvar(a_type, typing) or (isinstance(f.type, str) and _is_type(f.type, cls, typing, typing.ClassVar, _is_classvar))): f._field_type = _FIELD_CLASSVAR # If the type is InitVar, or if it's a matching string annotation, # then it's an InitVar. if f._field_type is _FIELD: # The module we're checking against is the module we're # currently in (dataclasses.py). dataclasses = sys.modules[__name__] if (_is_initvar(a_type, dataclasses) or (isinstance(f.type, str) and _is_type(f.type, cls, dataclasses, dataclasses.InitVar, _is_initvar))): f._field_type = _FIELD_INITVAR # Validations for individual fields. This is delayed until now, # instead of in the Field() constructor, since only here do we # know the field name, which allows for better error reporting. # Special restrictions for ClassVar and InitVar. if f._field_type in (_FIELD_CLASSVAR, _FIELD_INITVAR): if f.default_factory is not MISSING: raise TypeError(f'field {f.name} cannot have a ' 'default factory') # Should I check for other field settings? default_factory # seems the most serious to check for. Maybe add others. For # example, how about init=False (or really, # init=<not-the-default-init-value>)? It makes no sense for # ClassVar and InitVar to specify init=<anything>. # For real fields, disallow mutable defaults for known types. if f._field_type is _FIELD and isinstance(f.default, (list, dict, set)): raise ValueError(f'mutable default {type(f.default)} for field ' f'{f.name} is not allowed: use default_factory') return f def _set_new_attribute(cls, name, value): # Never overwrites an existing attribute. Returns True if the # attribute already exists. if name in cls.__dict__: return True setattr(cls, name, value) return False # Decide if/how we're going to create a hash function. Key is # (unsafe_hash, eq, frozen, does-hash-exist). Value is the action to # take. The common case is to do nothing, so instead of providing a # function that is a no-op, use None to signify that. def _hash_set_none(cls, fields): return None def _hash_add(cls, fields): flds = [f for f in fields if (f.compare if f.hash is None else f.hash)] return _hash_fn(flds) def _hash_exception(cls, fields): # Raise an exception. raise TypeError(f'Cannot overwrite attribute __hash__ ' f'in class {cls.__name__}') # # +-------------------------------------- unsafe_hash? # | +------------------------------- eq? # | | +------------------------ frozen? # | | | +---------------- has-explicit-hash? # | | | | # | | | | +------- action # | | | | | # v v v v v _hash_action = {(False, False, False, False): None, (False, False, False, True ): None, (False, False, True, False): None, (False, False, True, True ): None, (False, True, False, False): _hash_set_none, (False, True, False, True ): None, (False, True, True, False): _hash_add, (False, True, True, True ): None, (True, False, False, False): _hash_add, (True, False, False, True ): _hash_exception, (True, False, True, False): _hash_add, (True, False, True, True ): _hash_exception, (True, True, False, False): _hash_add, (True, True, False, True ): _hash_exception, (True, True, True, False): _hash_add, (True, True, True, True ): _hash_exception, } # See https://bugs.python.org/issue32929#msg312829 for an if-statement # version of this table. def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): # Now that dicts retain insertion order, there's no reason to use # an ordered dict. I am leveraging that ordering here, because # derived class fields overwrite base class fields, but the order # is defined by the base class, which is found first. fields = {} setattr(cls, _PARAMS, _DataclassParams(init, repr, eq, order, unsafe_hash, frozen)) # Find our base classes in reverse MRO order, and exclude # ourselves. In reversed order so that more derived classes # override earlier field definitions in base classes. As long as # we're iterating over them, see if any are frozen. any_frozen_base = False has_dataclass_bases = False for b in cls.__mro__[-1:0:-1]: # Only process classes that have been processed by our # decorator. That is, they have a _FIELDS attribute. base_fields = getattr(b, _FIELDS, None) if base_fields: has_dataclass_bases = True for f in base_fields.values(): fields[f.name] = f if getattr(b, _PARAMS).frozen: any_frozen_base = True # Annotations that are defined in this class (not in base # classes). If __annotations__ isn't present, then this class # adds no new annotations. We use this to compute fields that are # added by this class. # # Fields are found from cls_annotations, which is guaranteed to be # ordered. Default values are from class attributes, if a field # has a default. If the default value is a Field(), then it # contains additional info beyond (and possibly including) the # actual default value. Pseudo-fields ClassVars and InitVars are # included, despite the fact that they're not real fields. That's # dealt with later. cls_annotations = cls.__dict__.get('__annotations__', {}) # Now find fields in our class. While doing so, validate some # things, and set the default values (as class attributes) where # we can. cls_fields = [_get_field(cls, name, type) for name, type in cls_annotations.items()] for f in cls_fields: fields[f.name] = f # If the class attribute (which is the default value for this # field) exists and is of type 'Field', replace it with the # real default. This is so that normal class introspection # sees a real default value, not a Field. if isinstance(getattr(cls, f.name, None), Field): if f.default is MISSING: # If there's no default, delete the class attribute. # This happens if we specify field(repr=False), for # example (that is, we specified a field object, but # no default value). Also if we're using a default # factory. The class attribute should not be set at # all in the post-processed class. delattr(cls, f.name) else: setattr(cls, f.name, f.default) # Do we have any Field members that don't also have annotations? for name, value in cls.__dict__.items(): if isinstance(value, Field) and not name in cls_annotations: raise TypeError(f'{name!r} is a field but has no type annotation') # Check rules that apply if we are derived from any dataclasses. if has_dataclass_bases: # Raise an exception if any of our bases are frozen, but we're not. if any_frozen_base and not frozen: raise TypeError('cannot inherit non-frozen dataclass from a ' 'frozen one') # Raise an exception if we're frozen, but none of our bases are. if not any_frozen_base and frozen: raise TypeError('cannot inherit frozen dataclass from a ' 'non-frozen one') # Remember all of the fields on our class (including bases). This # also marks this class as being a dataclass. setattr(cls, _FIELDS, fields) # Was this class defined with an explicit __hash__? Note that if # __eq__ is defined in this class, then python will automatically # set __hash__ to None. This is a heuristic, as it's possible # that such a __hash__ == None was not auto-generated, but it # close enough. class_hash = cls.__dict__.get('__hash__', MISSING) has_explicit_hash = not (class_hash is MISSING or (class_hash is None and '__eq__' in cls.__dict__)) # If we're generating ordering methods, we must be generating the # eq methods. if order and not eq: raise ValueError('eq must be true if order is true') if init: # Does this class have a post-init function? has_post_init = hasattr(cls, _POST_INIT_NAME) # Include InitVars and regular fields (so, not ClassVars). flds = [f for f in fields.values() if f._field_type in (_FIELD, _FIELD_INITVAR)] _set_new_attribute(cls, '__init__', _init_fn(flds, frozen, has_post_init, # The name to use for the "self" # param in __init__. Use "self" # if possible. '__dataclass_self__' if 'self' in fields else 'self', )) # Get the fields as a list, and include only real fields. This is # used in all of the following methods. field_list = [f for f in fields.values() if f._field_type is _FIELD] if repr: flds = [f for f in field_list if f.repr] _set_new_attribute(cls, '__repr__', _repr_fn(flds)) if eq: # Create _eq__ method. There's no need for a __ne__ method, # since python will call __eq__ and negate it. flds = [f for f in field_list if f.compare] self_tuple = _tuple_str('self', flds) other_tuple = _tuple_str('other', flds) _set_new_attribute(cls, '__eq__', _cmp_fn('__eq__', '==', self_tuple, other_tuple)) if order: # Create and set the ordering methods. flds = [f for f in field_list if f.compare] self_tuple = _tuple_str('self', flds) other_tuple = _tuple_str('other', flds) for name, op in [('__lt__', '<'), ('__le__', '<='), ('__gt__', '>'), ('__ge__', '>='), ]: if _set_new_attribute(cls, name, _cmp_fn(name, op, self_tuple, other_tuple)): raise TypeError(f'Cannot overwrite attribute {name} ' f'in class {cls.__name__}. Consider using ' 'functools.total_ordering') if frozen: for fn in _frozen_get_del_attr(cls, field_list): if _set_new_attribute(cls, fn.__name__, fn): raise TypeError(f'Cannot overwrite attribute {fn.__name__} ' f'in class {cls.__name__}') # Decide if/how we're going to create a hash function. hash_action = _hash_action[bool(unsafe_hash), bool(eq), bool(frozen), has_explicit_hash] if hash_action: # No need to call _set_new_attribute here, since by the time # we're here the overwriting is unconditional. cls.__hash__ = hash_action(cls, field_list) if not getattr(cls, '__doc__'): # Create a class doc-string. cls.__doc__ = (cls.__name__ + str(inspect.signature(cls)).replace(' -> None', '')) return cls def dataclass(cls=None, /, *, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): """Returns the same class as was passed in, with dunder methods added based on the fields defined in the class. Examines PEP 526 __annotations__ to determine fields. If init is true, an __init__() method is added to the class. If repr is true, a __repr__() method is added. If order is true, rich comparison dunder methods are added. If unsafe_hash is true, a __hash__() method function is added. If frozen is true, fields may not be assigned to after instance creation. """ def wrap(cls): return _process_class(cls, init, repr, eq, order, unsafe_hash, frozen) # See if we're being called as @dataclass or @dataclass(). if cls is None: # We're called with parens. return wrap # We're called as @dataclass without parens. return wrap(cls) def fields(class_or_instance): """Return a tuple describing the fields of this dataclass. Accepts a dataclass or an instance of one. Tuple elements are of type Field. """ # Might it be worth caching this, per class? try: fields = getattr(class_or_instance, _FIELDS) except AttributeError: raise TypeError('must be called with a dataclass type or instance') # Exclude pseudo-fields. Note that fields is sorted by insertion # order, so the order of the tuple is as the fields were defined. return tuple(f for f in fields.values() if f._field_type is _FIELD) def _is_dataclass_instance(obj): """Returns True if obj is an instance of a dataclass.""" return not isinstance(obj, type) and hasattr(obj, _FIELDS) def is_dataclass(obj): """Returns True if obj is a dataclass or an instance of a dataclass.""" return hasattr(obj, _FIELDS) def asdict(obj, *, dict_factory=dict): """Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage: @dataclass class C: x: int y: int c = C(1, 2) assert asdict(c) == {'x': 1, 'y': 2} If given, 'dict_factory' will be used instead of built-in dict. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts. """ if not _is_dataclass_instance(obj): raise TypeError("asdict() should be called on dataclass instances") return _asdict_inner(obj, dict_factory) def _asdict_inner(obj, dict_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) return dict_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): # obj is a namedtuple. Recurse into it, but the returned # object is another namedtuple of the same type. This is # similar to how other list- or tuple-derived classes are # treated (see below), but we just need to create them # differently because a namedtuple's __init__ needs to be # called differently (see bpo-34363). # I'm not using namedtuple's _asdict() # method, because: # - it does not recurse in to the namedtuple fields and # convert them to dicts (using dict_factory). # - I don't actually want to return a dict here. The the main # use case here is json.dumps, and it handles converting # namedtuples to lists. Admittedly we're losing some # information here when we produce a json list instead of a # dict. Note that if we returned dicts here instead of # namedtuples, we could no longer call asdict() on a data # structure where a namedtuple was used as a dict key. return type(obj)(*[_asdict_inner(v, dict_factory) for v in obj]) elif isinstance(obj, (list, tuple)): # Assume we can create an object of this type by passing in a # generator (which is not true for namedtuples, handled # above). return type(obj)(_asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) def astuple(obj, *, tuple_factory=tuple): """Return the fields of a dataclass instance as a new tuple of field values. Example usage:: @dataclass class C: x: int y: int c = C(1, 2) assert astuple(c) == (1, 2) If given, 'tuple_factory' will be used instead of built-in tuple. The function applies recursively to field values that are dataclass instances. This will also look into built-in containers: tuples, lists, and dicts. """ if not _is_dataclass_instance(obj): raise TypeError("astuple() should be called on dataclass instances") return _astuple_inner(obj, tuple_factory) def _astuple_inner(obj, tuple_factory): if _is_dataclass_instance(obj): result = [] for f in fields(obj): value = _astuple_inner(getattr(obj, f.name), tuple_factory) result.append(value) return tuple_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): # obj is a namedtuple. Recurse into it, but the returned # object is another namedtuple of the same type. This is # similar to how other list- or tuple-derived classes are # treated (see below), but we just need to create them # differently because a namedtuple's __init__ needs to be # called differently (see bpo-34363). return type(obj)(*[_astuple_inner(v, tuple_factory) for v in obj]) elif isinstance(obj, (list, tuple)): # Assume we can create an object of this type by passing in a # generator (which is not true for namedtuples, handled # above). return type(obj)(_astuple_inner(v, tuple_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((_astuple_inner(k, tuple_factory), _astuple_inner(v, tuple_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False): """Return a new dynamically created dataclass. The dataclass name will be 'cls_name'. 'fields' is an iterable of either (name), (name, type) or (name, type, Field) objects. If type is omitted, use the string 'typing.Any'. Field objects are created by the equivalent of calling 'field(name, type [, Field-info])'. C = make_dataclass('C', ['x', ('y', int), ('z', int, field(init=False))], bases=(Base,)) is equivalent to: @dataclass class C(Base): x: 'typing.Any' y: int z: int = field(init=False) For the bases and namespace parameters, see the builtin type() function. The parameters init, repr, eq, order, unsafe_hash, and frozen are passed to dataclass(). """ if namespace is None: namespace = {} else: # Copy namespace since we're going to mutate it. namespace = namespace.copy() # While we're looking through the field names, validate that they # are identifiers, are not keywords, and not duplicates. seen = set() anns = {} for item in fields: if isinstance(item, str): name = item tp = 'typing.Any' elif len(item) == 2: name, tp, = item elif len(item) == 3: name, tp, spec = item namespace[name] = spec else: raise TypeError(f'Invalid field: {item!r}') if not isinstance(name, str) or not name.isidentifier(): raise TypeError(f'Field names must be valid identifiers: {name!r}') if keyword.iskeyword(name): raise TypeError(f'Field names must not be keywords: {name!r}') if name in seen: raise TypeError(f'Field name duplicated: {name!r}') seen.add(name) anns[name] = tp namespace['__annotations__'] = anns # We use `types.new_class()` instead of simply `type()` to allow dynamic creation # of generic dataclassses. cls = types.new_class(cls_name, bases, {}, lambda ns: ns.update(namespace)) return dataclass(cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen) def replace(obj, /, **changes): """Return a new object replacing specified fields with new values. This is especially useful for frozen classes. Example usage: @dataclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = replace(c, x=3) assert c1.x == 3 and c1.y == 2 """ # We're going to mutate 'changes', but that's okay because it's a # new dict, even if called with 'replace(obj, **my_changes)'. if not _is_dataclass_instance(obj): raise TypeError("replace() should be called on dataclass instances") # It's an error to have init=False fields in 'changes'. # If a field is not in 'changes', read its value from the provided obj. for f in getattr(obj, _FIELDS).values(): # Only consider normal fields or InitVars. if f._field_type is _FIELD_CLASSVAR: continue if not f.init: # Error if this field is specified in changes. if f.name in changes: raise ValueError(f'field {f.name} is declared with ' 'init=False, it cannot be specified with ' 'replace()') continue if f.name not in changes: if f._field_type is _FIELD_INITVAR: raise ValueError(f"InitVar {f.name!r} " 'must be specified with replace()') changes[f.name] = getattr(obj, f.name) # Create the new object, which calls __init__() and # __post_init__() (if defined), using all of the init fields we've # added and/or left in 'changes'. If there are values supplied in # changes that aren't fields, this will correctly raise a # TypeError. return obj.__class__(**changes)
from typing import Any, Dict, IO, Mapping, Optional, Sequence, Tuple, Union import cyvcf2 import logging import numpy as np log = logging.getLogger(__name__) # have to re-declare here since only exist in cyvcf2 stub and fails on execution Text = Union[str, bytes] Primitives = Union[int, float, bool, Text] def _numpy_unknown_to_none(a: np.ndarray) -> list: """ Unknown values ('.') in integer arrays are assigned as '-inf' (e.g. for in32 the value is -2^31) Convert array to list, and replace these values with None """ b = a.tolist() n = max(a.shape) indices = zip(*np.where(a < np.iinfo(a.dtype).min + n)) def set_value(x, i, value): "Set value in nested lists" if len(i) > 1: x = set_value(x[i[0]], i[1:], value) else: x[i[0]] = value for idx in indices: set_value(b, idx, None) return b def numpy_to_list(a: Optional[np.ndarray]): if a is None: return None if np.issubdtype(a.dtype, np.integer): return _numpy_unknown_to_none(a) else: return a.tolist() class Record(object): variant: cyvcf2.Variant samples: Sequence[str] meta: Mapping[str, Any] def __init__(self, variant: cyvcf2.Variant, samples: Sequence[str], meta: Mapping[str, Any]): self.variant = variant self.samples = samples self.meta = meta def _sample_index(self, sample_name: str): return self.samples.index(sample_name) def get_raw_filter(self): """Need to implement this here, as cyvcf2 does not distinguish between 'PASS' and '.' (both return None). Therefore, we need to parse the VCF line to get the raw filter status.""" return str(self.variant).split("\t")[6] def sample_genotype(self, sample_name: str): return tuple(self.variant.genotypes[self._sample_index(sample_name)][:-1]) def has_allele(self, sample_name: str): gt = self.sample_genotype(sample_name) return max(gt) == 1 def get_format_sample(self, property: str, sample_name: str, scalar: bool = False): if property == "GT": return self.sample_genotype(sample_name) else: prop = self.variant.format(property) if prop is not None: ret = numpy_to_list(prop[self._sample_index(sample_name)]) if scalar: assert len(ret) == 1 return ret[0] else: return ret def get_format(self, property: str): if property == "GT": return self.variant.genotypes else: return numpy_to_list(self.variant.format(property)) def get_block_id(self): return self.variant.INFO.get("OLD_MULTIALLELIC") def is_multiallelic(self): return self.get_block_id() is not None def is_sample_multiallelic(self, sample_name: str): return self.is_multiallelic() and bool(set(self.sample_genotype(sample_name)) - set([0, 1])) def annotation( self, ) -> Dict[str, Union[Primitives, Tuple[Primitives, ...]]]: return dict(x for x in self.variant.INFO) def __str__(self): s = repr(self.variant) if self.samples: genotypes = [] for i, x in enumerate(self.variant.gt_bases): genotypes.append(f"{x} ({str(self.samples[i])})") s += f" - Genotypes: {", ".join(genotypes)}" return s RESERVED_GT_HEADERS = { "AD": {"Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele"}, "ADF": { "Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele on the forward strand", }, "ADR": { "Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele on the reverse strand", }, "DP": {"Number": "1", "Type": "Integer", "Description": "Injected. Read depth"}, "EC": { "Number": "A", "Type": "Integer", "Description": "Injected. Expected alternate allele counts", }, "FT": { "Number": "1", "Type": "String", "Description": "Injected. Filter indicating if this genotype was “called”", }, "GL": {"Number": "G", "Type": "Float", "Description": "Injected. Genotype likelihoods"}, "GP": { "Number": "G", "Type": "Float", "Description": "Injected. Genotype posterior probabilities", }, "GQ": { "Number": "1", "Type": "Integer", "Description": "Injected. Conditional genotype quality", }, "GT": {"Number": "1", "Type": "String", "Description": "Injected. Genotype"}, "HQ": {"Number": "2", "Type": "Integer", "Description": "Injected. Haplotype quality"}, "MQ": {"Number": "1", "Type": "Integer", "Description": "Injected. RMS mapping quality"}, "PL": { "Number": "G", "Type": "Integer", "Description": "Injected. Phred-scaled genotype likelihoods rounded to the closest integer", }, "PP": { "Number": "G", "Type": "Integer", "Description": "Injected. Phred-scaled genotype posterior probabilities rounded to the closest integer", }, "PQ": {"Number": "1", "Type": "Integer", "Description": "Injected. Phasing quality"}, "PS": {"Number": "1", "Type": "Integer", "Description": "Injected. Phase"}, } class VcfIterator(object): def __init__(self, path_or_fileobject: Union[str, IO], include_raw: bool = False): self.path_or_fileobject = path_or_fileobject self.reader = cyvcf2.Reader(self.path_or_fileobject, gts012=True) self.include_raw = include_raw self.samples = self.reader.samples self.add_format_headers() self.meta: Dict[str, list] = {} for h in self.reader.header_iter(): if h.type not in self.meta: self.meta[h.type] = [] self.meta[h.type].append(h.info()) def add_format_headers(self): "Add format headers if they do not exist. This is a subset of the reserved genotype keys from https://samtools.github.io/hts-specs/VCFv4.3.pdf (table 2)" for key, fmt in RESERVED_GT_HEADERS.items(): if key in self.reader and self.reader.get_header_type(key) == "FORMAT": existing_header_line = self.reader[key] if ( existing_header_line["Number"] != fmt["Number"] or existing_header_line["Type"] != fmt["Type"] ): log.warning( f"Header for format field {key} in VCF does not match VCF spec. Ignoring." ) else: self.reader.add_format_to_header({**fmt, **{"ID": key}}) def __iter__(self): variant: cyvcf2.Variant if self.include_raw: for variant in self.reader: yield str(variant), variant else: for variant in self.reader: r = Record(variant, self.samples, self.meta) yield r
from typing import Any, Dict, IO, Mapping, Optional, Sequence, Tuple, Union import cyvcf2 import logging import numpy as np log = logging.getLogger(__name__) # have to re-declare here since only exist in cyvcf2 stub and fails on execution Text = Union[str, bytes] Primitives = Union[int, float, bool, Text] def _numpy_unknown_to_none(a: np.ndarray) -> list: """ Unknown values ('.') in integer arrays are assigned as '-inf' (e.g. for in32 the value is -2^31) Convert array to list, and replace these values with None """ b = a.tolist() n = max(a.shape) indices = zip(*np.where(a < np.iinfo(a.dtype).min + n)) def set_value(x, i, value): "Set value in nested lists" if len(i) > 1: x = set_value(x[i[0]], i[1:], value) else: x[i[0]] = value for idx in indices: set_value(b, idx, None) return b def numpy_to_list(a: Optional[np.ndarray]): if a is None: return None if np.issubdtype(a.dtype, np.integer): return _numpy_unknown_to_none(a) else: return a.tolist() class Record(object): variant: cyvcf2.Variant samples: Sequence[str] meta: Mapping[str, Any] def __init__(self, variant: cyvcf2.Variant, samples: Sequence[str], meta: Mapping[str, Any]): self.variant = variant self.samples = samples self.meta = meta def _sample_index(self, sample_name: str): return self.samples.index(sample_name) def get_raw_filter(self): """Need to implement this here, as cyvcf2 does not distinguish between 'PASS' and '.' (both return None). Therefore, we need to parse the VCF line to get the raw filter status.""" return str(self.variant).split("\t")[6] def sample_genotype(self, sample_name: str): return tuple(self.variant.genotypes[self._sample_index(sample_name)][:-1]) def has_allele(self, sample_name: str): gt = self.sample_genotype(sample_name) return max(gt) == 1 def get_format_sample(self, property: str, sample_name: str, scalar: bool = False): if property == "GT": return self.sample_genotype(sample_name) else: prop = self.variant.format(property) if prop is not None: ret = numpy_to_list(prop[self._sample_index(sample_name)]) if scalar: assert len(ret) == 1 return ret[0] else: return ret def get_format(self, property: str): if property == "GT": return self.variant.genotypes else: return numpy_to_list(self.variant.format(property)) def get_block_id(self): return self.variant.INFO.get("OLD_MULTIALLELIC") def is_multiallelic(self): return self.get_block_id() is not None def is_sample_multiallelic(self, sample_name: str): return self.is_multiallelic() and bool(set(self.sample_genotype(sample_name)) - set([0, 1])) def annotation( self, ) -> Dict[str, Union[Primitives, Tuple[Primitives, ...]]]: return dict(x for x in self.variant.INFO) def __str__(self): s = repr(self.variant) if self.samples: genotypes = [] for i, x in enumerate(self.variant.gt_bases): genotypes.append(f"{x} ({str(self.samples[i])})") s += f" - Genotypes: {', '.join(genotypes)}" return s RESERVED_GT_HEADERS = { "AD": {"Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele"}, "ADF": { "Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele on the forward strand", }, "ADR": { "Number": "R", "Type": "Integer", "Description": "Injected. Read depth for each allele on the reverse strand", }, "DP": {"Number": "1", "Type": "Integer", "Description": "Injected. Read depth"}, "EC": { "Number": "A", "Type": "Integer", "Description": "Injected. Expected alternate allele counts", }, "FT": { "Number": "1", "Type": "String", "Description": "Injected. Filter indicating if this genotype was “called”", }, "GL": {"Number": "G", "Type": "Float", "Description": "Injected. Genotype likelihoods"}, "GP": { "Number": "G", "Type": "Float", "Description": "Injected. Genotype posterior probabilities", }, "GQ": { "Number": "1", "Type": "Integer", "Description": "Injected. Conditional genotype quality", }, "GT": {"Number": "1", "Type": "String", "Description": "Injected. Genotype"}, "HQ": {"Number": "2", "Type": "Integer", "Description": "Injected. Haplotype quality"}, "MQ": {"Number": "1", "Type": "Integer", "Description": "Injected. RMS mapping quality"}, "PL": { "Number": "G", "Type": "Integer", "Description": "Injected. Phred-scaled genotype likelihoods rounded to the closest integer", }, "PP": { "Number": "G", "Type": "Integer", "Description": "Injected. Phred-scaled genotype posterior probabilities rounded to the closest integer", }, "PQ": {"Number": "1", "Type": "Integer", "Description": "Injected. Phasing quality"}, "PS": {"Number": "1", "Type": "Integer", "Description": "Injected. Phase"}, } class VcfIterator(object): def __init__(self, path_or_fileobject: Union[str, IO], include_raw: bool = False): self.path_or_fileobject = path_or_fileobject self.reader = cyvcf2.Reader(self.path_or_fileobject, gts012=True) self.include_raw = include_raw self.samples = self.reader.samples self.add_format_headers() self.meta: Dict[str, list] = {} for h in self.reader.header_iter(): if h.type not in self.meta: self.meta[h.type] = [] self.meta[h.type].append(h.info()) def add_format_headers(self): "Add format headers if they do not exist. This is a subset of the reserved genotype keys from https://samtools.github.io/hts-specs/VCFv4.3.pdf (table 2)" for key, fmt in RESERVED_GT_HEADERS.items(): if key in self.reader and self.reader.get_header_type(key) == "FORMAT": existing_header_line = self.reader[key] if ( existing_header_line["Number"] != fmt["Number"] or existing_header_line["Type"] != fmt["Type"] ): log.warning( f"Header for format field {key} in VCF does not match VCF spec. Ignoring." ) else: self.reader.add_format_to_header({**fmt, **{"ID": key}}) def __iter__(self): variant: cyvcf2.Variant if self.include_raw: for variant in self.reader: yield str(variant), variant else: for variant in self.reader: r = Record(variant, self.samples, self.meta) yield r
def rchop(s, ending): return s[: -len(ending)] if s.endswith(ending) else s def lchop(s, beginning): return s[len(beginning) :] if s.startswith(beginning) else s def ordinal_en(n: int): # https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement return f'{n}{'tsnrhtdd'[(n//10%10!=1)*(n%10<4)*n%10::4]}' def ordinal_fr(n: int): if n == 1: return "1er" return f"{n}è" def arrival_time_en(time_in_seconds: int): if time_in_seconds == 0: return "Here" time_in_mins = time_in_seconds // 60 if time_in_mins == 0: return "" return str(time_in_mins) + (" min" if time_in_mins == 1 else " mins")
def rchop(s, ending): return s[: -len(ending)] if s.endswith(ending) else s def lchop(s, beginning): return s[len(beginning) :] if s.startswith(beginning) else s def ordinal_en(n: int): # https://stackoverflow.com/questions/9647202/ordinal-numbers-replacement return f'{n}{"tsnrhtdd"[(n//10%10!=1)*(n%10<4)*n%10::4]}' def ordinal_fr(n: int): if n == 1: return "1er" return f"{n}è" def arrival_time_en(time_in_seconds: int): if time_in_seconds == 0: return "Here" time_in_mins = time_in_seconds // 60 if time_in_mins == 0: return "" return str(time_in_mins) + (" min" if time_in_mins == 1 else " mins")
import logging import warnings from collections import OrderedDict import transaction from pyramid.events import NewRequest import pyramid.tweens from enum import Enum from kinto.core.utils import strip_uri_prefix logger = logging.getLogger(__name__) class ACTIONS(Enum): CREATE = "create" DELETE = "delete" READ = "read" UPDATE = "update" @staticmethod def from_string_list(elements): return tuple(ACTIONS(el) for el in elements) class _ResourceEvent: def __init__(self, payload, request): self.payload = payload self.request = request def __repr__(self): return f"<{self.__class__.__name__} action={self.payload["action"]} uri={self.payload["uri"]}>" @property def read_records(self): message = "`read_records` is deprecated, use `read_objects` instead." warnings.warn(message, DeprecationWarning) return self.read_objects @property def impacted_records(self): message = "`impacted_records` is deprecated, use `impacted_objects` instead." warnings.warn(message, DeprecationWarning) return self.impacted_objects class ResourceRead(_ResourceEvent): """Triggered when a resource is being read. """ def __init__(self, payload, read_objects, request): super().__init__(payload, request) self.read_objects = read_objects class ResourceChanged(_ResourceEvent): """Triggered when a resource is being changed. """ def __init__(self, payload, impacted_objects, request): super().__init__(payload, request) self.impacted_objects = impacted_objects class AfterResourceRead(_ResourceEvent): """Triggered after a resource was successfully read. """ def __init__(self, payload, read_objects, request): super().__init__(payload, request) self.read_objects = read_objects class AfterResourceChanged(_ResourceEvent): """Triggered after a resource was successfully changed. """ def __init__(self, payload, impacted_objects, request): super().__init__(payload, request) self.impacted_objects = impacted_objects class EventCollector(object): """A collection to gather events emitted over the course of a request. Events are gathered by parent id, resource type, and event type. This serves as a primitive normalization so that we can emit fewer events. """ def __init__(self): self.event_dict = OrderedDict() """The events as collected so far. The key of the event_dict is a triple (resource_name, parent_id, action). The value is a triple (impacted, request, payload). If the same (resource_name, parent_id, action) is encountered, we just extend the existing impacted with the new impacted. N.B. this means all values in the payload must not be specific to a single impacted_object. See https://github.com/Kinto/kinto/issues/945 and https://github.com/Kinto/kinto/issues/1731. """ def add_event(self, resource_name, parent_id, action, payload, impacted, request): key = (resource_name, parent_id, action) if key not in self.event_dict: value = (payload, impacted, request) self.event_dict[key] = value else: old_value = self.event_dict[key] (old_payload, old_impacted, old_request) = old_value # May be a good idea to assert that old_payload == payload here. self.event_dict[key] = (old_payload, old_impacted + impacted, old_request) def drain(self): """Return an iterator that removes elements from this EventCollector. This can be used to process events while still allowing events to be added (for instance, as part of a cascade where events add other events). Items yielded will be of a tuple suitable for using as arguments to EventCollector.add_event. """ return EventCollectorDrain(self) class EventCollectorDrain(object): """An iterator that drains an EventCollector. Get one using EventCollector.drain().""" def __init__(self, event_collector): self.event_collector = event_collector def __iter__(self): return self def __next__(self): if self.event_collector.event_dict: # Get the "first" key in insertion order, so as to process # events in the same order they were queued. key = next(iter(self.event_collector.event_dict.keys())) value = self.event_collector.event_dict.pop(key) return key + value else: raise StopIteration def notify_resource_events_before(handler, registry): """pyramid_tm "commit veto" hook to run ResourceChanged events. This hook being a "commit veto" let us tell pyramid_tm to abort the transaction if the ResourceChanged listeners raise. """ def tween(request): response = handler(request) for event in request.get_resource_events(): request.registry.notify(event) return response return tween def setup_transaction_hook(config): """ Resource events are plugged with the transactions of ``pyramid_tm``. Once a transaction is committed, ``AfterResourceRead`` and ``AfterResourceChanged`` events are sent. """ def _notify_resource_events_after(success, request): """Notify the accumulated resource events if transaction succeeds. """ if not success: # pragma: no cover return for event in request.get_resource_events(after_commit=True): try: request.registry.notify(event) except Exception: logger.error("Unable to notify", exc_info=True) def on_new_request(event): """When a new request comes in, hook on transaction commit. """ # Since there is one transaction per batch, ignore subrequests. if hasattr(event.request, "parent"): return current = transaction.get() current.addAfterCommitHook(_notify_resource_events_after, args=(event.request,)) config.add_subscriber(on_new_request, NewRequest) config.add_tween( "kinto.core.events.notify_resource_events_before", under=pyramid.tweens.EXCVIEW ) def get_resource_events(request, after_commit=False): """Generator to iterate the list of events triggered on resources. The list is sorted chronologically (see OrderedDict). This drains the resource_events currently in the request, which allows us to process new events as they are added by current events. However, once the iteration is over, we merge all the events we've emitted into a new resource_events, which we store on the request so we can reprocess the same events in an after-commit tween. This generator must be completely consumed! """ by_resource = request.bound_data.get("resource_events", EventCollector()) afterwards = EventCollector() for event_call in by_resource.drain(): afterwards.add_event(*event_call) (_, _, action, payload, impacted, request) = event_call if after_commit: if action == ACTIONS.READ: event_cls = AfterResourceRead else: event_cls = AfterResourceChanged else: if action == ACTIONS.READ: event_cls = ResourceRead else: event_cls = ResourceChanged yield event_cls(payload, impacted, request) request.bound_data["resource_events"] = afterwards def notify_resource_event( request, parent_id, timestamp, data, action, old=None, resource_name=None, resource_data=None ): """Request helper to stack a resource event. If a similar event (same resource, same action) already occured during the current transaction (e.g. batch) then just extend the impacted objects of the previous one. :param resource_name: The name of the resource on which the event happened (taken from the request if not provided). :param resource_data: Information about the resource on which the event is being emitted. Usually contains information about how to find this object in the hierarchy (for instance, ``bucket_id`` and ``collection_id`` for a record). Taken from the request matchdict if absent. :type resource_data: dict """ if action == ACTIONS.READ: if not isinstance(data, list): data = [data] impacted = data elif action == ACTIONS.CREATE: impacted = [{"new": data}] elif action == ACTIONS.DELETE: if not isinstance(data, list): impacted = [{"new": data, "old": old}] else: impacted = [] for i, new in enumerate(data): impacted.append({"new": new, "old": old[i]}) else: # ACTIONS.UPDATE: impacted = [{"new": data, "old": old}] # Get previously triggered events. events = request.bound_data.setdefault("resource_events", EventCollector()) resource_name = resource_name or request.current_resource_name matchdict = resource_data or dict(request.matchdict) payload = { "timestamp": timestamp, "action": action.value, # Deprecated: don't actually use URI (see #945). "uri": strip_uri_prefix(request.path), "user_id": request.prefixed_userid, "resource_name": resource_name, } # Deprecated: don't actually use `resource_name_id` either (see #945). if "id" in request.matchdict: matchdict[resource_name + "_id"] = matchdict.pop("id") payload.update(**matchdict) events.add_event(resource_name, parent_id, action, payload, impacted, request)
import logging import warnings from collections import OrderedDict import transaction from pyramid.events import NewRequest import pyramid.tweens from enum import Enum from kinto.core.utils import strip_uri_prefix logger = logging.getLogger(__name__) class ACTIONS(Enum): CREATE = "create" DELETE = "delete" READ = "read" UPDATE = "update" @staticmethod def from_string_list(elements): return tuple(ACTIONS(el) for el in elements) class _ResourceEvent: def __init__(self, payload, request): self.payload = payload self.request = request def __repr__(self): return f"<{self.__class__.__name__} action={self.payload['action']} uri={self.payload['uri']}>" @property def read_records(self): message = "`read_records` is deprecated, use `read_objects` instead." warnings.warn(message, DeprecationWarning) return self.read_objects @property def impacted_records(self): message = "`impacted_records` is deprecated, use `impacted_objects` instead." warnings.warn(message, DeprecationWarning) return self.impacted_objects class ResourceRead(_ResourceEvent): """Triggered when a resource is being read. """ def __init__(self, payload, read_objects, request): super().__init__(payload, request) self.read_objects = read_objects class ResourceChanged(_ResourceEvent): """Triggered when a resource is being changed. """ def __init__(self, payload, impacted_objects, request): super().__init__(payload, request) self.impacted_objects = impacted_objects class AfterResourceRead(_ResourceEvent): """Triggered after a resource was successfully read. """ def __init__(self, payload, read_objects, request): super().__init__(payload, request) self.read_objects = read_objects class AfterResourceChanged(_ResourceEvent): """Triggered after a resource was successfully changed. """ def __init__(self, payload, impacted_objects, request): super().__init__(payload, request) self.impacted_objects = impacted_objects class EventCollector(object): """A collection to gather events emitted over the course of a request. Events are gathered by parent id, resource type, and event type. This serves as a primitive normalization so that we can emit fewer events. """ def __init__(self): self.event_dict = OrderedDict() """The events as collected so far. The key of the event_dict is a triple (resource_name, parent_id, action). The value is a triple (impacted, request, payload). If the same (resource_name, parent_id, action) is encountered, we just extend the existing impacted with the new impacted. N.B. this means all values in the payload must not be specific to a single impacted_object. See https://github.com/Kinto/kinto/issues/945 and https://github.com/Kinto/kinto/issues/1731. """ def add_event(self, resource_name, parent_id, action, payload, impacted, request): key = (resource_name, parent_id, action) if key not in self.event_dict: value = (payload, impacted, request) self.event_dict[key] = value else: old_value = self.event_dict[key] (old_payload, old_impacted, old_request) = old_value # May be a good idea to assert that old_payload == payload here. self.event_dict[key] = (old_payload, old_impacted + impacted, old_request) def drain(self): """Return an iterator that removes elements from this EventCollector. This can be used to process events while still allowing events to be added (for instance, as part of a cascade where events add other events). Items yielded will be of a tuple suitable for using as arguments to EventCollector.add_event. """ return EventCollectorDrain(self) class EventCollectorDrain(object): """An iterator that drains an EventCollector. Get one using EventCollector.drain().""" def __init__(self, event_collector): self.event_collector = event_collector def __iter__(self): return self def __next__(self): if self.event_collector.event_dict: # Get the "first" key in insertion order, so as to process # events in the same order they were queued. key = next(iter(self.event_collector.event_dict.keys())) value = self.event_collector.event_dict.pop(key) return key + value else: raise StopIteration def notify_resource_events_before(handler, registry): """pyramid_tm "commit veto" hook to run ResourceChanged events. This hook being a "commit veto" let us tell pyramid_tm to abort the transaction if the ResourceChanged listeners raise. """ def tween(request): response = handler(request) for event in request.get_resource_events(): request.registry.notify(event) return response return tween def setup_transaction_hook(config): """ Resource events are plugged with the transactions of ``pyramid_tm``. Once a transaction is committed, ``AfterResourceRead`` and ``AfterResourceChanged`` events are sent. """ def _notify_resource_events_after(success, request): """Notify the accumulated resource events if transaction succeeds. """ if not success: # pragma: no cover return for event in request.get_resource_events(after_commit=True): try: request.registry.notify(event) except Exception: logger.error("Unable to notify", exc_info=True) def on_new_request(event): """When a new request comes in, hook on transaction commit. """ # Since there is one transaction per batch, ignore subrequests. if hasattr(event.request, "parent"): return current = transaction.get() current.addAfterCommitHook(_notify_resource_events_after, args=(event.request,)) config.add_subscriber(on_new_request, NewRequest) config.add_tween( "kinto.core.events.notify_resource_events_before", under=pyramid.tweens.EXCVIEW ) def get_resource_events(request, after_commit=False): """Generator to iterate the list of events triggered on resources. The list is sorted chronologically (see OrderedDict). This drains the resource_events currently in the request, which allows us to process new events as they are added by current events. However, once the iteration is over, we merge all the events we've emitted into a new resource_events, which we store on the request so we can reprocess the same events in an after-commit tween. This generator must be completely consumed! """ by_resource = request.bound_data.get("resource_events", EventCollector()) afterwards = EventCollector() for event_call in by_resource.drain(): afterwards.add_event(*event_call) (_, _, action, payload, impacted, request) = event_call if after_commit: if action == ACTIONS.READ: event_cls = AfterResourceRead else: event_cls = AfterResourceChanged else: if action == ACTIONS.READ: event_cls = ResourceRead else: event_cls = ResourceChanged yield event_cls(payload, impacted, request) request.bound_data["resource_events"] = afterwards def notify_resource_event( request, parent_id, timestamp, data, action, old=None, resource_name=None, resource_data=None ): """Request helper to stack a resource event. If a similar event (same resource, same action) already occured during the current transaction (e.g. batch) then just extend the impacted objects of the previous one. :param resource_name: The name of the resource on which the event happened (taken from the request if not provided). :param resource_data: Information about the resource on which the event is being emitted. Usually contains information about how to find this object in the hierarchy (for instance, ``bucket_id`` and ``collection_id`` for a record). Taken from the request matchdict if absent. :type resource_data: dict """ if action == ACTIONS.READ: if not isinstance(data, list): data = [data] impacted = data elif action == ACTIONS.CREATE: impacted = [{"new": data}] elif action == ACTIONS.DELETE: if not isinstance(data, list): impacted = [{"new": data, "old": old}] else: impacted = [] for i, new in enumerate(data): impacted.append({"new": new, "old": old[i]}) else: # ACTIONS.UPDATE: impacted = [{"new": data, "old": old}] # Get previously triggered events. events = request.bound_data.setdefault("resource_events", EventCollector()) resource_name = resource_name or request.current_resource_name matchdict = resource_data or dict(request.matchdict) payload = { "timestamp": timestamp, "action": action.value, # Deprecated: don't actually use URI (see #945). "uri": strip_uri_prefix(request.path), "user_id": request.prefixed_userid, "resource_name": resource_name, } # Deprecated: don't actually use `resource_name_id` either (see #945). if "id" in request.matchdict: matchdict[resource_name + "_id"] = matchdict.pop("id") payload.update(**matchdict) events.add_event(resource_name, parent_id, action, payload, impacted, request)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from awsglue.blueprint.workflow import Workflow, Entities from awsglue.blueprint.job import Job from awsglue.blueprint.crawler import * import boto3 from botocore.client import ClientError import datetime def generate_schedule(type): now = datetime.datetime.utcnow() year = now.year number_of_month = now.month days = now.day hours = now.hour minutes = now.minute days_of_week = now.weekday() if type == 'Hourly': return generate_cron_expression(minutes, "0/1", "*", "*", "?", "*") elif type == 'Daily': return generate_cron_expression(minutes, hours, "*", "*", "?", "*") elif type == 'Weekly': return generate_cron_expression(minutes, hours, "?", "*", days_of_week, "*") elif type == 'Monthly': return generate_cron_expression(minutes, hours, days, "*", "?", "*") else: return generate_cron_expression(minutes, hours, days, number_of_month, "?", year) def generate_cron_expression(minutes, hours, days, number_of_month, days_of_week, year): return "cron({0} {1} {2} {3} {4} {5})".format(minutes, hours, days, number_of_month, days_of_week, year) def validate_params(user_params, system_params): if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "" \ and user_params['InputDataLocation'] == user_params['OutputDataLocation']: err_msg = 'InputDataLocation is same as OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') def generate_layout(user_params, system_params): file_name = "compaction_{0}_{1}.py".format(user_params['SourceDatabaseName'], user_params['SourceTableName']) session = boto3.Session(region_name=system_params['region']) glue = session.client('glue') s3_client = session.client('s3') workflow_name = user_params['WorkflowName'] # Validate params validate_params(user_params, system_params) # Create Source Database if it does not exists try: glue.create_database( DatabaseInput={ 'Name': user_params['SourceDatabaseName'] } ) print("New database is created.") except glue.exceptions.AlreadyExistsException: print("Existing database is used.") location = {'LocationConstraint': system_params['region']} # Creating script bucket the_script_bucket = f"aws-glue-scripts-{system_params["accountId"]}-{system_params["region"]}" try: s3_client.head_bucket(Bucket=the_script_bucket) print("Script bucket already exists: ", the_script_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating script bucket: ", the_script_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_script_bucket) else: bucket = s3_client.create_bucket(Bucket=the_script_bucket, CreateBucketConfiguration=location) # Creating temp bucket the_temp_bucket = f"aws-glue-temporary-{system_params["accountId"]}-{system_params["region"]}" the_temp_prefix = f"{workflow_name}/" the_temp_location = f"s3://{the_temp_bucket}/{the_temp_prefix}" try: s3_client.head_bucket(Bucket=the_temp_bucket) print("Temp bucket already exists: ", the_temp_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating temp bucket: ", the_temp_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_temp_bucket) else: bucket = s3_client.create_bucket(Bucket=the_temp_bucket, CreateBucketConfiguration=location) # Creating manifest bucket if user_params['EnableManifest']: the_manifest_bucket = f"aws-glue-compaction-manifest-{system_params["accountId"]}-{system_params["region"]}" the_manifest_prefix = f"{workflow_name}/" the_manifest_location = f"s3://{the_manifest_bucket}/{the_manifest_prefix}" try: s3_client.head_bucket(Bucket=the_manifest_bucket) print("Manifest bucket already exists: ", the_manifest_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating Manifest bucket: ", the_manifest_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_manifest_bucket) else: bucket = s3_client.create_bucket(Bucket=the_manifest_bucket, CreateBucketConfiguration=location) # Upload job script to script bucket the_script_key = f"{workflow_name}/{file_name}" the_script_location = f"s3://{the_script_bucket}/{the_script_key}" with open("compaction/compaction.py", "rb") as f: s3_client.upload_fileobj(f, the_script_bucket, the_script_key) jobs = [] crawlers = [] command = { "Name": "glueetl", "ScriptLocation": the_script_location, "PythonVersion": "3" } arguments = { "--region": system_params['region'], "--TempDir": the_temp_location, "--job-bookmark-option": "job-bookmark-disable", "--job-language": "python", "--enable-s3-parquet-optimized-committer": "", "--enable-rename-algorithm-v2": "", "--enable-metrics": "", "--enable-continuous-cloudwatch-log": "true", "--enable_size_control": user_params['EnableSizeControl'], "--input_database": user_params['SourceDatabaseName'], "--input_table": user_params['SourceTableName'], "--input_format": user_params['InputDataFormat'], "--output_path": user_params['OutputDataLocation'], "--desired_size_mb": user_params['DesiredFileSizeMB'], "--enable_manifest": user_params['EnableManifest'] } if user_params['InputDataFormatOptions']: arguments["--input_format_options"] = user_params['InputDataFormatOptions'] if user_params['EnableManifest']: arguments["--manifest_path"] = the_manifest_location crawler_source = None try: # Get the source table definition and validate the parameters with it. src_table = glue.get_table( DatabaseName=user_params['SourceDatabaseName'], Name=user_params['SourceTableName'] ) if src_table['Table']['StorageDescriptor']['Location'] == user_params['OutputDataLocation']: err_msg = 'Location on the source table is same as OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "" \ and src_table['Table']['StorageDescriptor']['Location'] != user_params['InputDataLocation']: err_msg = 'Location on the source table is different from InputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') print("Existing table is used.") except glue.exceptions.EntityNotFoundException: if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "": # Create a new source table if it does not exist glue.create_table( DatabaseName=user_params['SourceDatabaseName'], TableInput={ 'Name': user_params['SourceTableName'], 'StorageDescriptor': { 'Location': user_params['InputDataLocation'] } } ) print("New table is created.") else: err_msg = 'Source table does not exist, and input data location is not provided.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "": targets_source = {"CatalogTargets": [{"DatabaseName": user_params['SourceDatabaseName'], "Tables": [user_params['SourceTableName']]}]} crawler_source = Crawler( Name="{}_crawler_source".format(workflow_name), Role=user_params['IAMRole'], Grouping={ "TableGroupingPolicy": "CombineCompatibleSchemas" }, Targets=targets_source, SchemaChangePolicy={"DeleteBehavior": "LOG"}, ) crawlers.append(crawler_source) if crawler_source: transform_job = Job( Name="{0}_compaction_{1}_{2}".format(workflow_name, user_params['SourceDatabaseName'], user_params['SourceTableName']), Command=command, Role=user_params['IAMRole'], DefaultArguments=arguments, WorkerType="G.1X", NumberOfWorkers=user_params['NumberOfWorkers'], GlueVersion="2.0", DependsOn={crawler_source: "SUCCEEDED"} ) else: transform_job = Job( Name="{0}_compaction_{1}_{2}".format(workflow_name, user_params['SourceDatabaseName'], user_params['SourceTableName']), Command=command, Role=user_params['IAMRole'], DefaultArguments=arguments, WorkerType="G.1X", NumberOfWorkers=user_params['NumberOfWorkers'], GlueVersion="2.0" ) jobs.append(transform_job) # Create destination database if it does not exists try: glue.create_database( DatabaseInput={ 'Name': user_params['DestinationDatabaseName'] } ) print("New database is created.") except glue.exceptions.AlreadyExistsException: print("Existing database is used.") try: # Get the destination table and validate the parameters with it. dst_table = glue.get_table( DatabaseName=user_params['DestinationDatabaseName'], Name=user_params['DestinationTableName'] ) if dst_table['Table']['StorageDescriptor']['Location'] != user_params['OutputDataLocation']: err_msg = 'Location on the destination table is different from the OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') print("Existing table is used.") except glue.exceptions.EntityNotFoundException: # Create destination table if it does not exist glue.create_table( DatabaseName=user_params['DestinationDatabaseName'], TableInput={ 'Name': user_params['DestinationTableName'], 'StorageDescriptor': { 'Location': user_params['OutputDataLocation'] } } ) print("New table is created.") targets_destination = {"CatalogTargets": [{"DatabaseName": user_params['DestinationDatabaseName'], "Tables": [user_params['DestinationTableName']]}]} crawler_destination = Crawler( Name="{}_crawler_destination".format(workflow_name), Role=user_params['IAMRole'], Targets=targets_destination, SchemaChangePolicy={"DeleteBehavior": "LOG"}, DependsOn={transform_job: "SUCCEEDED"} ) crawlers.append(crawler_destination) if user_params['Frequency']: if user_params['Frequency'] == 'Custom': schedule = user_params['FrequencyCronFormat'] else: schedule = generate_schedule(user_params['Frequency']) else: schedule = None workflow = Workflow(Name=workflow_name, Entities=Entities(Jobs=jobs, Crawlers=crawlers), OnSchedule=schedule) return workflow
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 from awsglue.blueprint.workflow import Workflow, Entities from awsglue.blueprint.job import Job from awsglue.blueprint.crawler import * import boto3 from botocore.client import ClientError import datetime def generate_schedule(type): now = datetime.datetime.utcnow() year = now.year number_of_month = now.month days = now.day hours = now.hour minutes = now.minute days_of_week = now.weekday() if type == 'Hourly': return generate_cron_expression(minutes, "0/1", "*", "*", "?", "*") elif type == 'Daily': return generate_cron_expression(minutes, hours, "*", "*", "?", "*") elif type == 'Weekly': return generate_cron_expression(minutes, hours, "?", "*", days_of_week, "*") elif type == 'Monthly': return generate_cron_expression(minutes, hours, days, "*", "?", "*") else: return generate_cron_expression(minutes, hours, days, number_of_month, "?", year) def generate_cron_expression(minutes, hours, days, number_of_month, days_of_week, year): return "cron({0} {1} {2} {3} {4} {5})".format(minutes, hours, days, number_of_month, days_of_week, year) def validate_params(user_params, system_params): if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "" \ and user_params['InputDataLocation'] == user_params['OutputDataLocation']: err_msg = 'InputDataLocation is same as OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') def generate_layout(user_params, system_params): file_name = "compaction_{0}_{1}.py".format(user_params['SourceDatabaseName'], user_params['SourceTableName']) session = boto3.Session(region_name=system_params['region']) glue = session.client('glue') s3_client = session.client('s3') workflow_name = user_params['WorkflowName'] # Validate params validate_params(user_params, system_params) # Create Source Database if it does not exists try: glue.create_database( DatabaseInput={ 'Name': user_params['SourceDatabaseName'] } ) print("New database is created.") except glue.exceptions.AlreadyExistsException: print("Existing database is used.") location = {'LocationConstraint': system_params['region']} # Creating script bucket the_script_bucket = f"aws-glue-scripts-{system_params['accountId']}-{system_params['region']}" try: s3_client.head_bucket(Bucket=the_script_bucket) print("Script bucket already exists: ", the_script_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating script bucket: ", the_script_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_script_bucket) else: bucket = s3_client.create_bucket(Bucket=the_script_bucket, CreateBucketConfiguration=location) # Creating temp bucket the_temp_bucket = f"aws-glue-temporary-{system_params['accountId']}-{system_params['region']}" the_temp_prefix = f"{workflow_name}/" the_temp_location = f"s3://{the_temp_bucket}/{the_temp_prefix}" try: s3_client.head_bucket(Bucket=the_temp_bucket) print("Temp bucket already exists: ", the_temp_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating temp bucket: ", the_temp_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_temp_bucket) else: bucket = s3_client.create_bucket(Bucket=the_temp_bucket, CreateBucketConfiguration=location) # Creating manifest bucket if user_params['EnableManifest']: the_manifest_bucket = f"aws-glue-compaction-manifest-{system_params['accountId']}-{system_params['region']}" the_manifest_prefix = f"{workflow_name}/" the_manifest_location = f"s3://{the_manifest_bucket}/{the_manifest_prefix}" try: s3_client.head_bucket(Bucket=the_manifest_bucket) print("Manifest bucket already exists: ", the_manifest_bucket) except ClientError as ce: print(ce) print(ce.response['ResponseMetadata']) print("Creating Manifest bucket: ", the_manifest_bucket) if system_params['region'] == "us-east-1": bucket = s3_client.create_bucket(Bucket=the_manifest_bucket) else: bucket = s3_client.create_bucket(Bucket=the_manifest_bucket, CreateBucketConfiguration=location) # Upload job script to script bucket the_script_key = f"{workflow_name}/{file_name}" the_script_location = f"s3://{the_script_bucket}/{the_script_key}" with open("compaction/compaction.py", "rb") as f: s3_client.upload_fileobj(f, the_script_bucket, the_script_key) jobs = [] crawlers = [] command = { "Name": "glueetl", "ScriptLocation": the_script_location, "PythonVersion": "3" } arguments = { "--region": system_params['region'], "--TempDir": the_temp_location, "--job-bookmark-option": "job-bookmark-disable", "--job-language": "python", "--enable-s3-parquet-optimized-committer": "", "--enable-rename-algorithm-v2": "", "--enable-metrics": "", "--enable-continuous-cloudwatch-log": "true", "--enable_size_control": user_params['EnableSizeControl'], "--input_database": user_params['SourceDatabaseName'], "--input_table": user_params['SourceTableName'], "--input_format": user_params['InputDataFormat'], "--output_path": user_params['OutputDataLocation'], "--desired_size_mb": user_params['DesiredFileSizeMB'], "--enable_manifest": user_params['EnableManifest'] } if user_params['InputDataFormatOptions']: arguments["--input_format_options"] = user_params['InputDataFormatOptions'] if user_params['EnableManifest']: arguments["--manifest_path"] = the_manifest_location crawler_source = None try: # Get the source table definition and validate the parameters with it. src_table = glue.get_table( DatabaseName=user_params['SourceDatabaseName'], Name=user_params['SourceTableName'] ) if src_table['Table']['StorageDescriptor']['Location'] == user_params['OutputDataLocation']: err_msg = 'Location on the source table is same as OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "" \ and src_table['Table']['StorageDescriptor']['Location'] != user_params['InputDataLocation']: err_msg = 'Location on the source table is different from InputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') print("Existing table is used.") except glue.exceptions.EntityNotFoundException: if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "": # Create a new source table if it does not exist glue.create_table( DatabaseName=user_params['SourceDatabaseName'], TableInput={ 'Name': user_params['SourceTableName'], 'StorageDescriptor': { 'Location': user_params['InputDataLocation'] } } ) print("New table is created.") else: err_msg = 'Source table does not exist, and input data location is not provided.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') if user_params['InputDataLocation'] and user_params['InputDataLocation'] != "": targets_source = {"CatalogTargets": [{"DatabaseName": user_params['SourceDatabaseName'], "Tables": [user_params['SourceTableName']]}]} crawler_source = Crawler( Name="{}_crawler_source".format(workflow_name), Role=user_params['IAMRole'], Grouping={ "TableGroupingPolicy": "CombineCompatibleSchemas" }, Targets=targets_source, SchemaChangePolicy={"DeleteBehavior": "LOG"}, ) crawlers.append(crawler_source) if crawler_source: transform_job = Job( Name="{0}_compaction_{1}_{2}".format(workflow_name, user_params['SourceDatabaseName'], user_params['SourceTableName']), Command=command, Role=user_params['IAMRole'], DefaultArguments=arguments, WorkerType="G.1X", NumberOfWorkers=user_params['NumberOfWorkers'], GlueVersion="2.0", DependsOn={crawler_source: "SUCCEEDED"} ) else: transform_job = Job( Name="{0}_compaction_{1}_{2}".format(workflow_name, user_params['SourceDatabaseName'], user_params['SourceTableName']), Command=command, Role=user_params['IAMRole'], DefaultArguments=arguments, WorkerType="G.1X", NumberOfWorkers=user_params['NumberOfWorkers'], GlueVersion="2.0" ) jobs.append(transform_job) # Create destination database if it does not exists try: glue.create_database( DatabaseInput={ 'Name': user_params['DestinationDatabaseName'] } ) print("New database is created.") except glue.exceptions.AlreadyExistsException: print("Existing database is used.") try: # Get the destination table and validate the parameters with it. dst_table = glue.get_table( DatabaseName=user_params['DestinationDatabaseName'], Name=user_params['DestinationTableName'] ) if dst_table['Table']['StorageDescriptor']['Location'] != user_params['OutputDataLocation']: err_msg = 'Location on the destination table is different from the OutputDataLocation.' raise ClientError({"Error": {"Code": "InvalidInputException", "Message": err_msg}}, 'validate_params') print("Existing table is used.") except glue.exceptions.EntityNotFoundException: # Create destination table if it does not exist glue.create_table( DatabaseName=user_params['DestinationDatabaseName'], TableInput={ 'Name': user_params['DestinationTableName'], 'StorageDescriptor': { 'Location': user_params['OutputDataLocation'] } } ) print("New table is created.") targets_destination = {"CatalogTargets": [{"DatabaseName": user_params['DestinationDatabaseName'], "Tables": [user_params['DestinationTableName']]}]} crawler_destination = Crawler( Name="{}_crawler_destination".format(workflow_name), Role=user_params['IAMRole'], Targets=targets_destination, SchemaChangePolicy={"DeleteBehavior": "LOG"}, DependsOn={transform_job: "SUCCEEDED"} ) crawlers.append(crawler_destination) if user_params['Frequency']: if user_params['Frequency'] == 'Custom': schedule = user_params['FrequencyCronFormat'] else: schedule = generate_schedule(user_params['Frequency']) else: schedule = None workflow = Workflow(Name=workflow_name, Entities=Entities(Jobs=jobs, Crawlers=crawlers), OnSchedule=schedule) return workflow
import random from ..core import Basic, Integer from ..core.compatibility import as_int class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilton walk visits each vertex exactly once. The Gray code for a 3d cube is ['000','100','110','010','011','111','101', '001']. A Gray code solves the problem of sequentially generating all possible subsets of n objects in such a way that each subset is obtained from the previous one by either deleting or adding a single object. In the above example, 1 indicates that the object is present, and 0 indicates that its absent. Gray codes have applications in statistics as well when we want to compute various statistics related to subsets in an efficient manner. References ========== * Nijenhuis,A. and Wilf,H.S.(1978). Combinatorial Algorithms. Academic Press. * Knuth, D. (2011). The Art of Computer Programming, Vol 4 Addison Wesley Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> a = GrayCode(4) >>> list(a.generate_gray()) ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000'] """ _skip = False _current = 0 _rank = None def __new__(cls, n, *args, **kw_args): """ Default constructor. It takes a single argument ``n`` which gives the dimension of the Gray code. The starting Gray code string (``start``) or the starting ``rank`` may also be given; the default is to start at rank = 0 ('0...0'). Examples ======== >>> a = GrayCode(3) >>> a GrayCode(3) >>> a.n 3 >>> a = GrayCode(3, start='100') >>> a.current '100' >>> a = GrayCode(4, rank=4) >>> a.current '0110' >>> a.rank 4 """ if n < 1 or int(n) != n: raise ValueError( f'Gray code dimension must be a positive integer, not {n:d}') n = int(n) args = (Integer(n),) + args obj = Basic.__new__(cls, *args) if 'start' in kw_args: obj._current = kw_args['start'] if len(obj._current) > n: raise ValueError(f'Gray code start has length {len(obj._current):d} but ' f'should not be greater than {n:d}') elif 'rank' in kw_args: kw_args['rank'] = as_int(kw_args['rank']) if kw_args['rank'] <= 0: raise ValueError('Gray code rank must be a positive integer, ' f"not {kw_args["rank"]:d}") obj._rank = kw_args['rank'] % obj.selections obj._current = obj.unrank(n, obj._rank) return obj def next(self, delta=1): """ Returns the Gray code a distance ``delta`` (default = 1) from the current value in canonical order. Examples ======== >>> a = GrayCode(3, start='110') >>> a.next().current '111' >>> a.next(-1).current '010' """ return GrayCode(self.n, rank=(self.rank + delta) % self.selections) @property def selections(self): """ Returns the number of bit vectors in the Gray code. Examples ======== >>> a = GrayCode(3) >>> a.selections 8 """ return 2**self.n @property def n(self): """ Returns the dimension of the Gray code. Examples ======== >>> a = GrayCode(5) >>> a.n 5 """ return int(self.args[0]) def generate_gray(self, **hints): """ Generates the sequence of bit vectors of a Gray Code. [1] Knuth, D. (2011). The Art of Computer Programming, Vol 4, Addison Wesley Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(start='011')) ['011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(rank=4)) ['110', '111', '101', '100'] See Also ======== skip """ bits = self.n start = None if 'start' in hints: start = hints['start'] elif 'rank' in hints: start = GrayCode.unrank(self.n, hints['rank']) if start is not None: self._current = start current = self.current graycode_bin = gray_to_bin(current) if len(graycode_bin) > self.n: raise ValueError(f'Gray code start has length {len(graycode_bin):d} but should ' f'not be greater than {bits:d}') self._current = int(current, 2) graycode_int = int(''.join(graycode_bin), 2) for i in range(graycode_int, 1 << bits): if self._skip: self._skip = False else: yield self.current bbtc = (i ^ (i + 1)) gbtc = (bbtc ^ (bbtc >> 1)) self._current = (self._current ^ gbtc) self._current = 0 def skip(self): """ Skips the bit generation. Examples ======== >>> a = GrayCode(3) >>> for i in a.generate_gray(): ... if i == '010': ... a.skip() ... print(i) ... 000 001 011 010 111 101 100 See Also ======== generate_gray """ self._skip = True @property def rank(self): """ Ranks the Gray code. A ranking algorithm determines the position (or rank) of a combinatorial object among all the objects w.r.t. a given order. For example, the 4 bit binary reflected Gray code (BRGC) '0101' has a rank of 6 as it appears in the 6th position in the canonical ordering of the family of 4 bit Gray codes. References ========== * http://statweb.stanford.edu/~susan/courses/s208/node12.html Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> GrayCode(3, start='100').rank 7 >>> GrayCode(3, rank=7).current '100' See Also ======== unrank """ if self._rank is None: self._rank = int(gray_to_bin(self.current), 2) return self._rank @property def current(self): """ Returns the currently referenced Gray code as a bit string. Examples ======== >>> GrayCode(3, start='100').current '100' """ rv = self._current or '0' if type(rv) is not str: rv = bin(rv)[2:] return rv.rjust(self.n, '0') @classmethod def unrank(cls, n, rank): """ Unranks an n-bit sized Gray code of rank k. This method exists so that a derivative GrayCode class can define its own code of a given rank. The string here is generated in reverse order to allow for tail-call optimization. Examples ======== >>> GrayCode(5, rank=3).current '00010' >>> GrayCode.unrank(5, 3) '00010' See Also ======== rank """ def _unrank(k, n): if n == 1: return str(k % 2) m = 2**(n - 1) if k < m: return '0' + _unrank(k, n - 1) return '1' + _unrank(m - (k % m) - 1, n - 1) return _unrank(rank, n) def random_bitstring(n): """ Generates a random bitlist of length n. Examples ======== >>> random_bitstring(3) '110' """ return ''.join([random.choice('01') for i in range(n)]) def gray_to_bin(bin_list): """ Convert from Gray coding to binary coding. We assume big endian encoding. Examples ======== >>> gray_to_bin('100') '111' See Also ======== bin_to_gray """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(b[i - 1] != bin_list[i])) return ''.join(b) def bin_to_gray(bin_list): """ Convert from binary coding to gray coding. We assume big endian encoding. Examples ======== >>> bin_to_gray('111') '100' See Also ======== gray_to_bin """ b = [bin_list[0]] for i in range(len(bin_list) - 1): b += str(int(bin_list[i]) ^ int(b[i - 1])) return ''.join(b) def get_subset_from_bitstring(super_set, bitstring): """ Gets the subset defined by the bitstring. Examples ======== >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') ['c', 'd'] >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') ['c', 'a'] See Also ======== graycode_subsets """ if len(super_set) != len(bitstring): raise ValueError('The sizes of the lists are not equal') return [super_set[i] for i, j in enumerate(bitstring) if j == '1'] def graycode_subsets(gray_code_set): """ Generates the subsets as enumerated by a Gray code. Examples ======== >>> list(graycode_subsets(['a', 'b', 'c'])) [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['a']] >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']] See Also ======== get_subset_from_bitstring """ for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): yield get_subset_from_bitstring(gray_code_set, bitstring)
import random from ..core import Basic, Integer from ..core.compatibility import as_int class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilton walk visits each vertex exactly once. The Gray code for a 3d cube is ['000','100','110','010','011','111','101', '001']. A Gray code solves the problem of sequentially generating all possible subsets of n objects in such a way that each subset is obtained from the previous one by either deleting or adding a single object. In the above example, 1 indicates that the object is present, and 0 indicates that its absent. Gray codes have applications in statistics as well when we want to compute various statistics related to subsets in an efficient manner. References ========== * Nijenhuis,A. and Wilf,H.S.(1978). Combinatorial Algorithms. Academic Press. * Knuth, D. (2011). The Art of Computer Programming, Vol 4 Addison Wesley Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> a = GrayCode(4) >>> list(a.generate_gray()) ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000'] """ _skip = False _current = 0 _rank = None def __new__(cls, n, *args, **kw_args): """ Default constructor. It takes a single argument ``n`` which gives the dimension of the Gray code. The starting Gray code string (``start``) or the starting ``rank`` may also be given; the default is to start at rank = 0 ('0...0'). Examples ======== >>> a = GrayCode(3) >>> a GrayCode(3) >>> a.n 3 >>> a = GrayCode(3, start='100') >>> a.current '100' >>> a = GrayCode(4, rank=4) >>> a.current '0110' >>> a.rank 4 """ if n < 1 or int(n) != n: raise ValueError( f'Gray code dimension must be a positive integer, not {n:d}') n = int(n) args = (Integer(n),) + args obj = Basic.__new__(cls, *args) if 'start' in kw_args: obj._current = kw_args['start'] if len(obj._current) > n: raise ValueError(f'Gray code start has length {len(obj._current):d} but ' f'should not be greater than {n:d}') elif 'rank' in kw_args: kw_args['rank'] = as_int(kw_args['rank']) if kw_args['rank'] <= 0: raise ValueError('Gray code rank must be a positive integer, ' f"not {kw_args['rank']:d}") obj._rank = kw_args['rank'] % obj.selections obj._current = obj.unrank(n, obj._rank) return obj def next(self, delta=1): """ Returns the Gray code a distance ``delta`` (default = 1) from the current value in canonical order. Examples ======== >>> a = GrayCode(3, start='110') >>> a.next().current '111' >>> a.next(-1).current '010' """ return GrayCode(self.n, rank=(self.rank + delta) % self.selections) @property def selections(self): """ Returns the number of bit vectors in the Gray code. Examples ======== >>> a = GrayCode(3) >>> a.selections 8 """ return 2**self.n @property def n(self): """ Returns the dimension of the Gray code. Examples ======== >>> a = GrayCode(5) >>> a.n 5 """ return int(self.args[0]) def generate_gray(self, **hints): """ Generates the sequence of bit vectors of a Gray Code. [1] Knuth, D. (2011). The Art of Computer Programming, Vol 4, Addison Wesley Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(start='011')) ['011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(rank=4)) ['110', '111', '101', '100'] See Also ======== skip """ bits = self.n start = None if 'start' in hints: start = hints['start'] elif 'rank' in hints: start = GrayCode.unrank(self.n, hints['rank']) if start is not None: self._current = start current = self.current graycode_bin = gray_to_bin(current) if len(graycode_bin) > self.n: raise ValueError(f'Gray code start has length {len(graycode_bin):d} but should ' f'not be greater than {bits:d}') self._current = int(current, 2) graycode_int = int(''.join(graycode_bin), 2) for i in range(graycode_int, 1 << bits): if self._skip: self._skip = False else: yield self.current bbtc = (i ^ (i + 1)) gbtc = (bbtc ^ (bbtc >> 1)) self._current = (self._current ^ gbtc) self._current = 0 def skip(self): """ Skips the bit generation. Examples ======== >>> a = GrayCode(3) >>> for i in a.generate_gray(): ... if i == '010': ... a.skip() ... print(i) ... 000 001 011 010 111 101 100 See Also ======== generate_gray """ self._skip = True @property def rank(self): """ Ranks the Gray code. A ranking algorithm determines the position (or rank) of a combinatorial object among all the objects w.r.t. a given order. For example, the 4 bit binary reflected Gray code (BRGC) '0101' has a rank of 6 as it appears in the 6th position in the canonical ordering of the family of 4 bit Gray codes. References ========== * http://statweb.stanford.edu/~susan/courses/s208/node12.html Examples ======== >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> GrayCode(3, start='100').rank 7 >>> GrayCode(3, rank=7).current '100' See Also ======== unrank """ if self._rank is None: self._rank = int(gray_to_bin(self.current), 2) return self._rank @property def current(self): """ Returns the currently referenced Gray code as a bit string. Examples ======== >>> GrayCode(3, start='100').current '100' """ rv = self._current or '0' if type(rv) is not str: rv = bin(rv)[2:] return rv.rjust(self.n, '0') @classmethod def unrank(cls, n, rank): """ Unranks an n-bit sized Gray code of rank k. This method exists so that a derivative GrayCode class can define its own code of a given rank. The string here is generated in reverse order to allow for tail-call optimization. Examples ======== >>> GrayCode(5, rank=3).current '00010' >>> GrayCode.unrank(5, 3) '00010' See Also ======== rank """ def _unrank(k, n): if n == 1: return str(k % 2) m = 2**(n - 1) if k < m: return '0' + _unrank(k, n - 1) return '1' + _unrank(m - (k % m) - 1, n - 1) return _unrank(rank, n) def random_bitstring(n): """ Generates a random bitlist of length n. Examples ======== >>> random_bitstring(3) '110' """ return ''.join([random.choice('01') for i in range(n)]) def gray_to_bin(bin_list): """ Convert from Gray coding to binary coding. We assume big endian encoding. Examples ======== >>> gray_to_bin('100') '111' See Also ======== bin_to_gray """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(b[i - 1] != bin_list[i])) return ''.join(b) def bin_to_gray(bin_list): """ Convert from binary coding to gray coding. We assume big endian encoding. Examples ======== >>> bin_to_gray('111') '100' See Also ======== gray_to_bin """ b = [bin_list[0]] for i in range(len(bin_list) - 1): b += str(int(bin_list[i]) ^ int(b[i - 1])) return ''.join(b) def get_subset_from_bitstring(super_set, bitstring): """ Gets the subset defined by the bitstring. Examples ======== >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') ['c', 'd'] >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') ['c', 'a'] See Also ======== graycode_subsets """ if len(super_set) != len(bitstring): raise ValueError('The sizes of the lists are not equal') return [super_set[i] for i, j in enumerate(bitstring) if j == '1'] def graycode_subsets(gray_code_set): """ Generates the subsets as enumerated by a Gray code. Examples ======== >>> list(graycode_subsets(['a', 'b', 'c'])) [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['a']] >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']] See Also ======== get_subset_from_bitstring """ for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): yield get_subset_from_bitstring(gray_code_set, bitstring)
#!/usr/bin/env python import argparse import copy import traceback from os import listdir from os.path import isfile, join #from cv_bridge import CvBridge import math import matplotlib.pyplot as plt import pandas as pd import random # u import numpy as np import cv2 as cv import rospy # Brings in the SimpleActionClient import actionlib # Brings in the .action file and messages used by the move base action from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from squaternion import quat2euler from squaternion import euler2quat from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import Point32 from geometry_msgs.msg import TransformStamped from rosgraph_msgs.msg import Clock from costmap_converter.msg import ObstacleArrayMsg from costmap_converter.msg import ObstacleMsg from geometry_msgs.msg import Twist import threading import _thread from squaternion import quat2euler from squaternion import euler2quat from simple_pid import PID import pickle import utils import logging logger = logging.getLogger(__name__) class Robot(): def __init__(self, name): self.name = name self.prev_call_vicon = None self.state_ = {"position":(None, None), \ "orientation":None} self.all_states_ = [] self.last_time_observation = None if self.name == "robot": rospy.Subscriber("/vicon/Robot/Robot", TransformStamped, self.vicon_cb) elif self.name == "person": rospy.Subscriber("/vicon/Person/Person", TransformStamped, self.vicon_cb) def get_pos(self, idx): if "position" in self.all_states_[idx].keys(): pos = self.all_states_[idx]["position"] else: pos = self.all_states_[idx]["pos"] return pos def get_orientation(self, idx): return self.all_states_[idx]["orientation"] def vicon_cb(self, pose_msg): if self.last_time_observation is not None and abs(rospy.Time.now().to_sec() - self.last_time_observation) <0.025: return pos = pose_msg.transform.translation self.last_time_observation = rospy.Time.now().to_sec() self.state_["position"] = (pos.x, pos.y) euler = quat2euler(pose_msg.transform.rotation.x, pose_msg.transform.rotation.y, pose_msg.transform.rotation.z, pose_msg.transform.rotation.w) self.state_["orientation"] = euler[0] self.all_states_.append(self.state_.copy()) def get_relative_position(self, center, idx): relative_orientation = self.all_states_[idx]['orientation'] center_pos = np.asarray(center.get_pos(idx)) center_orientation = center.all_states_[idx]['orientation'] # transform the pos to center coordinat relative_pos = np.asarray(self.get_pos(idx) - center_pos) rotation_matrix = np.asarray([[np.cos(-center_orientation), np.sin(-center_orientation)], [-np.sin(-center_orientation), np.cos(-center_orientation)]]) relative_pos = np.matmul(relative_pos, rotation_matrix) return relative_pos def get_relative_heading_position(self, center, idx): relative_orientation = self.all_states_[idx]['orientation'] center_pos = np.asarray(center.get_pos(idx)) center_orientation = center.all_states_[idx]['orientation'] print (np.rad2deg(relative_orientation - center_orientation)) # transform the relative to center coordinat relative_pos = np.asarray(self.get_pos(idx) - center_pos) relative_pos2 = np.asarray((relative_pos[0] +math.cos(relative_orientation) , relative_pos[1] + math.sin(relative_orientation))) rotation_matrix = np.asarray([[np.cos(-center_orientation), np.sin(-center_orientation)], [-np.sin(-center_orientation), np.cos(-center_orientation)]]) relative_pos = np.matmul(relative_pos, rotation_matrix) relative_pos2 = np.matmul(relative_pos2, rotation_matrix) angle_relative = np.arctan2(relative_pos2[1]-relative_pos[1], relative_pos2[0]-relative_pos[0]) return angle_relative, relative_pos def is_bag_finish(self): if self.last_time_observation is not None and abs(rospy.Time.now().to_sec() - self.last_time_observation) > 1: return True return False class Results(): def __init__(self): self.center_pos_ = (0, 0) self.name = "" self.DESIRE_DISTANCE = 1.5 self.colors_visualization = cv.cvtColor(cv.applyColorMap(np.arange(0, 255, dtype=np.uint8), cv.COLORMAP_WINTER), cv.COLOR_RGB2BGR).reshape(255,3).tolist() self.current_obsevation_image_ = np.zeros([500,500,3]) self.current_obsevation_image_.fill(255) self.color_index = 0 self.first_call_observation = True self.robot = Robot("robot") self.person = Robot("person") def add_line_observation_to_image(self, pos, pos2): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_image2 = utils.to_image_coordinate(pos2, self.center_pos_) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return self.new_obsevation_image_ = cv.line(self.new_obsevation_image_, (pos_image[0], pos_image[1]), (pos_image2[0], pos_image2[1]), color, 1) def add_triangle_observation_to_image(self, pos, orientation): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_triangle1 = utils.to_image_coordinate((pos[0]+math.cos(orientation)*0.3, pos[1]+math.sin(orientation)*0.3), self.center_pos_) pos_triangle2 = utils.to_image_coordinate((pos[0]+math.cos(orientation+math.pi/2)*0.1, pos[1]+math.sin(orientation+math.pi/2)*0.1), self.center_pos_) pos_triangle3 = utils.to_image_coordinate((pos[0]+math.cos(orientation-math.pi/2)*0.1, pos[1]+math.sin(orientation-math.pi/2)*0.1), self.center_pos_) poses = [pos_triangle1, pos_triangle2, pos_triangle3] for pos in poses: if pos[0] >self.current_obsevation_image_.shape[0] or pos[0] < 0 or pos[1] >self.current_obsevation_image_.shape[1] or pos[1] < 0: rospy.logerr("problem with observation: {}".format(pos)) return self.new_obsevation_image_ = cv.drawContours(self.new_obsevation_image_, [np.asarray(poses)], 0, color, -1) def add_arrow_observation_to_image(self, pos, orientation): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_image2 = utils.to_image_coordinate((pos[0]+math.cos(orientation)*0.3, pos[1]+math.sin(orientation)*0.3), self.center_pos_) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return self.new_obsevation_image_ = cv.arrowedLine(self.new_obsevation_image_, (pos_image[0], pos_image[1]), (pos_image2[0], pos_image2[1]), color, 2, tipLength=0.5) def add_circle_observation_to_image(self, pos, center_pos=None, image=None): color = self.colors_visualization[self.color_index] if image is None: image = self.new_obsevation_image_ if center_pos is None: center_pos = self.center_pos_ pos_image = utils.to_image_coordinate(pos, center_pos) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return return (cv.circle(image , (pos_image[0], pos_image[1]), 4, color, 2)) def update_observation_image(self, idx, len_data): self.new_obsevation_image_ = np.copy(self.current_obsevation_image_) robot_pos = self.robot.get_pos(idx) robot_orientation = self.robot.get_orientation(idx) person_pos = self.person.get_pos(idx) person_orientation = self.person.get_orientation(idx) if person_orientation is None or robot_orientation is None: rospy.logerr("person or robot orientation is None") return if self.first_call_observation: self.first_call_observation = False self.center_pos = person_pos #self.add_circle_observation_to_image(robot_pos) self.add_arrow_observation_to_image(robot_pos, robot_orientation) self.add_triangle_observation_to_image(person_pos, person_orientation) # self.add_line_observation_to_image(robot_pos, person_pos) alpha = 0.50 self.current_obsevation_image_ = cv.addWeighted(self.new_obsevation_image_, alpha, self.current_obsevation_image_, 1 - alpha, 0) self.color_index += 255//len_data def get_current_observation_image(self): image = self.current_obsevation_image_.astype(np.uint8) #image = image/255. return image def get_angle_person_robot(self, idx): pos_rel = self.robot.get_relative_position(self.person, idx) angle_robot_person = math.atan2(pos_rel[1], pos_rel[0]) return (utils.wrap_pi_to_pi(angle_robot_person)) def get_dist_person_robot(self, idx): pos_rel = self.robot.get_relative_position(self.person, idx) return math.hypot(pos_rel[0], pos_rel[1]) def get_reward(self, idx): reward = 0 pos_rel = self.robot.get_relative_position(self.person, idx) angle_robot_person = math.atan2(pos_rel[1], pos_rel[0]) angle_robot_person = np.rad2deg(utils.wrap_pi_to_pi(angle_robot_person)) distance = math.hypot(pos_rel[0], pos_rel[1]) # Negative reward for being behind the person if distance<0.4: reward -= 1 if distance < 0.5: reward = -1.3 elif abs(distance - self.DESIRE_DISTANCE) < 0.5: reward += 0.5 * (0.5 - abs(distance - self.DESIRE_DISTANCE)) elif distance >= self.DESIRE_DISTANCE + 0.5: reward -= 0.25 * (distance - self.DESIRE_DISTANCE + 0.5) elif distance < self.DESIRE_DISTANCE - 0.5: reward -= (self.DESIRE_DISTANCE - 0.5 - distance)/(self.DESIRE_DISTANCE - 0.5) if abs(angle_robot_person) < 25: reward += 0.5 * (25 - abs(angle_robot_person)) / 25 else: reward -= 0.25 * abs(angle_robot_person) / 180 if abs(distance - self.DESIRE_DISTANCE) < 0.5 and abs(angle_robot_person) < 25: reward += 0.25 reward = min(max(reward, -1), 1) return reward def save(self, name): dic_data = {"name":name,"robot":self.robot.all_states_, "person":self.person.all_states_} with open (name+"_.pkl", "wb") as f: pickle.dump(dic_data, f) def load(self, file_address, use_sim=False): with open(file_address, "rb") as f: dic_data = pickle.load(f) self.name = dic_data["name"] self.person.all_states_ = dic_data["person"][4:].copy() self.robot.all_states_ = dic_data["robot"][4:].copy() if use_sim: self.person.all_states_ = [ self.person.all_states_[idx*10] for idx in range (len(self.person.all_states_)//10)] self.robot.all_states_ = [ self.robot.all_states_[idx*10] for idx in range (len(self.robot.all_states_)//10)] def wait_until_bag_finish(self): while not self.robot.is_bag_finish() or not self.person.is_bag_finish(): rospy.sleep(0.1) rospy.loginfo("waiting for bag to finish") if len(self.person.all_states_)>0 and len(self.robot.all_states_)>0: print(self.robot.get_relative_position(self.person, -1)) print(np.rad2deg(self.get_angle_person_robot(-1))) print (self.robot.all_states_) print (self.person.all_states_) def calculate_orientation_dif(self, idx): ori_rel, pos_rel = self.robot.get_relative_heading_position(self.person, idx) return ori_rel def get_metrics(self): rewards = [] orientations = [] orientation_dif = [] distances = [] len_data = min(len(self.robot.all_states_), len(self.person.all_states_)) for idx in range (len_data): # if idx % 10==0: # self.update_observation_image(idx) rewards.append(self.get_reward(idx)) distances.append(self.get_dist_person_robot(idx)) orientations.append(self.get_angle_person_robot(idx)) orientation_dif.append(self.calculate_orientation_dif(idx)) mean_orientation = np.mean(orientations) sum_orientations_m = 0 for orientation in orientations: sum_orientations_m += np.power(utils.wrap_pi_to_pi(mean_orientation - orientation),2) sum_orientations_m /= len(orientations) std = np.sqrt(sum_orientations_m) return {"name":self.name, "orientation_mean":np.average(orientations), "orientation_std":std, \ "reward":np.sum(rewards), "distance":np.average(distances), "distance_std":np.std(distances),\ "ori_dif":np.average(orientation_dif)} def plot_calculate_metrics(self): rewards = [] orientations = [] distances = [] len_data = min(len(self.robot.all_states_), len(self.person.all_states_)) for idx in range (len_data): if idx % 3==0: self.update_observation_image(idx, len_data//3) rewards.append(self.get_reward(idx)) distances.append(self.get_dist_person_robot(idx)) orientations.append(self.get_angle_person_robot(idx)) print (np.rad2deg(self.robot.get_relative_heading_position(self.person, 0)[0])) img = self.get_current_observation_image() img = cv.cvtColor(img, cv.COLOR_RGB2BGR) print(f"\n\ndist avg: {np.average(distances)} orientation avg: {np.rad2deg(np.average(orientations))}, reward: {np.sum(rewards)} reward avg: {np.average(rewards)}") cv.imshow("image", img) cv.waitKey(0) def plot_all_results( results, is_sim=False): name = [] orientations = [] rewards = [] distances = [] orientations_std = [] distances_std = [] for result in results: met = result.get_metrics() name.append(met["name"]) rewards.append(met["reward"]) distances.append(met["distance"]) distances_std.append(met["distance_std"]) orientations.append(np.rad2deg(met["orientation_mean"])) orientations_std.append(np.rad2deg(met["orientation_std"])) print (f"{name[-1]}: Distance_avg: {distances[-1]:.2f} Distance_std: {distances_std[-1]:.2f} Orientation_avg: {orientations[-1]:.1f} Orientation_std: {orientations_std[-1]:.1f} reward: {rewards[-1]:.2f} ori_dif: {np.rad2deg(met["ori_dif"]):0.2f}") if is_sim: print (f"{name[-1]}: ${distances[-1]:.2f}\pm{distances_std[-1]:.1f}$ & ${orientations[-1]:.1f}\pm{orientations_std[-1]:.1f}$ & ${rewards[-1]:.2f}$") else: print (f"{name[-1]}: ${distances[-1]:.2f}\pm{distances_std[-1]:.1f}$ & ${orientations[-1]:.1f}\pm{orientations_std[-1]:.1f}$ & ${rewards[-1]:.2f}$") print ("\n") #df = pd.DataFrame({'name': name, 'assess':[x for x in range(len(name))]}) #plt.errorbar(range(len(df['name'])), orientations, orientations_std, fmt='o') #plt.xticks(range(len(df['name'])), df['name']) if __name__== "__main__": parser = argparse.ArgumentParser(description='input weight file of the network') parser.add_argument('--name', default="no_name", type=str, help='name_traj') parser.add_argument('--file-name', default="no_name", type=str, help='name_file_to_load') parser.add_argument('--folder-name', default="no_name", type=str, help='name_file_to_load') parser.add_argument('--save', action='store_true') parser.add_argument('--load-file', action='store_true') parser.add_argument('--load-folder', action='store_true') parser.add_argument('--plot', action='store_true') parser.add_argument('--use-sim-data', action='store_true') parser.add_argument('--from-bag', action='store_true') args = parser.parse_args() node = rospy.init_node('plot_results') if args.load_folder: onlyfiles = [join(args.folder_name, f) for f in listdir(args.folder_name) if isfile(join(args.folder_name, f))] onlyfiles.sort() all_results = [] for pkl_name in onlyfiles: result = Results() result.load(pkl_name) name_list = result.name.split("_") if not args.use_sim_data and name_list[-1] != "planner" and name_list[-1] != "line": print ("error ") continue new_name = f"{name_list[-1]}_{name_list[-2]}_base_line" result.name = new_name result.save(new_name) all_results.append(result) plot_all_results(all_results, args.use_sim_data) #plt.show() else: result = Results() if args.from_bag or args.load_file: if args.from_bag: result.wait_until_bag_finish() else: result.load(args.file_name, args.use_sim_data) else: print("exiting you need to load or read from bag file") exit(0) if args.save: result.save(args.name) if args.plot: result.plot_calculate_metrics()
#!/usr/bin/env python import argparse import copy import traceback from os import listdir from os.path import isfile, join #from cv_bridge import CvBridge import math import matplotlib.pyplot as plt import pandas as pd import random # u import numpy as np import cv2 as cv import rospy # Brings in the SimpleActionClient import actionlib # Brings in the .action file and messages used by the move base action from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from squaternion import quat2euler from squaternion import euler2quat from sensor_msgs.msg import Image from geometry_msgs.msg import Point from geometry_msgs.msg import Point32 from geometry_msgs.msg import TransformStamped from rosgraph_msgs.msg import Clock from costmap_converter.msg import ObstacleArrayMsg from costmap_converter.msg import ObstacleMsg from geometry_msgs.msg import Twist import threading import _thread from squaternion import quat2euler from squaternion import euler2quat from simple_pid import PID import pickle import utils import logging logger = logging.getLogger(__name__) class Robot(): def __init__(self, name): self.name = name self.prev_call_vicon = None self.state_ = {"position":(None, None), \ "orientation":None} self.all_states_ = [] self.last_time_observation = None if self.name == "robot": rospy.Subscriber("/vicon/Robot/Robot", TransformStamped, self.vicon_cb) elif self.name == "person": rospy.Subscriber("/vicon/Person/Person", TransformStamped, self.vicon_cb) def get_pos(self, idx): if "position" in self.all_states_[idx].keys(): pos = self.all_states_[idx]["position"] else: pos = self.all_states_[idx]["pos"] return pos def get_orientation(self, idx): return self.all_states_[idx]["orientation"] def vicon_cb(self, pose_msg): if self.last_time_observation is not None and abs(rospy.Time.now().to_sec() - self.last_time_observation) <0.025: return pos = pose_msg.transform.translation self.last_time_observation = rospy.Time.now().to_sec() self.state_["position"] = (pos.x, pos.y) euler = quat2euler(pose_msg.transform.rotation.x, pose_msg.transform.rotation.y, pose_msg.transform.rotation.z, pose_msg.transform.rotation.w) self.state_["orientation"] = euler[0] self.all_states_.append(self.state_.copy()) def get_relative_position(self, center, idx): relative_orientation = self.all_states_[idx]['orientation'] center_pos = np.asarray(center.get_pos(idx)) center_orientation = center.all_states_[idx]['orientation'] # transform the pos to center coordinat relative_pos = np.asarray(self.get_pos(idx) - center_pos) rotation_matrix = np.asarray([[np.cos(-center_orientation), np.sin(-center_orientation)], [-np.sin(-center_orientation), np.cos(-center_orientation)]]) relative_pos = np.matmul(relative_pos, rotation_matrix) return relative_pos def get_relative_heading_position(self, center, idx): relative_orientation = self.all_states_[idx]['orientation'] center_pos = np.asarray(center.get_pos(idx)) center_orientation = center.all_states_[idx]['orientation'] print (np.rad2deg(relative_orientation - center_orientation)) # transform the relative to center coordinat relative_pos = np.asarray(self.get_pos(idx) - center_pos) relative_pos2 = np.asarray((relative_pos[0] +math.cos(relative_orientation) , relative_pos[1] + math.sin(relative_orientation))) rotation_matrix = np.asarray([[np.cos(-center_orientation), np.sin(-center_orientation)], [-np.sin(-center_orientation), np.cos(-center_orientation)]]) relative_pos = np.matmul(relative_pos, rotation_matrix) relative_pos2 = np.matmul(relative_pos2, rotation_matrix) angle_relative = np.arctan2(relative_pos2[1]-relative_pos[1], relative_pos2[0]-relative_pos[0]) return angle_relative, relative_pos def is_bag_finish(self): if self.last_time_observation is not None and abs(rospy.Time.now().to_sec() - self.last_time_observation) > 1: return True return False class Results(): def __init__(self): self.center_pos_ = (0, 0) self.name = "" self.DESIRE_DISTANCE = 1.5 self.colors_visualization = cv.cvtColor(cv.applyColorMap(np.arange(0, 255, dtype=np.uint8), cv.COLORMAP_WINTER), cv.COLOR_RGB2BGR).reshape(255,3).tolist() self.current_obsevation_image_ = np.zeros([500,500,3]) self.current_obsevation_image_.fill(255) self.color_index = 0 self.first_call_observation = True self.robot = Robot("robot") self.person = Robot("person") def add_line_observation_to_image(self, pos, pos2): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_image2 = utils.to_image_coordinate(pos2, self.center_pos_) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return self.new_obsevation_image_ = cv.line(self.new_obsevation_image_, (pos_image[0], pos_image[1]), (pos_image2[0], pos_image2[1]), color, 1) def add_triangle_observation_to_image(self, pos, orientation): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_triangle1 = utils.to_image_coordinate((pos[0]+math.cos(orientation)*0.3, pos[1]+math.sin(orientation)*0.3), self.center_pos_) pos_triangle2 = utils.to_image_coordinate((pos[0]+math.cos(orientation+math.pi/2)*0.1, pos[1]+math.sin(orientation+math.pi/2)*0.1), self.center_pos_) pos_triangle3 = utils.to_image_coordinate((pos[0]+math.cos(orientation-math.pi/2)*0.1, pos[1]+math.sin(orientation-math.pi/2)*0.1), self.center_pos_) poses = [pos_triangle1, pos_triangle2, pos_triangle3] for pos in poses: if pos[0] >self.current_obsevation_image_.shape[0] or pos[0] < 0 or pos[1] >self.current_obsevation_image_.shape[1] or pos[1] < 0: rospy.logerr("problem with observation: {}".format(pos)) return self.new_obsevation_image_ = cv.drawContours(self.new_obsevation_image_, [np.asarray(poses)], 0, color, -1) def add_arrow_observation_to_image(self, pos, orientation): color = self.colors_visualization[self.color_index] pos_image = utils.to_image_coordinate(pos, self.center_pos_) pos_image2 = utils.to_image_coordinate((pos[0]+math.cos(orientation)*0.3, pos[1]+math.sin(orientation)*0.3), self.center_pos_) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return self.new_obsevation_image_ = cv.arrowedLine(self.new_obsevation_image_, (pos_image[0], pos_image[1]), (pos_image2[0], pos_image2[1]), color, 2, tipLength=0.5) def add_circle_observation_to_image(self, pos, center_pos=None, image=None): color = self.colors_visualization[self.color_index] if image is None: image = self.new_obsevation_image_ if center_pos is None: center_pos = self.center_pos_ pos_image = utils.to_image_coordinate(pos, center_pos) if pos_image[0] >self.current_obsevation_image_.shape[0] or pos_image[0] < 0 or pos_image[1] >self.current_obsevation_image_.shape[1] or pos_image[1] < 0: rospy.logerr("problem with observation: {}".format(pos_image)) return return (cv.circle(image , (pos_image[0], pos_image[1]), 4, color, 2)) def update_observation_image(self, idx, len_data): self.new_obsevation_image_ = np.copy(self.current_obsevation_image_) robot_pos = self.robot.get_pos(idx) robot_orientation = self.robot.get_orientation(idx) person_pos = self.person.get_pos(idx) person_orientation = self.person.get_orientation(idx) if person_orientation is None or robot_orientation is None: rospy.logerr("person or robot orientation is None") return if self.first_call_observation: self.first_call_observation = False self.center_pos = person_pos #self.add_circle_observation_to_image(robot_pos) self.add_arrow_observation_to_image(robot_pos, robot_orientation) self.add_triangle_observation_to_image(person_pos, person_orientation) # self.add_line_observation_to_image(robot_pos, person_pos) alpha = 0.50 self.current_obsevation_image_ = cv.addWeighted(self.new_obsevation_image_, alpha, self.current_obsevation_image_, 1 - alpha, 0) self.color_index += 255//len_data def get_current_observation_image(self): image = self.current_obsevation_image_.astype(np.uint8) #image = image/255. return image def get_angle_person_robot(self, idx): pos_rel = self.robot.get_relative_position(self.person, idx) angle_robot_person = math.atan2(pos_rel[1], pos_rel[0]) return (utils.wrap_pi_to_pi(angle_robot_person)) def get_dist_person_robot(self, idx): pos_rel = self.robot.get_relative_position(self.person, idx) return math.hypot(pos_rel[0], pos_rel[1]) def get_reward(self, idx): reward = 0 pos_rel = self.robot.get_relative_position(self.person, idx) angle_robot_person = math.atan2(pos_rel[1], pos_rel[0]) angle_robot_person = np.rad2deg(utils.wrap_pi_to_pi(angle_robot_person)) distance = math.hypot(pos_rel[0], pos_rel[1]) # Negative reward for being behind the person if distance<0.4: reward -= 1 if distance < 0.5: reward = -1.3 elif abs(distance - self.DESIRE_DISTANCE) < 0.5: reward += 0.5 * (0.5 - abs(distance - self.DESIRE_DISTANCE)) elif distance >= self.DESIRE_DISTANCE + 0.5: reward -= 0.25 * (distance - self.DESIRE_DISTANCE + 0.5) elif distance < self.DESIRE_DISTANCE - 0.5: reward -= (self.DESIRE_DISTANCE - 0.5 - distance)/(self.DESIRE_DISTANCE - 0.5) if abs(angle_robot_person) < 25: reward += 0.5 * (25 - abs(angle_robot_person)) / 25 else: reward -= 0.25 * abs(angle_robot_person) / 180 if abs(distance - self.DESIRE_DISTANCE) < 0.5 and abs(angle_robot_person) < 25: reward += 0.25 reward = min(max(reward, -1), 1) return reward def save(self, name): dic_data = {"name":name,"robot":self.robot.all_states_, "person":self.person.all_states_} with open (name+"_.pkl", "wb") as f: pickle.dump(dic_data, f) def load(self, file_address, use_sim=False): with open(file_address, "rb") as f: dic_data = pickle.load(f) self.name = dic_data["name"] self.person.all_states_ = dic_data["person"][4:].copy() self.robot.all_states_ = dic_data["robot"][4:].copy() if use_sim: self.person.all_states_ = [ self.person.all_states_[idx*10] for idx in range (len(self.person.all_states_)//10)] self.robot.all_states_ = [ self.robot.all_states_[idx*10] for idx in range (len(self.robot.all_states_)//10)] def wait_until_bag_finish(self): while not self.robot.is_bag_finish() or not self.person.is_bag_finish(): rospy.sleep(0.1) rospy.loginfo("waiting for bag to finish") if len(self.person.all_states_)>0 and len(self.robot.all_states_)>0: print(self.robot.get_relative_position(self.person, -1)) print(np.rad2deg(self.get_angle_person_robot(-1))) print (self.robot.all_states_) print (self.person.all_states_) def calculate_orientation_dif(self, idx): ori_rel, pos_rel = self.robot.get_relative_heading_position(self.person, idx) return ori_rel def get_metrics(self): rewards = [] orientations = [] orientation_dif = [] distances = [] len_data = min(len(self.robot.all_states_), len(self.person.all_states_)) for idx in range (len_data): # if idx % 10==0: # self.update_observation_image(idx) rewards.append(self.get_reward(idx)) distances.append(self.get_dist_person_robot(idx)) orientations.append(self.get_angle_person_robot(idx)) orientation_dif.append(self.calculate_orientation_dif(idx)) mean_orientation = np.mean(orientations) sum_orientations_m = 0 for orientation in orientations: sum_orientations_m += np.power(utils.wrap_pi_to_pi(mean_orientation - orientation),2) sum_orientations_m /= len(orientations) std = np.sqrt(sum_orientations_m) return {"name":self.name, "orientation_mean":np.average(orientations), "orientation_std":std, \ "reward":np.sum(rewards), "distance":np.average(distances), "distance_std":np.std(distances),\ "ori_dif":np.average(orientation_dif)} def plot_calculate_metrics(self): rewards = [] orientations = [] distances = [] len_data = min(len(self.robot.all_states_), len(self.person.all_states_)) for idx in range (len_data): if idx % 3==0: self.update_observation_image(idx, len_data//3) rewards.append(self.get_reward(idx)) distances.append(self.get_dist_person_robot(idx)) orientations.append(self.get_angle_person_robot(idx)) print (np.rad2deg(self.robot.get_relative_heading_position(self.person, 0)[0])) img = self.get_current_observation_image() img = cv.cvtColor(img, cv.COLOR_RGB2BGR) print(f"\n\ndist avg: {np.average(distances)} orientation avg: {np.rad2deg(np.average(orientations))}, reward: {np.sum(rewards)} reward avg: {np.average(rewards)}") cv.imshow("image", img) cv.waitKey(0) def plot_all_results( results, is_sim=False): name = [] orientations = [] rewards = [] distances = [] orientations_std = [] distances_std = [] for result in results: met = result.get_metrics() name.append(met["name"]) rewards.append(met["reward"]) distances.append(met["distance"]) distances_std.append(met["distance_std"]) orientations.append(np.rad2deg(met["orientation_mean"])) orientations_std.append(np.rad2deg(met["orientation_std"])) print (f"{name[-1]}: Distance_avg: {distances[-1]:.2f} Distance_std: {distances_std[-1]:.2f} Orientation_avg: {orientations[-1]:.1f} Orientation_std: {orientations_std[-1]:.1f} reward: {rewards[-1]:.2f} ori_dif: {np.rad2deg(met['ori_dif']):0.2f}") if is_sim: print (f"{name[-1]}: ${distances[-1]:.2f}\pm{distances_std[-1]:.1f}$ & ${orientations[-1]:.1f}\pm{orientations_std[-1]:.1f}$ & ${rewards[-1]:.2f}$") else: print (f"{name[-1]}: ${distances[-1]:.2f}\pm{distances_std[-1]:.1f}$ & ${orientations[-1]:.1f}\pm{orientations_std[-1]:.1f}$ & ${rewards[-1]:.2f}$") print ("\n") #df = pd.DataFrame({'name': name, 'assess':[x for x in range(len(name))]}) #plt.errorbar(range(len(df['name'])), orientations, orientations_std, fmt='o') #plt.xticks(range(len(df['name'])), df['name']) if __name__== "__main__": parser = argparse.ArgumentParser(description='input weight file of the network') parser.add_argument('--name', default="no_name", type=str, help='name_traj') parser.add_argument('--file-name', default="no_name", type=str, help='name_file_to_load') parser.add_argument('--folder-name', default="no_name", type=str, help='name_file_to_load') parser.add_argument('--save', action='store_true') parser.add_argument('--load-file', action='store_true') parser.add_argument('--load-folder', action='store_true') parser.add_argument('--plot', action='store_true') parser.add_argument('--use-sim-data', action='store_true') parser.add_argument('--from-bag', action='store_true') args = parser.parse_args() node = rospy.init_node('plot_results') if args.load_folder: onlyfiles = [join(args.folder_name, f) for f in listdir(args.folder_name) if isfile(join(args.folder_name, f))] onlyfiles.sort() all_results = [] for pkl_name in onlyfiles: result = Results() result.load(pkl_name) name_list = result.name.split("_") if not args.use_sim_data and name_list[-1] != "planner" and name_list[-1] != "line": print ("error ") continue new_name = f"{name_list[-1]}_{name_list[-2]}_base_line" result.name = new_name result.save(new_name) all_results.append(result) plot_all_results(all_results, args.use_sim_data) #plt.show() else: result = Results() if args.from_bag or args.load_file: if args.from_bag: result.wait_until_bag_finish() else: result.load(args.file_name, args.use_sim_data) else: print("exiting you need to load or read from bag file") exit(0) if args.save: result.save(args.name) if args.plot: result.plot_calculate_metrics()
#!/usr/bin/env python3 import os import re import datetime import json import copy # Parses the md file, outputs html string def createArticle(mdFileName:str, isBlog=True): """ mdFileName: md file name isBlog: boolean Returns: { article, postTitle, postSubject, timeCreated } article: the blog post in HTML string to be injected postTitle: h1 postSubject: initial 50 chars of first para timeCreated: datetime, updates when the function is called """ # TODO: Add tags to articles, maybe a custom syntax in the markdown file article = "" postTitle = "" postSubject = None # global variables global timeCreated timeCreated = datetime.datetime.now().strftime("%a %b %d %X %Y") global thumbnail thumbnail = "" global numImgFound numImgFound = -1 def isHeader(line): return line[0:1] == "#" and line != "" def makeHeader(line): headerType, *text = line.split(" ") headerText = " ".join(text) headerId = "-".join(re.sub(r"[\W_]+", " ", headerText).strip().lower().split(" ")) # header = f"<h{len(headerType)} id=\"{headerId}\"><a href=\"#{headerId}\" class=\"topic\">{headerText}</a></h{len(headerType)}>" header = f"<h{len(headerType)} id=\"{headerId}\" class=\"topic\">{headerText}</h{len(headerType)}>" # only show post-info if blog post if len(headerType) == 1 and isBlog and mdFileName != "index.md": global timeCreated title = headerText header += f"<div id=\"post-info\"><p class=\"post-meta\">{timeCreated}, Author: Vikram S. Negi</p></div>" return [header, title] elif len(headerType) == 1: title = headerText return [header, title] else: return header def makeLink(line): foundLink = re.findall(r"\[(.+?)\]\((.+?)\)", line) # print(foundLink) for text, href in foundLink: if href[0:1] == "#": line = re.sub(r"\[(.+?)\]\((.+?)\)", f"<a href=\"{href}\">{text}</a>", line, count=1) else: line = re.sub(r"\[(.+?)\]\((.+?)\)", f"<a href=\"{href}\" target=\"_blank\" rel=\"noopener noreferrer\">{text}</a>", line, count=1) if foundLink: # print("found:", line, end="\n\n") return line def makeItalic(line): foundItalic = re.findall(r"\*(.+?)\*", line) for text in foundItalic: line = re.sub(r"\*(.+?)\*", f"<em>{text}</em>", line, count=1) if foundItalic: return line def makeBold(line): foundBold = re.findall(r"\*\*(.+?)\*\*", line) for text in foundBold: line = re.sub(r"\*\*(.+?)\*\*", f"<strong>{text}</strong>", line, count=1) if foundBold: return line def isListItem(line): return line[0:1] == "*" and line[1:2] == " " def makeList(line, init=True): list = "" bullet, *text = line.split(" ") listItem = " ".join(text) if init: list += "<ul>" list += f"<li>{listItem}</li>" else: list += f"<li>{listItem}</li>" return list def makeCode(line): foundCode = re.findall(r"\`(.+?)\`", line) for text in foundCode: line = re.sub(r"\`.+?\`", f"<code>{text}</code>", line, count=1) if foundCode: return line def isCodeBlock(line): return line[0:3] == "```" def makeCodeBlock(line): codeBlock = "" lang = "" if len(line) > 3: lang = re.findall(r"^\`\`\`(\w+)", line)[0] codeBlock += f"<pre><code class=\"language-{lang}\">" else: codeBlock += f"<pre><code>" return codeBlock def isImg(line): return line[0:1] == "!" def makeImg(line): foundImg = re.findall(r"\!\[(.+?)\]\((.+?)\)", line) if foundImg: global numImgFound numImgFound += len(foundImg) for alt, linkAndCaption in foundImg: # print(linkAndCaption) try: link, *caption = linkAndCaption.split(" ") except: # print("no caption was found!") link = linkAndCaption caption = [] # print(caption) global thumbnail if thumbnail == "": # print("thumbnail is blank", link) thumbnail = link if len(caption) == 0: line = re.sub(r"\!\[(.+?)\]\((.+?)\)", f"<figure><img src=\"{link}\" alt=\"{alt}\" loading=\"lazy\" /></figure>", line, count=1) else: line = re.sub(r"\!\[(.+?)\]\((.+?)\)", f"<figure><img src=\"{link}\" alt=\"{alt}\" loading=\"lazy\" /><figcaption>Figure {numImgFound}. {" ".join(caption)[1:-1]}</figcaption></figure>", line, count=1) if foundImg: return line def isHr(line): return line[0:3] == "---" def isBlockquote(line): return line[0:1] == ">" def makeBlockquote(line): sign, *text = line.split(" ") text = " ".join(text) return f"<blockquote><p class=\"quote\">{text}</p></blockquote>" # TODO: error handling if syntax does has None as the input: ![]() maybe add "" (blank sting) instead of None # TODO: mark # TODO: <!-- comments --> # TODO: some functions seem repetitive, refactor those! if isBlog: path = os.getcwd() + f"/articles/{mdFileName}" else: path = os.getcwd() + f"/root_files/{mdFileName}" print(f"reading {mdFileName}...") with open(path, "r") as f: prevLine = "" inCodeBlock = False isFirstPara = True for line in f: # cross site scripting (xss) security reason # line = line.replace("<", "&lt;").replace(">", "&gt;") # for some reason the following replace method, replaces "!" with "<" if isImg(line): article += makeImg(line) line = "" line = line.replace("<", "&lt;") if not inCodeBlock: line = line.strip() # Check this, if any errors regarding imgs line = makeImg(line) or line line = makeLink(line) or line line = makeBold(line) or line line = makeItalic(line) or line if isBlockquote(line): article += makeBlockquote(line) line = "" # print(index, line) if isHeader(line): headerOut = makeHeader(line) if type(headerOut) == list: headerTag = headerOut[0] postTitle += headerOut[1] else: headerTag = headerOut article += headerTag line = "" unorderedList = "" if isListItem(line): try: if not isListItem(prevLine): unorderedList += makeList(line, init=True) else: unorderedList += makeList(line, init=False) except: print("err: prevLine blank or first in the file") unorderedList += makeList(line, init=True) prevLine = line line = "" elif not isListItem(line): try: if isListItem(prevLine): unorderedList += "</ul>" except: unorderedList += "</ul>" prevLine = line article += unorderedList codeBlock = "" if isCodeBlock(line) and not inCodeBlock: codeBlock += makeCodeBlock(line) inCodeBlock = True line = "" elif isCodeBlock(line) and inCodeBlock: inCodeBlock = False codeBlock += "</code></pre>" line = "" elif inCodeBlock: codeBlock += line.replace("<", "&lt;").replace(">", "&gt;") line = "" article += codeBlock line = makeCode(line) or line if isHr(line): article += "<hr noshade />" line = "" if line != "" and isFirstPara: if len(line) > 50: postSubject = line[:47].strip() + "..." else: postSubject = line line = f"<p>{line}</p>" isFirstPara = False elif line != "" and not isFirstPara: line = f"<p>{line}</p>" article += line f.close() # print(article) fileCom = mdFileName.split(".") fileName = "".join(fileCom[:-1]) # if isBlog: # pathToHTMLFile = f"./blog/{fileName}.html" # else: # pathToHTMLFile = f"./{fileName}.html" pathToHTMLFile = f"./{fileName}.html" return { "article": article, "pathToHTMLFile": pathToHTMLFile, "postTitle": postTitle, "postSubject": postSubject, "timeCreated": timeCreated, "thumbnail": thumbnail } # Test func # print(createArticle("fintech-info.md")) def enterTags(nTags=3): """ Asks user to input hashtags, for blog posts 3 tags by default Returns: an array of tags """ tags = [] # TODO: add confirmation of tags while nTags > 0: tag = input("HashTag: ").strip().lower().replace(" ", "_") or "misc" tags.append(tag) nTags -= 1 return tags def updateCategoryTagsDB(HTMLPath:str, tags:list): """ updates the category tags db """ post = ".".join(HTMLPath[2:].split(".")[:-1 or None]) pathToDB = f"{os.getcwd()}/db/category-tags.json" tagDict = None # {"posts": [], "tagFrequency": {}} with open(pathToDB, "r") as db: tagDict = json.load(db) if post in tagDict["posts"]: print(f"\nTag info of {post} is already in CategoryTagsDB\n") else: tagDict["posts"].append(post) for tag in tags: tagDict["tagFrequency"][tag] = tagDict["tagFrequency"].get(tag, 0) + 1 print(f"\n{len(tagDict["posts"])} posts info saved in CategoryTagsDB\n") with open(pathToDB, "w") as db: json.dump(tagDict, db) # json db def saveToBlogDB(data:dict): """ saves the post meta data, like postTitle, to db """ pathToDB = f"{os.getcwd()}/db/blog-info.json" blogInfo = None # read and load json as dict with open(pathToDB, "r") as db: blogInfo = json.load(db) results = blogInfo["results"] articlePathHTML = data["pathToHTMLFile"] HTMLFileName = articlePathHTML.split("/")[-1] blogFound = False i = 0 while i < len(results): if articlePathHTML == results[i]["pathToHTMLFile"]: # check if the HTML file exists in the /blog dir entirePath = f"{os.getcwd()}/public/blog/{articlePathHTML[2:]}" if not os.path.exists(entirePath): print(f"\nFile doesn't exists! Removing it from the DB...\n") results.pop(i) break print("\nUpdating the blog post...\n") blogFound = True # copy the tag from previously saved data tags = copy.deepcopy(results[i]["tags"]) data["tags"] = tags timeCreated = results[i]["timeCreated"] data["timeCreated"] = timeCreated # rest everything gets updated results[i] = data break i += 1 # /blog/index.html doesn't get entered into the db if not blogFound and HTMLFileName != "index.html": print("Adding article tags...") data["tags"] = enterTags() updateCategoryTagsDB(data["pathToHTMLFile"], data["tags"]) results.insert(0, data) # update length blogInfo["length"] = len(results) print(f"\nNumber of posts saved in BlogInfoDB: {len(results)}\n") # clear the data and re-write everything with open(pathToDB, "w") as db: json.dump(blogInfo, db) # print(data["pathToHTMLFile"], data["tags"]) # !Important: Only for testing, clearing the blog-info.json def clearResults(): with open(f"{os.getcwd()}/db/blog-info.json", "w") as db: json.dump({"results": []}, db) # Create entire HTML string def makeHTMLString(isBlog:bool, articleHTML:dict)->str: """ Params: isBlog, articleHTML Returns: returns html string """ print("\ncreating html string...\n") stylePath = "./style.css" javascriptPath = "./js/main.js" codeBlockTags = { "css": "<link rel=\"stylesheet\" href=\"./css/dark.min.css\">", "js": "<script src=\"./js/highlight.min.js\"></script>" } if isBlog: stylePath = "../style.css" javascriptPath = "../js/main.js" codeBlockTags["css"] = "<link rel=\"stylesheet\" href=\"../css/dark.min.css\">" codeBlockTags["js"] = "<script src=\"../js/highlight.min.js\"></script>" html = f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{articleHTML["postTitle"] or "Home"} - lostvikx</title> <link rel="stylesheet" href="{stylePath}"> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>❄️</text></svg>" > {codeBlockTags["css"] or ""} {codeBlockTags["js"] or ""} </head> <body> <nav> <div class="nav-link">[ <a href="/">Home</a> ]</div> <div class="nav-link">[ <a href="/blog">Blog</a> ]</div> <div class="nav-link">[ <a href="/github" target="_blank" rel="noopener noreferrer">GitHub</a> ]</div> <div class="nav-link">[ <a href="/radio">Radio</a> ]</div> </nav> <div id="article">{articleHTML["article"]}</div> <div class="bottom-footer"> <hr class="footer-line" /> <footer> <div>This website was crafted with the help of a lot of ☕ and 💪🏼</div> <div class="contact-links"> <div><a href="mailto:viknegi0@gmail.com">Mail</a></div> <div><a href="https://github.com/lostvikx" target="_blank" rel="noopener noreferrer">GitHub</a></div> <div><a href="https://twitter.com/lostvikx" target="_blank" rel="noopener noreferrer">Twitter</a></div> <div><a href="https://linkedin.com/in/vikram-singh-negi/" target="_blank" rel="noopener noreferrer">Linkedin</a></div> </div> </footer> </div> <script src="{javascriptPath}" type="module"></script> </body> </html>""" # rm article (the html string) from the object articleHTML.pop("article", None) # only blog posts get saved to the DB if isBlog: saveToBlogDB(articleHTML) return html def saveHTMLFile(isBlog:bool, fileName:str)->None: """ Creates an HTML file in either the ./blog or ./ (root directory) """ if isBlog: path = f"{os.getcwd()}/public/blog/{fileName}.html" else: path = f"{os.getcwd()}/public/{fileName}.html" try: HTMLString = makeHTMLString(isBlog, createArticle(f"{fileName}.md", isBlog)) except: print("Couldn't create HTML String.") HTMLString = "" if HTMLString != "": with open(path, "w") as file_handle: file_handle.write(HTMLString) file_handle.close() print(f"Your HTML file: {path}") else: print(f"err: in writing {fileName}") # Input a markdown file fileName = None while True: # if blank fName = input("Enter md file to convert: ") or "test" fileCom = fName.split(".") # .md file if fileCom[-1] == "md": fileName = "".join(fileCom[:-1]) else: fileName = fName # check for the .md fileName in both article and root dir articlePath = f"{os.getcwd()}/articles/{fileName}.md" rootFilePath = f"{os.getcwd()}/root_files/{fileName}.md" articlePathExists = os.path.exists(articlePath) rootFilePathExists = os.path.exists(rootFilePath) if articlePathExists and rootFilePathExists: print(f"\nfound [1]: {articlePath}") print(f"found [2]: {rootFilePath}\n") print("[1] -> blog\n[2] -> root_file") # Is a blog post or not while True: try: foundId = int(input("\nSelection: ")) # print(foundId, type(foundId)) if foundId == 1: saveHTMLFile(True, fileName) elif foundId == 2: saveHTMLFile(False, fileName) else: print("Enter a valid option!") continue break except: print("Enter a valid option!") continue elif articlePathExists: print(f"\nfound: {articlePath}") saveHTMLFile(True, fileName) elif rootFilePathExists: print(f"\nfound: {rootFilePath}") saveHTMLFile(False, fileName) else: print(f"Error: {fileName}.md not found!") if articlePathExists or rootFilePathExists: break else: continue
#!/usr/bin/env python3 import os import re import datetime import json import copy # Parses the md file, outputs html string def createArticle(mdFileName:str, isBlog=True): """ mdFileName: md file name isBlog: boolean Returns: { article, postTitle, postSubject, timeCreated } article: the blog post in HTML string to be injected postTitle: h1 postSubject: initial 50 chars of first para timeCreated: datetime, updates when the function is called """ # TODO: Add tags to articles, maybe a custom syntax in the markdown file article = "" postTitle = "" postSubject = None # global variables global timeCreated timeCreated = datetime.datetime.now().strftime("%a %b %d %X %Y") global thumbnail thumbnail = "" global numImgFound numImgFound = -1 def isHeader(line): return line[0:1] == "#" and line != "" def makeHeader(line): headerType, *text = line.split(" ") headerText = " ".join(text) headerId = "-".join(re.sub(r"[\W_]+", " ", headerText).strip().lower().split(" ")) # header = f"<h{len(headerType)} id=\"{headerId}\"><a href=\"#{headerId}\" class=\"topic\">{headerText}</a></h{len(headerType)}>" header = f"<h{len(headerType)} id=\"{headerId}\" class=\"topic\">{headerText}</h{len(headerType)}>" # only show post-info if blog post if len(headerType) == 1 and isBlog and mdFileName != "index.md": global timeCreated title = headerText header += f"<div id=\"post-info\"><p class=\"post-meta\">{timeCreated}, Author: Vikram S. Negi</p></div>" return [header, title] elif len(headerType) == 1: title = headerText return [header, title] else: return header def makeLink(line): foundLink = re.findall(r"\[(.+?)\]\((.+?)\)", line) # print(foundLink) for text, href in foundLink: if href[0:1] == "#": line = re.sub(r"\[(.+?)\]\((.+?)\)", f"<a href=\"{href}\">{text}</a>", line, count=1) else: line = re.sub(r"\[(.+?)\]\((.+?)\)", f"<a href=\"{href}\" target=\"_blank\" rel=\"noopener noreferrer\">{text}</a>", line, count=1) if foundLink: # print("found:", line, end="\n\n") return line def makeItalic(line): foundItalic = re.findall(r"\*(.+?)\*", line) for text in foundItalic: line = re.sub(r"\*(.+?)\*", f"<em>{text}</em>", line, count=1) if foundItalic: return line def makeBold(line): foundBold = re.findall(r"\*\*(.+?)\*\*", line) for text in foundBold: line = re.sub(r"\*\*(.+?)\*\*", f"<strong>{text}</strong>", line, count=1) if foundBold: return line def isListItem(line): return line[0:1] == "*" and line[1:2] == " " def makeList(line, init=True): list = "" bullet, *text = line.split(" ") listItem = " ".join(text) if init: list += "<ul>" list += f"<li>{listItem}</li>" else: list += f"<li>{listItem}</li>" return list def makeCode(line): foundCode = re.findall(r"\`(.+?)\`", line) for text in foundCode: line = re.sub(r"\`.+?\`", f"<code>{text}</code>", line, count=1) if foundCode: return line def isCodeBlock(line): return line[0:3] == "```" def makeCodeBlock(line): codeBlock = "" lang = "" if len(line) > 3: lang = re.findall(r"^\`\`\`(\w+)", line)[0] codeBlock += f"<pre><code class=\"language-{lang}\">" else: codeBlock += f"<pre><code>" return codeBlock def isImg(line): return line[0:1] == "!" def makeImg(line): foundImg = re.findall(r"\!\[(.+?)\]\((.+?)\)", line) if foundImg: global numImgFound numImgFound += len(foundImg) for alt, linkAndCaption in foundImg: # print(linkAndCaption) try: link, *caption = linkAndCaption.split(" ") except: # print("no caption was found!") link = linkAndCaption caption = [] # print(caption) global thumbnail if thumbnail == "": # print("thumbnail is blank", link) thumbnail = link if len(caption) == 0: line = re.sub(r"\!\[(.+?)\]\((.+?)\)", f"<figure><img src=\"{link}\" alt=\"{alt}\" loading=\"lazy\" /></figure>", line, count=1) else: line = re.sub(r"\!\[(.+?)\]\((.+?)\)", f"<figure><img src=\"{link}\" alt=\"{alt}\" loading=\"lazy\" /><figcaption>Figure {numImgFound}. {' '.join(caption)[1:-1]}</figcaption></figure>", line, count=1) if foundImg: return line def isHr(line): return line[0:3] == "---" def isBlockquote(line): return line[0:1] == ">" def makeBlockquote(line): sign, *text = line.split(" ") text = " ".join(text) return f"<blockquote><p class=\"quote\">{text}</p></blockquote>" # TODO: error handling if syntax does has None as the input: ![]() maybe add "" (blank sting) instead of None # TODO: mark # TODO: <!-- comments --> # TODO: some functions seem repetitive, refactor those! if isBlog: path = os.getcwd() + f"/articles/{mdFileName}" else: path = os.getcwd() + f"/root_files/{mdFileName}" print(f"reading {mdFileName}...") with open(path, "r") as f: prevLine = "" inCodeBlock = False isFirstPara = True for line in f: # cross site scripting (xss) security reason # line = line.replace("<", "&lt;").replace(">", "&gt;") # for some reason the following replace method, replaces "!" with "<" if isImg(line): article += makeImg(line) line = "" line = line.replace("<", "&lt;") if not inCodeBlock: line = line.strip() # Check this, if any errors regarding imgs line = makeImg(line) or line line = makeLink(line) or line line = makeBold(line) or line line = makeItalic(line) or line if isBlockquote(line): article += makeBlockquote(line) line = "" # print(index, line) if isHeader(line): headerOut = makeHeader(line) if type(headerOut) == list: headerTag = headerOut[0] postTitle += headerOut[1] else: headerTag = headerOut article += headerTag line = "" unorderedList = "" if isListItem(line): try: if not isListItem(prevLine): unorderedList += makeList(line, init=True) else: unorderedList += makeList(line, init=False) except: print("err: prevLine blank or first in the file") unorderedList += makeList(line, init=True) prevLine = line line = "" elif not isListItem(line): try: if isListItem(prevLine): unorderedList += "</ul>" except: unorderedList += "</ul>" prevLine = line article += unorderedList codeBlock = "" if isCodeBlock(line) and not inCodeBlock: codeBlock += makeCodeBlock(line) inCodeBlock = True line = "" elif isCodeBlock(line) and inCodeBlock: inCodeBlock = False codeBlock += "</code></pre>" line = "" elif inCodeBlock: codeBlock += line.replace("<", "&lt;").replace(">", "&gt;") line = "" article += codeBlock line = makeCode(line) or line if isHr(line): article += "<hr noshade />" line = "" if line != "" and isFirstPara: if len(line) > 50: postSubject = line[:47].strip() + "..." else: postSubject = line line = f"<p>{line}</p>" isFirstPara = False elif line != "" and not isFirstPara: line = f"<p>{line}</p>" article += line f.close() # print(article) fileCom = mdFileName.split(".") fileName = "".join(fileCom[:-1]) # if isBlog: # pathToHTMLFile = f"./blog/{fileName}.html" # else: # pathToHTMLFile = f"./{fileName}.html" pathToHTMLFile = f"./{fileName}.html" return { "article": article, "pathToHTMLFile": pathToHTMLFile, "postTitle": postTitle, "postSubject": postSubject, "timeCreated": timeCreated, "thumbnail": thumbnail } # Test func # print(createArticle("fintech-info.md")) def enterTags(nTags=3): """ Asks user to input hashtags, for blog posts 3 tags by default Returns: an array of tags """ tags = [] # TODO: add confirmation of tags while nTags > 0: tag = input("HashTag: ").strip().lower().replace(" ", "_") or "misc" tags.append(tag) nTags -= 1 return tags def updateCategoryTagsDB(HTMLPath:str, tags:list): """ updates the category tags db """ post = ".".join(HTMLPath[2:].split(".")[:-1 or None]) pathToDB = f"{os.getcwd()}/db/category-tags.json" tagDict = None # {"posts": [], "tagFrequency": {}} with open(pathToDB, "r") as db: tagDict = json.load(db) if post in tagDict["posts"]: print(f"\nTag info of {post} is already in CategoryTagsDB\n") else: tagDict["posts"].append(post) for tag in tags: tagDict["tagFrequency"][tag] = tagDict["tagFrequency"].get(tag, 0) + 1 print(f"\n{len(tagDict['posts'])} posts info saved in CategoryTagsDB\n") with open(pathToDB, "w") as db: json.dump(tagDict, db) # json db def saveToBlogDB(data:dict): """ saves the post meta data, like postTitle, to db """ pathToDB = f"{os.getcwd()}/db/blog-info.json" blogInfo = None # read and load json as dict with open(pathToDB, "r") as db: blogInfo = json.load(db) results = blogInfo["results"] articlePathHTML = data["pathToHTMLFile"] HTMLFileName = articlePathHTML.split("/")[-1] blogFound = False i = 0 while i < len(results): if articlePathHTML == results[i]["pathToHTMLFile"]: # check if the HTML file exists in the /blog dir entirePath = f"{os.getcwd()}/public/blog/{articlePathHTML[2:]}" if not os.path.exists(entirePath): print(f"\nFile doesn't exists! Removing it from the DB...\n") results.pop(i) break print("\nUpdating the blog post...\n") blogFound = True # copy the tag from previously saved data tags = copy.deepcopy(results[i]["tags"]) data["tags"] = tags timeCreated = results[i]["timeCreated"] data["timeCreated"] = timeCreated # rest everything gets updated results[i] = data break i += 1 # /blog/index.html doesn't get entered into the db if not blogFound and HTMLFileName != "index.html": print("Adding article tags...") data["tags"] = enterTags() updateCategoryTagsDB(data["pathToHTMLFile"], data["tags"]) results.insert(0, data) # update length blogInfo["length"] = len(results) print(f"\nNumber of posts saved in BlogInfoDB: {len(results)}\n") # clear the data and re-write everything with open(pathToDB, "w") as db: json.dump(blogInfo, db) # print(data["pathToHTMLFile"], data["tags"]) # !Important: Only for testing, clearing the blog-info.json def clearResults(): with open(f"{os.getcwd()}/db/blog-info.json", "w") as db: json.dump({"results": []}, db) # Create entire HTML string def makeHTMLString(isBlog:bool, articleHTML:dict)->str: """ Params: isBlog, articleHTML Returns: returns html string """ print("\ncreating html string...\n") stylePath = "./style.css" javascriptPath = "./js/main.js" codeBlockTags = { "css": "<link rel=\"stylesheet\" href=\"./css/dark.min.css\">", "js": "<script src=\"./js/highlight.min.js\"></script>" } if isBlog: stylePath = "../style.css" javascriptPath = "../js/main.js" codeBlockTags["css"] = "<link rel=\"stylesheet\" href=\"../css/dark.min.css\">" codeBlockTags["js"] = "<script src=\"../js/highlight.min.js\"></script>" html = f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{articleHTML["postTitle"] or "Home"} - lostvikx</title> <link rel="stylesheet" href="{stylePath}"> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>❄️</text></svg>" > {codeBlockTags["css"] or ""} {codeBlockTags["js"] or ""} </head> <body> <nav> <div class="nav-link">[ <a href="/">Home</a> ]</div> <div class="nav-link">[ <a href="/blog">Blog</a> ]</div> <div class="nav-link">[ <a href="/github" target="_blank" rel="noopener noreferrer">GitHub</a> ]</div> <div class="nav-link">[ <a href="/radio">Radio</a> ]</div> </nav> <div id="article">{articleHTML["article"]}</div> <div class="bottom-footer"> <hr class="footer-line" /> <footer> <div>This website was crafted with the help of a lot of ☕ and 💪🏼</div> <div class="contact-links"> <div><a href="mailto:viknegi0@gmail.com">Mail</a></div> <div><a href="https://github.com/lostvikx" target="_blank" rel="noopener noreferrer">GitHub</a></div> <div><a href="https://twitter.com/lostvikx" target="_blank" rel="noopener noreferrer">Twitter</a></div> <div><a href="https://linkedin.com/in/vikram-singh-negi/" target="_blank" rel="noopener noreferrer">Linkedin</a></div> </div> </footer> </div> <script src="{javascriptPath}" type="module"></script> </body> </html>""" # rm article (the html string) from the object articleHTML.pop("article", None) # only blog posts get saved to the DB if isBlog: saveToBlogDB(articleHTML) return html def saveHTMLFile(isBlog:bool, fileName:str)->None: """ Creates an HTML file in either the ./blog or ./ (root directory) """ if isBlog: path = f"{os.getcwd()}/public/blog/{fileName}.html" else: path = f"{os.getcwd()}/public/{fileName}.html" try: HTMLString = makeHTMLString(isBlog, createArticle(f"{fileName}.md", isBlog)) except: print("Couldn't create HTML String.") HTMLString = "" if HTMLString != "": with open(path, "w") as file_handle: file_handle.write(HTMLString) file_handle.close() print(f"Your HTML file: {path}") else: print(f"err: in writing {fileName}") # Input a markdown file fileName = None while True: # if blank fName = input("Enter md file to convert: ") or "test" fileCom = fName.split(".") # .md file if fileCom[-1] == "md": fileName = "".join(fileCom[:-1]) else: fileName = fName # check for the .md fileName in both article and root dir articlePath = f"{os.getcwd()}/articles/{fileName}.md" rootFilePath = f"{os.getcwd()}/root_files/{fileName}.md" articlePathExists = os.path.exists(articlePath) rootFilePathExists = os.path.exists(rootFilePath) if articlePathExists and rootFilePathExists: print(f"\nfound [1]: {articlePath}") print(f"found [2]: {rootFilePath}\n") print("[1] -> blog\n[2] -> root_file") # Is a blog post or not while True: try: foundId = int(input("\nSelection: ")) # print(foundId, type(foundId)) if foundId == 1: saveHTMLFile(True, fileName) elif foundId == 2: saveHTMLFile(False, fileName) else: print("Enter a valid option!") continue break except: print("Enter a valid option!") continue elif articlePathExists: print(f"\nfound: {articlePath}") saveHTMLFile(True, fileName) elif rootFilePathExists: print(f"\nfound: {rootFilePath}") saveHTMLFile(False, fileName) else: print(f"Error: {fileName}.md not found!") if articlePathExists or rootFilePathExists: break else: continue
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # This file is part of Wizard # MIT License # Copyright (c) 2021 Leo brunel # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This module manages the project events # the events are stored in the project database # and are accessed by the 'project' module but # this module decode what is stored in the # event rows # Python modules import logging # Wizard modules from wizard.core import environment from wizard.core import project from wizard.core import assets logger = logging.getLogger(__name__) def add_creation_event(instance_type, instance_id): data = (instance_type, instance_id) title = f"Created {assets.instance_to_string((instance_type, instance_id))}" project.add_event('creation', title, '', data) def add_export_event(export_version_id): title = f"Exported {assets.instance_to_string(("export_version", export_version_id))}" data = export_version_id export_version_row = project.get_export_version_data(export_version_id) project.add_event('export', title, export_version_row['comment'], data, '', export_version_row['work_version_thumbnail_path']) def add_archive_event(title, archive_path): data = archive_path project.add_event('archive', title, '', data) def add_tag_event(instance_type, instance_id, comment, user): data_dic = dict() data_dic['instance'] = (instance_type, instance_id) data_dic['tagged_user'] = user title = f"Tagged {user} in a comment" project.add_event('tag', title, comment, data_dic)
# coding: utf-8 # Author: Leo BRUNEL # Contact: contact@leobrunel.com # This file is part of Wizard # MIT License # Copyright (c) 2021 Leo brunel # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This module manages the project events # the events are stored in the project database # and are accessed by the 'project' module but # this module decode what is stored in the # event rows # Python modules import logging # Wizard modules from wizard.core import environment from wizard.core import project from wizard.core import assets logger = logging.getLogger(__name__) def add_creation_event(instance_type, instance_id): data = (instance_type, instance_id) title = f"Created {assets.instance_to_string((instance_type, instance_id))}" project.add_event('creation', title, '', data) def add_export_event(export_version_id): title = f"Exported {assets.instance_to_string(('export_version', export_version_id))}" data = export_version_id export_version_row = project.get_export_version_data(export_version_id) project.add_event('export', title, export_version_row['comment'], data, '', export_version_row['work_version_thumbnail_path']) def add_archive_event(title, archive_path): data = archive_path project.add_event('archive', title, '', data) def add_tag_event(instance_type, instance_id, comment, user): data_dic = dict() data_dic['instance'] = (instance_type, instance_id) data_dic['tagged_user'] = user title = f"Tagged {user} in a comment" project.add_event('tag', title, comment, data_dic)
from financialmodelingprep.decorator import get_json_data BASE_URL = 'https://financialmodelingprep.com' class calendars(): BASE_URL = 'https://financialmodelingprep.com' API_KEY = '' def __init__(self, API_KEY): self.API = API_KEY @get_json_data def earning_calendar(self): ''' Earnings Calendar ''' return f'{self.BASE_URL}/api/v3/earning_calendar?apikey={self.API}' @get_json_data def earning_calendar_period(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/earning_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def company_historical_earnings_calender(self, ticker: str, limit: int): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/earning_calendar/{ticker}?limit={str(limit)}?apikey={self.API}' @get_json_data def company_historical_earnings_calender(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/ipo_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def ipo_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/ipo_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def stock_split_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/stock_split_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def stock_dividend_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/stock_dividend_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def economic_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/economic_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}' @get_json_data def economic_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/economic_calendar?from={datetime_from.strftime('%Y-%m-%d')}&to={datetime_to.strftime('%Y-%m-%d')}?apikey={self.API}'
from financialmodelingprep.decorator import get_json_data BASE_URL = 'https://financialmodelingprep.com' class calendars(): BASE_URL = 'https://financialmodelingprep.com' API_KEY = '' def __init__(self, API_KEY): self.API = API_KEY @get_json_data def earning_calendar(self): ''' Earnings Calendar ''' return f'{self.BASE_URL}/api/v3/earning_calendar?apikey={self.API}' @get_json_data def earning_calendar_period(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/earning_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def company_historical_earnings_calender(self, ticker: str, limit: int): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/earning_calendar/{ticker}?limit={str(limit)}?apikey={self.API}' @get_json_data def company_historical_earnings_calender(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/ipo_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def ipo_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/ipo_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def stock_split_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/stock_split_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def stock_dividend_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/stock_dividend_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def economic_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/economic_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}' @get_json_data def economic_calendar(self, datetime_from, datetime_to): ''' Earnings Calendar with period ''' return f'{self.BASE_URL}/api/v3/economic_calendar?from={datetime_from.strftime("%Y-%m-%d")}&to={datetime_to.strftime("%Y-%m-%d")}?apikey={self.API}'
""" CS 229 Machine Learning Question: Reinforcement Learning - The Inverted Pendulum """ from __future__ import division, print_function import matplotlib matplotlib.use('TkAgg') from env import CartPole, Physics import matplotlib.pyplot as plt import numpy as np from scipy.signal import lfilter """ Parts of the code (cart and pole dynamics, and the state discretization) are inspired from code available at the RL repository http://www-anw.cs.umass.edu/rlr/domains.html Briefly, the cart-pole system is described in `cart_pole.py`. The main simulation loop in this file calls the `simulate()` function for simulating the pole dynamics, `get_state()` for discretizing the otherwise continuous state space in discrete states, and `show_cart()` for display. Some useful parameters are listed below: `NUM_STATES`: Number of states in the discretized state space You must assume that states are numbered 0 through `NUM_STATES` - 1. The state numbered `NUM_STATES` - 1 (the last one) is a special state that marks the state when the pole has been judged to have fallen (or when the cart is out of bounds). However, you should NOT treat this state any differently in your code. Any distinctions you need to make between states should come automatically from your learning algorithm. After each simulation cycle, you are supposed to update the transition counts and rewards observed. However, you should not change either your value function or the transition probability matrix at each cycle. Whenever the pole falls, a section of your code below will be executed. At this point, you must use the transition counts and reward observations that you have gathered to generate a new model for the MDP (i.e. transition probabilities and state rewards). After that, you must use value iteration to get the optimal value function for this MDP model. `TOLERANCE`: Controls the convergence criteria for each value iteration run. In value iteration, you can assume convergence when the maximum absolute change in the value function at any state in an iteration becomes lower than `TOLERANCE. You need to write code that chooses the best action according to your current value function, and the current model of the MDP. The action must be either 0 or 1 (corresponding to possible directions of pushing the cart) Finally, we assume that the simulation has converged when `NO_LEARNING_THRESHOLD` consecutive value function computations all converged within one value function iteration. Intuitively, it seems like there will be little learning after this, so we end the simulation here, and say the overall algorithm has converged. Learning curves can be generated by calling a code snippet at the end (it assumes that the learning was just executed, and the array `time_steps_to_failure` that records the time for which the pole was balanced before each failure is in memory). `num_failures` is a variable that stores the number of failures (pole drops / cart out of bounds) till now. Other parameters in the code are described below: `GAMMA`: Discount factor to be used The following parameters control the simulation display; you dont really need to know about them: `pause_time`: Controls the pause between successive frames of the display. Higher values make your simulation slower. `min_trial_length_to_start_display`: Allows you to start the display only after the pole has been successfully balanced for at least this many trials. Setting this to zero starts the display immediately. Choosing a reasonably high value (around 100) can allow you to rush through the initial learning quickly, and start the display only after the performance is reasonable. """ def initialize_mdp_data(num_states): """ Return a variable that contains all the parameters/state you need for your MDP. Feel free to use whatever data type is most convenient for you (custom classes, tuples, dicts, etc) Assume that no transitions or rewards have been observed. Initialize the value function array to small random values (0 to 0.10, say). Initialize the transition probabilities uniformly (ie, probability of transitioning for state x to state y using action a is exactly 1/num_states). Initialize all state rewards to zero. Args: num_states: The number of states Returns: The initial MDP parameters """ transition_counts = np.zeros((num_states, num_states, 2)) # P_ijk = P_{s_i, a_k} (s_j) i.e. s_i -> s_j under a_k transition_probs = np.ones((num_states, num_states, 2)) / num_states # initial uniform distribution #Index zero is count of rewards being -1 , index 1 is count of total num state is reached reward_counts = np.zeros((num_states, 2)) reward = np.zeros(num_states) value = np.random.rand(num_states) * 0.1 # - 0.05 - 1/num_states return { 'transition_counts': transition_counts, 'transition_probs': transition_probs, 'reward_counts': reward_counts, 'reward': reward, 'value': value, 'num_states': num_states, 'state_action_history': [[]] } def choose_action(state, mdp_data): """ Choose the next action (0 or 1) that is optimal according to your current mdp_data. When there is no optimal action, return a random action. Args: state: The current state in the MDP mdp_data: The parameters for your MDP. See initialize_mdp_data. Returns: 0 or 1 that is optimal according to your current MDP """ # *** START CODE HERE *** # argmax over actions a of sum_s' P_sa(s') V(s') # s, s', a axes. times in axis s', sum over it, argmax over a and then take state s expected_state_action_value = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1) optimal = expected_state_action_value.argmax(axis=1) # argmax over the 2 actions is_optimal = expected_state_action_value[state][int(optimal[state])] > \ expected_state_action_value[state][int(not optimal[state])] action = optimal[state] if is_optimal else np.random.randint(2) #print(f'state: {state}; optimal action: {action}; expected values: {expected_state_action_value[state]}') return optimal[state] if expected_state_action_value[state][int(optimal[state])] > expected_state_action_value[state][int(not optimal[state])] else np.random.randint(2) # *** END CODE HERE *** def update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, reward): """ Update the transition count and reward count information in your mdp_data. Do not change the other MDP parameters (those get changed later). Record the number of times `state, action, new_state` occurs. Record the rewards for every `new_state` (since rewards are -1 or 0, you just need to record number of times reward -1 is seen in 'reward_counts' index new_state,0) Record the number of time `new_state` was reached (in 'reward_counts' index new_state,1) Args: mdp_data: The parameters of your MDP. See initialize_mdp_data. state: The state that was observed at the start. action: The action you performed. new_state: The state after your action. reward: The reward after your action (i.e. reward corresponding to new_state). Returns: Nothing """ # *** START CODE HERE *** mdp_data['state_action_history'][-1].append([state, action, new_state]) if reward == -1: mdp_data['reward_counts'][new_state][0] += 1 mdp_data['reward_counts'][new_state][1] += 1 # the number of times reaching this state regardless of reward -1 or 0 mdp_data['transition_counts'][state, new_state, action] += 1 # *** END CODE HERE *** # This function does not return anything return def update_mdp_transition_probs_reward(mdp_data): """ Update the estimated transition probabilities and reward values in your MDP. Make sure you account for the case when a state-action pair has never been tried before, or the state has never been visited before. In that case, you must not change that component (and thus keep it at the initialized uniform distribution). Args: mdp_data: The data for your MDP. See initialize_mdp_data. Returns: Nothing """ # *** START CODE HERE *** num_states = mdp_data['value'].shape[0] transition_counts = mdp_data['transition_counts'] # i.e. some s' transition occured for s,a pair state_actions_occurred = transition_counts.sum(axis=1) > 0 state_actions_occurred = np.tile(state_actions_occurred, (num_states, 1, 1)).transpose(1,0,2) # where s,a pair occured take from counts, otherwise from the previous probs transition_probs = np.where(state_actions_occurred, transition_counts, mdp_data['transition_probs']) # counts at s' for s,a pair divided by total counts for s,a is our new prob - or same as old prob if no s,a # pair occured transition_probs = transition_probs/transition_probs.sum(axis=1).reshape(num_states, 1, 2) mdp_data['transition_probs'] = transition_probs # number of -1 rewards divided by total number of rewards (more general would be sum rewards / number times visited) # rewards <-> new states, so did we ever reach this new state? reward_occured = transition_counts.sum(axis=(0, 2)) > 0 reward = np.where(reward_occured, - mdp_data['reward_counts'][:, 0] / mdp_data['reward_counts'][:, 1], mdp_data['reward']) mdp_data['reward'] = reward # *** END CODE HERE *** # This function does not return anything return def update_mdp_value(mdp_data, tolerance, gamma): """ Update the estimated values in your MDP. Perform value iteration using the new estimated model for the MDP. The convergence criterion should be based on `TOLERANCE` as described at the top of the file. Return true if it converges within one iteration. Args: mdp_data: The data for your MDP. See initialize_mdp_data. tolerance: The tolerance to use for the convergence criterion. gamma: Your discount factor. Returns: True if the value iteration converged in one iteration """ # *** START CODE HERE *** action_values = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1) old_value = mdp_data['value'] mdp_data['value'] = mdp_data['reward'] + gamma * action_values.max(axis=1) max_diff = np.max(np.abs(mdp_data['value'] - old_value)) print(f'max state value diff: {max_diff}') return max_diff < tolerance # *** END CODE HERE *** def plot_mdp_data(mdp_data): plt.figure() plt.plot(mdp_data['value']) def main(plot=True): # Seed the randomness of the simulation so this outputs the same thing each time np.random.seed(3) # Simulation parameters pause_time = 0.0001 min_trial_length_to_start_display = 100 display_started = min_trial_length_to_start_display == 0 NUM_STATES = 163 GAMMA = 0.995 TOLERANCE = 0.01 NO_LEARNING_THRESHOLD = 20 # TOTAL_MAX_TRIALS might be useful otherwise it takes up to 300 ish iterations to converge sometimes # Time cycle of the simulation time = 0 # These variables perform bookkeeping (how many cycles was the pole # balanced for before it fell). Useful for plotting learning curves. time_steps_to_failure = [] num_failures = 0 time_at_start_of_current_trial = 0 # You should reach convergence well before this max_failures = 500 # Initialize a cart pole cart_pole = CartPole(Physics()) # Starting `state_tuple` is (0, 0, 0, 0) # x, x_dot, theta, theta_dot represents the actual continuous state vector x, x_dot, theta, theta_dot = 0.0, 0.0, 0.0, 0.0 state_tuple = (x, x_dot, theta, theta_dot) # `state` is the number given to this state, you only need to consider # this representation of the state state = cart_pole.get_state(state_tuple) if min_trial_length_to_start_display == 0 or display_started == 1: cart_pole.show_cart(state_tuple, pause_time) mdp_data = initialize_mdp_data(NUM_STATES) # This is the criterion to end the simulation. # You should change it to terminate when the previous # 'NO_LEARNING_THRESHOLD' consecutive value function computations all # converged within one value function iteration. Intuitively, it seems # like there will be little learning after this, so end the simulation # here, and say the overall algorithm has converged. consecutive_no_learning_trials = 0 while consecutive_no_learning_trials < NO_LEARNING_THRESHOLD: action = choose_action(state, mdp_data) # Get the next state by simulating the dynamics state_tuple = cart_pole.simulate(action, state_tuple) # x, x_dot, theta, theta_dot = state_tuple # Increment simulation time time = time + 1 # Get the state number corresponding to new state vector new_state = cart_pole.get_state(state_tuple) # if display_started == 1: # cart_pole.show_cart(state_tuple, pause_time) #print(f'state transition prob: {state}, {action} -> {new_state}: {mdp_data['transition_probs'][state, new_state, action]}') # reward function to use - do not change this! if new_state == NUM_STATES - 1: R = -1 else: R = 0 # add to transition count for s, s', a triple and to reward count for s' update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, R) # Recompute MDP model whenever pole falls # Compute the value function V for the new model if new_state == NUM_STATES - 1: update_mdp_transition_probs_reward(mdp_data) converged_in_one_iteration = update_mdp_value(mdp_data, TOLERANCE, GAMMA) if converged_in_one_iteration: consecutive_no_learning_trials = consecutive_no_learning_trials + 1 else: consecutive_no_learning_trials = 0 # Do NOT change this code: Controls the simulation, and handles the case # when the pole fell and the state must be reinitialized. if new_state == NUM_STATES - 1: num_failures += 1 if num_failures >= max_failures: break print('[INFO] Failure number {}'.format(num_failures)) # plot_mdp_data(mdp_data) time_steps_to_failure.append(time - time_at_start_of_current_trial) print(f'time to failure: {time_steps_to_failure[-1]}') # print(f'history: {mdp_data['state_action_history'][-1]}') mdp_data["state_action_history"].append([]) # time_steps_to_failure[num_failures] = time - time_at_start_of_current_trial time_at_start_of_current_trial = time if time_steps_to_failure[num_failures - 1] > min_trial_length_to_start_display: display_started = 1 # Reinitialize state # x = 0.0 x = -1.1 + np.random.uniform() * 2.2 x_dot, theta, theta_dot = 0.0, 0.0, 0.0 state_tuple = (x, x_dot, theta, theta_dot) state = cart_pole.get_state(state_tuple) else: state = new_state if plot: plt.figure() # plot the learning curve (time balanced vs. trial) log_tstf = np.log(np.array(time_steps_to_failure)) plt.plot(np.arange(len(time_steps_to_failure)), log_tstf, 'k') window = 30 w = np.array([1/window for _ in range(window)]) weights = lfilter(w, 1, log_tstf) x = np.arange(window//2, len(log_tstf) - window//2) plt.plot(x, weights[window:len(log_tstf)], 'r--') plt.xlabel('Num failures') plt.ylabel('Log of num steps to failure') plt.savefig('./control_seed3.pdf') return np.array(time_steps_to_failure) if __name__ == '__main__': main()
""" CS 229 Machine Learning Question: Reinforcement Learning - The Inverted Pendulum """ from __future__ import division, print_function import matplotlib matplotlib.use('TkAgg') from env import CartPole, Physics import matplotlib.pyplot as plt import numpy as np from scipy.signal import lfilter """ Parts of the code (cart and pole dynamics, and the state discretization) are inspired from code available at the RL repository http://www-anw.cs.umass.edu/rlr/domains.html Briefly, the cart-pole system is described in `cart_pole.py`. The main simulation loop in this file calls the `simulate()` function for simulating the pole dynamics, `get_state()` for discretizing the otherwise continuous state space in discrete states, and `show_cart()` for display. Some useful parameters are listed below: `NUM_STATES`: Number of states in the discretized state space You must assume that states are numbered 0 through `NUM_STATES` - 1. The state numbered `NUM_STATES` - 1 (the last one) is a special state that marks the state when the pole has been judged to have fallen (or when the cart is out of bounds). However, you should NOT treat this state any differently in your code. Any distinctions you need to make between states should come automatically from your learning algorithm. After each simulation cycle, you are supposed to update the transition counts and rewards observed. However, you should not change either your value function or the transition probability matrix at each cycle. Whenever the pole falls, a section of your code below will be executed. At this point, you must use the transition counts and reward observations that you have gathered to generate a new model for the MDP (i.e. transition probabilities and state rewards). After that, you must use value iteration to get the optimal value function for this MDP model. `TOLERANCE`: Controls the convergence criteria for each value iteration run. In value iteration, you can assume convergence when the maximum absolute change in the value function at any state in an iteration becomes lower than `TOLERANCE. You need to write code that chooses the best action according to your current value function, and the current model of the MDP. The action must be either 0 or 1 (corresponding to possible directions of pushing the cart) Finally, we assume that the simulation has converged when `NO_LEARNING_THRESHOLD` consecutive value function computations all converged within one value function iteration. Intuitively, it seems like there will be little learning after this, so we end the simulation here, and say the overall algorithm has converged. Learning curves can be generated by calling a code snippet at the end (it assumes that the learning was just executed, and the array `time_steps_to_failure` that records the time for which the pole was balanced before each failure is in memory). `num_failures` is a variable that stores the number of failures (pole drops / cart out of bounds) till now. Other parameters in the code are described below: `GAMMA`: Discount factor to be used The following parameters control the simulation display; you dont really need to know about them: `pause_time`: Controls the pause between successive frames of the display. Higher values make your simulation slower. `min_trial_length_to_start_display`: Allows you to start the display only after the pole has been successfully balanced for at least this many trials. Setting this to zero starts the display immediately. Choosing a reasonably high value (around 100) can allow you to rush through the initial learning quickly, and start the display only after the performance is reasonable. """ def initialize_mdp_data(num_states): """ Return a variable that contains all the parameters/state you need for your MDP. Feel free to use whatever data type is most convenient for you (custom classes, tuples, dicts, etc) Assume that no transitions or rewards have been observed. Initialize the value function array to small random values (0 to 0.10, say). Initialize the transition probabilities uniformly (ie, probability of transitioning for state x to state y using action a is exactly 1/num_states). Initialize all state rewards to zero. Args: num_states: The number of states Returns: The initial MDP parameters """ transition_counts = np.zeros((num_states, num_states, 2)) # P_ijk = P_{s_i, a_k} (s_j) i.e. s_i -> s_j under a_k transition_probs = np.ones((num_states, num_states, 2)) / num_states # initial uniform distribution #Index zero is count of rewards being -1 , index 1 is count of total num state is reached reward_counts = np.zeros((num_states, 2)) reward = np.zeros(num_states) value = np.random.rand(num_states) * 0.1 # - 0.05 - 1/num_states return { 'transition_counts': transition_counts, 'transition_probs': transition_probs, 'reward_counts': reward_counts, 'reward': reward, 'value': value, 'num_states': num_states, 'state_action_history': [[]] } def choose_action(state, mdp_data): """ Choose the next action (0 or 1) that is optimal according to your current mdp_data. When there is no optimal action, return a random action. Args: state: The current state in the MDP mdp_data: The parameters for your MDP. See initialize_mdp_data. Returns: 0 or 1 that is optimal according to your current MDP """ # *** START CODE HERE *** # argmax over actions a of sum_s' P_sa(s') V(s') # s, s', a axes. times in axis s', sum over it, argmax over a and then take state s expected_state_action_value = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1) optimal = expected_state_action_value.argmax(axis=1) # argmax over the 2 actions is_optimal = expected_state_action_value[state][int(optimal[state])] > \ expected_state_action_value[state][int(not optimal[state])] action = optimal[state] if is_optimal else np.random.randint(2) #print(f'state: {state}; optimal action: {action}; expected values: {expected_state_action_value[state]}') return optimal[state] if expected_state_action_value[state][int(optimal[state])] > expected_state_action_value[state][int(not optimal[state])] else np.random.randint(2) # *** END CODE HERE *** def update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, reward): """ Update the transition count and reward count information in your mdp_data. Do not change the other MDP parameters (those get changed later). Record the number of times `state, action, new_state` occurs. Record the rewards for every `new_state` (since rewards are -1 or 0, you just need to record number of times reward -1 is seen in 'reward_counts' index new_state,0) Record the number of time `new_state` was reached (in 'reward_counts' index new_state,1) Args: mdp_data: The parameters of your MDP. See initialize_mdp_data. state: The state that was observed at the start. action: The action you performed. new_state: The state after your action. reward: The reward after your action (i.e. reward corresponding to new_state). Returns: Nothing """ # *** START CODE HERE *** mdp_data['state_action_history'][-1].append([state, action, new_state]) if reward == -1: mdp_data['reward_counts'][new_state][0] += 1 mdp_data['reward_counts'][new_state][1] += 1 # the number of times reaching this state regardless of reward -1 or 0 mdp_data['transition_counts'][state, new_state, action] += 1 # *** END CODE HERE *** # This function does not return anything return def update_mdp_transition_probs_reward(mdp_data): """ Update the estimated transition probabilities and reward values in your MDP. Make sure you account for the case when a state-action pair has never been tried before, or the state has never been visited before. In that case, you must not change that component (and thus keep it at the initialized uniform distribution). Args: mdp_data: The data for your MDP. See initialize_mdp_data. Returns: Nothing """ # *** START CODE HERE *** num_states = mdp_data['value'].shape[0] transition_counts = mdp_data['transition_counts'] # i.e. some s' transition occured for s,a pair state_actions_occurred = transition_counts.sum(axis=1) > 0 state_actions_occurred = np.tile(state_actions_occurred, (num_states, 1, 1)).transpose(1,0,2) # where s,a pair occured take from counts, otherwise from the previous probs transition_probs = np.where(state_actions_occurred, transition_counts, mdp_data['transition_probs']) # counts at s' for s,a pair divided by total counts for s,a is our new prob - or same as old prob if no s,a # pair occured transition_probs = transition_probs/transition_probs.sum(axis=1).reshape(num_states, 1, 2) mdp_data['transition_probs'] = transition_probs # number of -1 rewards divided by total number of rewards (more general would be sum rewards / number times visited) # rewards <-> new states, so did we ever reach this new state? reward_occured = transition_counts.sum(axis=(0, 2)) > 0 reward = np.where(reward_occured, - mdp_data['reward_counts'][:, 0] / mdp_data['reward_counts'][:, 1], mdp_data['reward']) mdp_data['reward'] = reward # *** END CODE HERE *** # This function does not return anything return def update_mdp_value(mdp_data, tolerance, gamma): """ Update the estimated values in your MDP. Perform value iteration using the new estimated model for the MDP. The convergence criterion should be based on `TOLERANCE` as described at the top of the file. Return true if it converges within one iteration. Args: mdp_data: The data for your MDP. See initialize_mdp_data. tolerance: The tolerance to use for the convergence criterion. gamma: Your discount factor. Returns: True if the value iteration converged in one iteration """ # *** START CODE HERE *** action_values = (mdp_data['transition_probs'] * mdp_data['value'].reshape(1, -1, 1)).sum(axis=1) old_value = mdp_data['value'] mdp_data['value'] = mdp_data['reward'] + gamma * action_values.max(axis=1) max_diff = np.max(np.abs(mdp_data['value'] - old_value)) print(f'max state value diff: {max_diff}') return max_diff < tolerance # *** END CODE HERE *** def plot_mdp_data(mdp_data): plt.figure() plt.plot(mdp_data['value']) def main(plot=True): # Seed the randomness of the simulation so this outputs the same thing each time np.random.seed(3) # Simulation parameters pause_time = 0.0001 min_trial_length_to_start_display = 100 display_started = min_trial_length_to_start_display == 0 NUM_STATES = 163 GAMMA = 0.995 TOLERANCE = 0.01 NO_LEARNING_THRESHOLD = 20 # TOTAL_MAX_TRIALS might be useful otherwise it takes up to 300 ish iterations to converge sometimes # Time cycle of the simulation time = 0 # These variables perform bookkeeping (how many cycles was the pole # balanced for before it fell). Useful for plotting learning curves. time_steps_to_failure = [] num_failures = 0 time_at_start_of_current_trial = 0 # You should reach convergence well before this max_failures = 500 # Initialize a cart pole cart_pole = CartPole(Physics()) # Starting `state_tuple` is (0, 0, 0, 0) # x, x_dot, theta, theta_dot represents the actual continuous state vector x, x_dot, theta, theta_dot = 0.0, 0.0, 0.0, 0.0 state_tuple = (x, x_dot, theta, theta_dot) # `state` is the number given to this state, you only need to consider # this representation of the state state = cart_pole.get_state(state_tuple) if min_trial_length_to_start_display == 0 or display_started == 1: cart_pole.show_cart(state_tuple, pause_time) mdp_data = initialize_mdp_data(NUM_STATES) # This is the criterion to end the simulation. # You should change it to terminate when the previous # 'NO_LEARNING_THRESHOLD' consecutive value function computations all # converged within one value function iteration. Intuitively, it seems # like there will be little learning after this, so end the simulation # here, and say the overall algorithm has converged. consecutive_no_learning_trials = 0 while consecutive_no_learning_trials < NO_LEARNING_THRESHOLD: action = choose_action(state, mdp_data) # Get the next state by simulating the dynamics state_tuple = cart_pole.simulate(action, state_tuple) # x, x_dot, theta, theta_dot = state_tuple # Increment simulation time time = time + 1 # Get the state number corresponding to new state vector new_state = cart_pole.get_state(state_tuple) # if display_started == 1: # cart_pole.show_cart(state_tuple, pause_time) #print(f'state transition prob: {state}, {action} -> {new_state}: {mdp_data["transition_probs"][state, new_state, action]}') # reward function to use - do not change this! if new_state == NUM_STATES - 1: R = -1 else: R = 0 # add to transition count for s, s', a triple and to reward count for s' update_mdp_transition_counts_reward_counts(mdp_data, state, action, new_state, R) # Recompute MDP model whenever pole falls # Compute the value function V for the new model if new_state == NUM_STATES - 1: update_mdp_transition_probs_reward(mdp_data) converged_in_one_iteration = update_mdp_value(mdp_data, TOLERANCE, GAMMA) if converged_in_one_iteration: consecutive_no_learning_trials = consecutive_no_learning_trials + 1 else: consecutive_no_learning_trials = 0 # Do NOT change this code: Controls the simulation, and handles the case # when the pole fell and the state must be reinitialized. if new_state == NUM_STATES - 1: num_failures += 1 if num_failures >= max_failures: break print('[INFO] Failure number {}'.format(num_failures)) # plot_mdp_data(mdp_data) time_steps_to_failure.append(time - time_at_start_of_current_trial) print(f'time to failure: {time_steps_to_failure[-1]}') # print(f'history: {mdp_data["state_action_history"][-1]}') mdp_data["state_action_history"].append([]) # time_steps_to_failure[num_failures] = time - time_at_start_of_current_trial time_at_start_of_current_trial = time if time_steps_to_failure[num_failures - 1] > min_trial_length_to_start_display: display_started = 1 # Reinitialize state # x = 0.0 x = -1.1 + np.random.uniform() * 2.2 x_dot, theta, theta_dot = 0.0, 0.0, 0.0 state_tuple = (x, x_dot, theta, theta_dot) state = cart_pole.get_state(state_tuple) else: state = new_state if plot: plt.figure() # plot the learning curve (time balanced vs. trial) log_tstf = np.log(np.array(time_steps_to_failure)) plt.plot(np.arange(len(time_steps_to_failure)), log_tstf, 'k') window = 30 w = np.array([1/window for _ in range(window)]) weights = lfilter(w, 1, log_tstf) x = np.arange(window//2, len(log_tstf) - window//2) plt.plot(x, weights[window:len(log_tstf)], 'r--') plt.xlabel('Num failures') plt.ylabel('Log of num steps to failure') plt.savefig('./control_seed3.pdf') return np.array(time_steps_to_failure) if __name__ == '__main__': main()
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import getpass import os import textwrap from typing import Optional import attr import click import datetime import glob import releasetool.filehelpers import releasetool.git import releasetool.github import releasetool.secrets import releasetool.commands.common _CHANGELOG_TEMPLATE = """\ # Release History [RubyGems.org history][1] [1]: https://rubygems.org/gems/{package_name}/versions """ @attr.s(auto_attribs=True, slots=True) class Context(releasetool.commands.common.GitHubContext): last_release_version: Optional[str] = None last_release_committish: Optional[str] = None release_version: Optional[str] = None release_branch: Optional[str] = None pull_request: Optional[dict] = None version_file: Optional[str] = None def determine_package_name(ctx: Context) -> None: click.secho("> Figuring out the package name.", fg="cyan") ctx.package_name = os.path.basename(os.getcwd()) click.secho(f"Looks like we're releasing {ctx.package_name}.") def determine_last_release(ctx: Context) -> None: click.secho("> Figuring out what the last release was.", fg="cyan") tags = releasetool.git.list_tags() candidates = [tag for tag in tags if tag.startswith(ctx.package_name)] if candidates and "google-cloud" in candidates[0]: ctx.last_release_committish = candidates[0] ctx.last_release_version = candidates[0].rsplit("/").pop().lstrip("v") elif ("google-cloud" not in ctx.package_name) and tags: ctx.last_release_committish = tags[0] ctx.last_release_version = tags[0].rsplit("/")[-1].lstrip("v") else: click.secho( f"I couldn't figure out the last release for {ctx.package_name}, " "so I'm assuming this is the first release. Can you tell me " "which git rev/sha to start the changelog at?", fg="yellow", ) ctx.last_release_committish = click.prompt("Committish") ctx.last_release_version = "0.0.0" click.secho(f"The last release was {ctx.last_release_version}.") def gather_changes(ctx: Context) -> None: click.secho(f"> Gathering changes since {ctx.last_release_version}", fg="cyan") ctx.changes = releasetool.git.summary_log( from_=ctx.last_release_committish, to=f"{ctx.upstream_name}/master" ) click.secho(f"Cool, {len(ctx.changes)} changes found.") def edit_release_notes(ctx: Context) -> None: click.secho(f"> Opening your editor to finalize release notes.", fg="cyan") release_notes = "\n".join(f"* {change.strip()}" for change in set(ctx.changes)) ctx.release_notes = releasetool.filehelpers.open_editor_with_tempfile( release_notes, "release-notes.md" ).strip() def determine_release_version(ctx: Context) -> None: click.secho(f"> Now it's time to pick a release version!", fg="cyan") release_notes = textwrap.indent(ctx.release_notes, "\t") click.secho(f"Here's the release notes you wrote:\n\n{release_notes}\n") parsed_version = [int(x) for x in ctx.last_release_version.split(".")] if parsed_version == [0, 0, 0]: ctx.release_version = "0.1.0" return selection = click.prompt( "Is this a major, minor, or patch update (or enter the new version " "directly)" ) if selection == "major": parsed_version[0] += 1 parsed_version[1] = 0 parsed_version[2] = 0 elif selection == "minor": parsed_version[1] += 1 parsed_version[2] = 0 elif selection == "patch": parsed_version[2] += 1 else: ctx.release_version = selection return ctx.release_version = "{}.{}.{}".format(*parsed_version) click.secho(f"Got it, releasing {ctx.release_version}.") def create_release_branch(ctx) -> None: ctx.release_branch = f"release-{ctx.package_name}-v{ctx.release_version}" click.secho(f"> Creating branch {ctx.release_branch}", fg="cyan") return releasetool.git.checkout_create_branch(ctx.release_branch) def update_changelog(ctx: Context) -> None: changelog_filename = "CHANGELOG.md" click.secho(f"> Updating {changelog_filename}.", fg="cyan") if not os.path.exists(changelog_filename): print(f"{changelog_filename} does not yet exist. Opening it for " "creation.") releasetool.filehelpers.open_editor_with_content( changelog_filename, _CHANGELOG_TEMPLATE.format(package_name=ctx.package_name), ) today = datetime.date.today() changelog_entry = ( f"### {ctx.release_version} / {today}" f"\n\n" f"{ctx.release_notes}" f"\n\n" ) releasetool.filehelpers.insert_before( changelog_filename, changelog_entry, r"^### (.+)$|\Z" ) def update_version(ctx: Context) -> None: click.secho("> Updating version.rb.", fg="cyan") gemspec = glob.glob("*.gemspec")[0] version = releasetool.filehelpers.extract(gemspec, r"gem.version.*=(.*)") if version.lower().find("version") == -1: final = ( releasetool.filehelpers.extract(gemspec, "(gem.version.*=)") + f' "{ctx.release_version}"' ) ctx.version_file = gemspec releasetool.filehelpers.replace(ctx.version_file, r"gem.version.*", final) else: ctx.version_file = glob.glob("lib/**/version.rb", recursive=True)[0] releasetool.filehelpers.replace( ctx.version_file, r'VERSION = "(.+?)"', f'VERSION = "{ctx.release_version}"' ) def create_release_commit(ctx: Context) -> None: """Create a release commit.""" click.secho("> Committing changes to CHANGELOG.md, {ctx.version_file}", fg="cyan") releasetool.git.commit( ["CHANGELOG.md", ctx.version_file], f"Release {ctx.package_name} {ctx.release_version}\n\n{ctx.release_notes}", ) def push_release_branch(ctx: Context) -> None: click.secho("> Pushing release branch.", fg="cyan") releasetool.git.push(ctx.release_branch) def create_release_pr(ctx: Context, autorelease: bool = True) -> None: click.secho(f"> Creating release pull request.", fg="cyan") if ctx.upstream_repo == ctx.origin_repo: head = ctx.release_branch else: head = f"{ctx.origin_user}:{ctx.release_branch}" ctx.pull_request = ctx.github.create_pull_request( ctx.upstream_repo, head=head, title=f"Release {ctx.package_name} {ctx.release_version}", body=f"{ctx.release_notes}\n\nThis pull request was generated using releasetool.", ) if autorelease: ctx.github.add_issue_labels( ctx.upstream_repo, ctx.pull_request["number"], ["autorelease: pending"] ) click.secho(f"Pull request is at {ctx.pull_request["html_url"]}.") def start() -> None: ctx = Context() click.secho(f"o/ Hey, {getpass.getuser()}, let's release some Ruby!", fg="magenta") releasetool.commands.common.setup_github_context(ctx) determine_package_name(ctx) determine_last_release(ctx) gather_changes(ctx) edit_release_notes(ctx) determine_release_version(ctx) create_release_branch(ctx) update_changelog(ctx) update_version(ctx) create_release_commit(ctx) push_release_branch(ctx) # TODO: Confirm? create_release_pr(ctx) click.secho(f"\\o/ All done!", fg="magenta")
# Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import getpass import os import textwrap from typing import Optional import attr import click import datetime import glob import releasetool.filehelpers import releasetool.git import releasetool.github import releasetool.secrets import releasetool.commands.common _CHANGELOG_TEMPLATE = """\ # Release History [RubyGems.org history][1] [1]: https://rubygems.org/gems/{package_name}/versions """ @attr.s(auto_attribs=True, slots=True) class Context(releasetool.commands.common.GitHubContext): last_release_version: Optional[str] = None last_release_committish: Optional[str] = None release_version: Optional[str] = None release_branch: Optional[str] = None pull_request: Optional[dict] = None version_file: Optional[str] = None def determine_package_name(ctx: Context) -> None: click.secho("> Figuring out the package name.", fg="cyan") ctx.package_name = os.path.basename(os.getcwd()) click.secho(f"Looks like we're releasing {ctx.package_name}.") def determine_last_release(ctx: Context) -> None: click.secho("> Figuring out what the last release was.", fg="cyan") tags = releasetool.git.list_tags() candidates = [tag for tag in tags if tag.startswith(ctx.package_name)] if candidates and "google-cloud" in candidates[0]: ctx.last_release_committish = candidates[0] ctx.last_release_version = candidates[0].rsplit("/").pop().lstrip("v") elif ("google-cloud" not in ctx.package_name) and tags: ctx.last_release_committish = tags[0] ctx.last_release_version = tags[0].rsplit("/")[-1].lstrip("v") else: click.secho( f"I couldn't figure out the last release for {ctx.package_name}, " "so I'm assuming this is the first release. Can you tell me " "which git rev/sha to start the changelog at?", fg="yellow", ) ctx.last_release_committish = click.prompt("Committish") ctx.last_release_version = "0.0.0" click.secho(f"The last release was {ctx.last_release_version}.") def gather_changes(ctx: Context) -> None: click.secho(f"> Gathering changes since {ctx.last_release_version}", fg="cyan") ctx.changes = releasetool.git.summary_log( from_=ctx.last_release_committish, to=f"{ctx.upstream_name}/master" ) click.secho(f"Cool, {len(ctx.changes)} changes found.") def edit_release_notes(ctx: Context) -> None: click.secho(f"> Opening your editor to finalize release notes.", fg="cyan") release_notes = "\n".join(f"* {change.strip()}" for change in set(ctx.changes)) ctx.release_notes = releasetool.filehelpers.open_editor_with_tempfile( release_notes, "release-notes.md" ).strip() def determine_release_version(ctx: Context) -> None: click.secho(f"> Now it's time to pick a release version!", fg="cyan") release_notes = textwrap.indent(ctx.release_notes, "\t") click.secho(f"Here's the release notes you wrote:\n\n{release_notes}\n") parsed_version = [int(x) for x in ctx.last_release_version.split(".")] if parsed_version == [0, 0, 0]: ctx.release_version = "0.1.0" return selection = click.prompt( "Is this a major, minor, or patch update (or enter the new version " "directly)" ) if selection == "major": parsed_version[0] += 1 parsed_version[1] = 0 parsed_version[2] = 0 elif selection == "minor": parsed_version[1] += 1 parsed_version[2] = 0 elif selection == "patch": parsed_version[2] += 1 else: ctx.release_version = selection return ctx.release_version = "{}.{}.{}".format(*parsed_version) click.secho(f"Got it, releasing {ctx.release_version}.") def create_release_branch(ctx) -> None: ctx.release_branch = f"release-{ctx.package_name}-v{ctx.release_version}" click.secho(f"> Creating branch {ctx.release_branch}", fg="cyan") return releasetool.git.checkout_create_branch(ctx.release_branch) def update_changelog(ctx: Context) -> None: changelog_filename = "CHANGELOG.md" click.secho(f"> Updating {changelog_filename}.", fg="cyan") if not os.path.exists(changelog_filename): print(f"{changelog_filename} does not yet exist. Opening it for " "creation.") releasetool.filehelpers.open_editor_with_content( changelog_filename, _CHANGELOG_TEMPLATE.format(package_name=ctx.package_name), ) today = datetime.date.today() changelog_entry = ( f"### {ctx.release_version} / {today}" f"\n\n" f"{ctx.release_notes}" f"\n\n" ) releasetool.filehelpers.insert_before( changelog_filename, changelog_entry, r"^### (.+)$|\Z" ) def update_version(ctx: Context) -> None: click.secho("> Updating version.rb.", fg="cyan") gemspec = glob.glob("*.gemspec")[0] version = releasetool.filehelpers.extract(gemspec, r"gem.version.*=(.*)") if version.lower().find("version") == -1: final = ( releasetool.filehelpers.extract(gemspec, "(gem.version.*=)") + f' "{ctx.release_version}"' ) ctx.version_file = gemspec releasetool.filehelpers.replace(ctx.version_file, r"gem.version.*", final) else: ctx.version_file = glob.glob("lib/**/version.rb", recursive=True)[0] releasetool.filehelpers.replace( ctx.version_file, r'VERSION = "(.+?)"', f'VERSION = "{ctx.release_version}"' ) def create_release_commit(ctx: Context) -> None: """Create a release commit.""" click.secho("> Committing changes to CHANGELOG.md, {ctx.version_file}", fg="cyan") releasetool.git.commit( ["CHANGELOG.md", ctx.version_file], f"Release {ctx.package_name} {ctx.release_version}\n\n{ctx.release_notes}", ) def push_release_branch(ctx: Context) -> None: click.secho("> Pushing release branch.", fg="cyan") releasetool.git.push(ctx.release_branch) def create_release_pr(ctx: Context, autorelease: bool = True) -> None: click.secho(f"> Creating release pull request.", fg="cyan") if ctx.upstream_repo == ctx.origin_repo: head = ctx.release_branch else: head = f"{ctx.origin_user}:{ctx.release_branch}" ctx.pull_request = ctx.github.create_pull_request( ctx.upstream_repo, head=head, title=f"Release {ctx.package_name} {ctx.release_version}", body=f"{ctx.release_notes}\n\nThis pull request was generated using releasetool.", ) if autorelease: ctx.github.add_issue_labels( ctx.upstream_repo, ctx.pull_request["number"], ["autorelease: pending"] ) click.secho(f"Pull request is at {ctx.pull_request['html_url']}.") def start() -> None: ctx = Context() click.secho(f"o/ Hey, {getpass.getuser()}, let's release some Ruby!", fg="magenta") releasetool.commands.common.setup_github_context(ctx) determine_package_name(ctx) determine_last_release(ctx) gather_changes(ctx) edit_release_notes(ctx) determine_release_version(ctx) create_release_branch(ctx) update_changelog(ctx) update_version(ctx) create_release_commit(ctx) push_release_branch(ctx) # TODO: Confirm? create_release_pr(ctx) click.secho(f"\\o/ All done!", fg="magenta")
#!/usr/bin/env python3 """Zeff record config generator for HousePrice records.""" import logging import urllib.parse import csv LOGGER = logging.getLogger("zeffclient.record.generator") def HousePriceRecordGenerator(arg: str): """Return house primary key value.""" with open(arg, "r") as csvfile: for row in csv.DictReader(csvfile): url = f"file://{arg}/?id={row["id"]}" yield url if __name__ == "__main__": from logging import basicConfig, DEBUG from zeff.cli import load_configuration basicConfig(level=DEBUG) config = load_configuration() generatorarg = config.records.records_config_arg for config in HousePriceRecordGenerator(generatorarg): print(config)
#!/usr/bin/env python3 """Zeff record config generator for HousePrice records.""" import logging import urllib.parse import csv LOGGER = logging.getLogger("zeffclient.record.generator") def HousePriceRecordGenerator(arg: str): """Return house primary key value.""" with open(arg, "r") as csvfile: for row in csv.DictReader(csvfile): url = f"file://{arg}/?id={row['id']}" yield url if __name__ == "__main__": from logging import basicConfig, DEBUG from zeff.cli import load_configuration basicConfig(level=DEBUG) config = load_configuration() generatorarg = config.records.records_config_arg for config in HousePriceRecordGenerator(generatorarg): print(config)
#!/usr/bin/python import os import sys import time import signal import importlib import argparse import subprocess import xml.etree.ElementTree as ET import xml.dom.minidom import board import timer class Server(object): """ Othello server, implements a simple file-based playing protocol """ def __init__(self, p1_dir, p2_dir, delay, history, output): """ Initializes the Othello game server :param p1_dir: directory where the 'agent.py' of the 1st player is located :param p2_dir: directory where the 'agent.py' of the 2nd player is located :param delay: time limit to make a move :param history: file that will contain the match history (plain text) :param output: file to save game details (includes history) """ self.basedir = os.path.abspath('.') self.player_dirs = [p1_dir, p2_dir] self.player_colors = [board.Board.BLACK, board.Board.WHITE] self.color_names = ['black', 'white'] self.board = board.Board() self.history = [] # a list of performed moves (tuple: ((x,y), color) self.history_file = open(history, 'w') self.output_file = output self.delay = delay self.result = None # start and finish times of match self.start = None self.finish = None # imports 'agent.py' from both players self.player_modules = [ importlib.import_module(f"{p1_dir.strip("/")}.agent"), importlib.import_module(f"{p2_dir.strip("/")}.agent"), ] def __del__(self): self.history_file.close() def run(self): self.start = time.localtime() player = 0 illegal_count = [0, 0] # counts the number of illegal move attempts print(f'---- Current match: {self.player_dirs[0]} (B) x {self.player_dirs[1]} (W) ----') print('Initial board:') print(self.board.decorated_str()) while True: # runs until endgame # checks whether players have available moves no_moves_current = len(self.board.legal_moves(self.player_colors[player])) == 0 no_moves_opponent = len(self.board.legal_moves(self.board.opponent(self.player_colors[player]))) == 0 # calculates scores p1_score = sum([1 for char in str(self.board) if char == self.board.BLACK]) p2_score = sum([1 for char in str(self.board) if char == self.board.WHITE]) print(f'---- Current match: {self.player_dirs[0]} (B) x {self.player_dirs[1]} (W) ----') # disqualify player if he attempts illegal moves 5 times in a row if illegal_count[player] >= 5: print(f'Player {player+1} ({self.player_dirs[player]}) DISQUALIFIED! Too many illegal move attempts.') print('End of game reached!') print('Player 1 (B): %d' % p1_score) print('Player 2 (W): %d' % p2_score) self.result = 1 - player self.finish = time.localtime() return self.result # checks whether both players don't have available moves (end of game) if no_moves_current and no_moves_opponent: print('End of game reached! Scores:') print(f'Player 1 (B - {self.player_dirs[0]}): {p1_score}') print(f'Player 2 (W - {self.player_dirs[1]}): {p2_score}') if p1_score > p2_score: print(f'Player 1 (B - {self.player_dirs[0]} wins!') elif p2_score > p1_score: print(f'Player 2 (W - {self.player_dirs[1]}) wins!') else: print('Draw!') self.result = 0 if p1_score > p2_score else 1 if p2_score > p1_score else 2 self.finish = time.localtime() return self.result # if current player has no moves, toggle player and continue if no_moves_current: print(f'Player {player+1} ({self.player_dirs[player]}) has no legal moves and will not play this turn.') illegal_count[player] = 0 player = 1 - player continue # creates a copy of the board, so that player changes won't affect mine board_copy = board.from_string(self.board.__str__()) # calls current player's make_move function with the specified timeout function_call = timer.FunctionTimer(self.player_modules[player].make_move, (board_copy, self.player_colors[player])) move = function_call.run(self.delay) if move is None: # detects timeout print('Player %d has not made a move and lost its turn.' % (player + 1)) player = 1 - player continue move_x, move_y = move # saves move in history self.history_file.write('%d,%d,%s\n' % (move_x, move_y, self.player_colors[player])) self.history.append(((move_x, move_y), self.player_colors[player])) if self.board.process_move((move_x, move_y), self.player_colors[player]): illegal_count[player] = 0 print('Player %d move %d,%d accepted.' % (player + 1, move_x, move_y)) else: illegal_count[player] += 1 print('Player %d move %d,%d ILLEGAL!' % (player + 1,move_x, move_y)) print('Current board:') print(self.board.decorated_str()) # toggle player for next move player = 1 - player def write_output(self): """ Writes a xml file with detailed match data :return: """ os.chdir(self.basedir) root = ET.Element('othello-match') colors = [self.board.BLACK, self.board.WHITE, 'None'] self.player_dirs.append('None') # trick for writing a draw match timing = ET.SubElement(root, 'timing') timing.set('start', time.asctime(self.start)) timing.set('finish', time.asctime(self.finish)) scores = [self.board.piece_count['B'], self.board.piece_count['W']] for idx, p in enumerate(self.player_dirs[:2]): elem = ET.SubElement(root, 'player%d' % (idx + 1)) elem.set('directory', p) elem.set('color', colors[idx]) result = 'win' if scores[idx] > scores[idx - 1] else 'loss' if scores[idx] < scores[idx - 1] else 'draw' elem.set('result', result) elem.set('score', str(scores[idx])) moves = ET.SubElement(root, 'moves') for coords, color in self.history: move = ET.SubElement(moves, 'move') move.set('coord', '%d,%d' % coords) move.set('color', color) # preety xml thanks to: https://stackoverflow.com/a/1206856/1251716 ugly_xml = ET.tostring(root).decode('utf-8') dom = xml.dom.minidom.parseString(ugly_xml) # or xml.dom.minidom.parseString(xml_string) pretty_xml = dom.toprettyxml() f = open(self.output_file, 'w') f.write(pretty_xml) f.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Othello server.') parser.add_argument('players', metavar='player', type=str, nargs=2, help='Path to player directory') parser.add_argument('-d', '--delay', type=float, metavar='delay', default=5.0, help='Time allocated for players to make a move.') parser.add_argument('-l', '--log-history', type=str, dest='history', default='history.txt', metavar='log-history', help='File to save game log (history).') parser.add_argument('-o', '--output-file', type=str, dest='output', default='results.xml', metavar='output-file', help='File to save game details (includes history)') args = parser.parse_args() p1, p2 = args.players s = Server(p1, p2, args.delay, args.history, args.output) s.run() s.write_output()
#!/usr/bin/python import os import sys import time import signal import importlib import argparse import subprocess import xml.etree.ElementTree as ET import xml.dom.minidom import board import timer class Server(object): """ Othello server, implements a simple file-based playing protocol """ def __init__(self, p1_dir, p2_dir, delay, history, output): """ Initializes the Othello game server :param p1_dir: directory where the 'agent.py' of the 1st player is located :param p2_dir: directory where the 'agent.py' of the 2nd player is located :param delay: time limit to make a move :param history: file that will contain the match history (plain text) :param output: file to save game details (includes history) """ self.basedir = os.path.abspath('.') self.player_dirs = [p1_dir, p2_dir] self.player_colors = [board.Board.BLACK, board.Board.WHITE] self.color_names = ['black', 'white'] self.board = board.Board() self.history = [] # a list of performed moves (tuple: ((x,y), color) self.history_file = open(history, 'w') self.output_file = output self.delay = delay self.result = None # start and finish times of match self.start = None self.finish = None # imports 'agent.py' from both players self.player_modules = [ importlib.import_module(f"{p1_dir.strip('/')}.agent"), importlib.import_module(f"{p2_dir.strip('/')}.agent"), ] def __del__(self): self.history_file.close() def run(self): self.start = time.localtime() player = 0 illegal_count = [0, 0] # counts the number of illegal move attempts print(f'---- Current match: {self.player_dirs[0]} (B) x {self.player_dirs[1]} (W) ----') print('Initial board:') print(self.board.decorated_str()) while True: # runs until endgame # checks whether players have available moves no_moves_current = len(self.board.legal_moves(self.player_colors[player])) == 0 no_moves_opponent = len(self.board.legal_moves(self.board.opponent(self.player_colors[player]))) == 0 # calculates scores p1_score = sum([1 for char in str(self.board) if char == self.board.BLACK]) p2_score = sum([1 for char in str(self.board) if char == self.board.WHITE]) print(f'---- Current match: {self.player_dirs[0]} (B) x {self.player_dirs[1]} (W) ----') # disqualify player if he attempts illegal moves 5 times in a row if illegal_count[player] >= 5: print(f'Player {player+1} ({self.player_dirs[player]}) DISQUALIFIED! Too many illegal move attempts.') print('End of game reached!') print('Player 1 (B): %d' % p1_score) print('Player 2 (W): %d' % p2_score) self.result = 1 - player self.finish = time.localtime() return self.result # checks whether both players don't have available moves (end of game) if no_moves_current and no_moves_opponent: print('End of game reached! Scores:') print(f'Player 1 (B - {self.player_dirs[0]}): {p1_score}') print(f'Player 2 (W - {self.player_dirs[1]}): {p2_score}') if p1_score > p2_score: print(f'Player 1 (B - {self.player_dirs[0]} wins!') elif p2_score > p1_score: print(f'Player 2 (W - {self.player_dirs[1]}) wins!') else: print('Draw!') self.result = 0 if p1_score > p2_score else 1 if p2_score > p1_score else 2 self.finish = time.localtime() return self.result # if current player has no moves, toggle player and continue if no_moves_current: print(f'Player {player+1} ({self.player_dirs[player]}) has no legal moves and will not play this turn.') illegal_count[player] = 0 player = 1 - player continue # creates a copy of the board, so that player changes won't affect mine board_copy = board.from_string(self.board.__str__()) # calls current player's make_move function with the specified timeout function_call = timer.FunctionTimer(self.player_modules[player].make_move, (board_copy, self.player_colors[player])) move = function_call.run(self.delay) if move is None: # detects timeout print('Player %d has not made a move and lost its turn.' % (player + 1)) player = 1 - player continue move_x, move_y = move # saves move in history self.history_file.write('%d,%d,%s\n' % (move_x, move_y, self.player_colors[player])) self.history.append(((move_x, move_y), self.player_colors[player])) if self.board.process_move((move_x, move_y), self.player_colors[player]): illegal_count[player] = 0 print('Player %d move %d,%d accepted.' % (player + 1, move_x, move_y)) else: illegal_count[player] += 1 print('Player %d move %d,%d ILLEGAL!' % (player + 1,move_x, move_y)) print('Current board:') print(self.board.decorated_str()) # toggle player for next move player = 1 - player def write_output(self): """ Writes a xml file with detailed match data :return: """ os.chdir(self.basedir) root = ET.Element('othello-match') colors = [self.board.BLACK, self.board.WHITE, 'None'] self.player_dirs.append('None') # trick for writing a draw match timing = ET.SubElement(root, 'timing') timing.set('start', time.asctime(self.start)) timing.set('finish', time.asctime(self.finish)) scores = [self.board.piece_count['B'], self.board.piece_count['W']] for idx, p in enumerate(self.player_dirs[:2]): elem = ET.SubElement(root, 'player%d' % (idx + 1)) elem.set('directory', p) elem.set('color', colors[idx]) result = 'win' if scores[idx] > scores[idx - 1] else 'loss' if scores[idx] < scores[idx - 1] else 'draw' elem.set('result', result) elem.set('score', str(scores[idx])) moves = ET.SubElement(root, 'moves') for coords, color in self.history: move = ET.SubElement(moves, 'move') move.set('coord', '%d,%d' % coords) move.set('color', color) # preety xml thanks to: https://stackoverflow.com/a/1206856/1251716 ugly_xml = ET.tostring(root).decode('utf-8') dom = xml.dom.minidom.parseString(ugly_xml) # or xml.dom.minidom.parseString(xml_string) pretty_xml = dom.toprettyxml() f = open(self.output_file, 'w') f.write(pretty_xml) f.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Othello server.') parser.add_argument('players', metavar='player', type=str, nargs=2, help='Path to player directory') parser.add_argument('-d', '--delay', type=float, metavar='delay', default=5.0, help='Time allocated for players to make a move.') parser.add_argument('-l', '--log-history', type=str, dest='history', default='history.txt', metavar='log-history', help='File to save game log (history).') parser.add_argument('-o', '--output-file', type=str, dest='output', default='results.xml', metavar='output-file', help='File to save game details (includes history)') args = parser.parse_args() p1, p2 = args.players s = Server(p1, p2, args.delay, args.history, args.output) s.run() s.write_output()
"""Scans directories for files that satisfy a specific mask and updates version tags of all actions. Example: python3 update_actions.py live.yml action.y*ml folder/*.y*ml """ import argparse import re from pathlib import Path from typing import Dict, List, Optional from github import Github ACTION_PATTERN = r"\s+action:\s*(?P<svc>gh|github):(?P<org>[\w-]+)/(?P<repo>[\w-]+)@(?P<cur_tag>[\w.]+)" # noqa: E501 def main(): args = parse_args() patterns: List[str] = args.patterns token: Optional[str] = args.token if args.root: root = Path(args.root).resolve() else: root = Path(__file__).parent.resolve() update_actions(patterns, root, token) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "patterns", metavar="PATTERN", nargs="+", help="Neuro-flow workflow file, which should be scanned for action updates.", ) parser.add_argument("--token", nargs="?", help="GitHub token to use.") parser.add_argument( "--root", nargs="?", help="Directory, where to start searching for workflow files", ) return parser.parse_args() def update_actions(patterns: List[str], root_dir: Path, gh_token: Optional[str]): github_client = Github(gh_token) action_string_pattern = re.compile(ACTION_PATTERN) # action_file_rel_path: [found_actions, updated_actions] update_stats: Dict[str, List[int, int]] = {} for pattern in patterns: for file_path in root_dir.rglob(pattern): found_actions = 0 updated_actions = 0 new_file_content = [] rel_path = str(file_path.relative_to(root_dir)) for line in file_path.read_text().splitlines(keepends=True): match = action_string_pattern.match(line) if match: found_actions += 1 gh_repo = github_client.get_repo(f"{match["org"]}/{match["repo"]}") current_tag = match["cur_tag"] release_tags = [rel.tag_name for rel in gh_repo.get_releases()] if not release_tags: print(f"No releases found for '{gh_repo.full_name}' action") elif current_tag not in release_tags: print( f"Ignoring '{gh_repo.full_name}' action in '{rel_path}'," " since it is not refferenced by the release tag," f" but by '{current_tag}'." ) else: latest_tag = release_tags[0] if latest_tag != current_tag: updated_actions += 1 line = line.replace(current_tag, latest_tag) new_file_content.append(line) file_path.write_text("".join(new_file_content)) update_stats[rel_path] = [found_actions, updated_actions] pr_body_lines = [ "::set-output name=updated_files::", ] for filename in update_stats: pr_body_lines.append( f"{filename}: found {update_stats[filename][0]} " f"updated {update_stats[filename][1]} actions; " ) # The output afterwards will be used by GH CI to submit a PR. print("".join(pr_body_lines)) if __name__ == "__main__": main()
"""Scans directories for files that satisfy a specific mask and updates version tags of all actions. Example: python3 update_actions.py live.yml action.y*ml folder/*.y*ml """ import argparse import re from pathlib import Path from typing import Dict, List, Optional from github import Github ACTION_PATTERN = r"\s+action:\s*(?P<svc>gh|github):(?P<org>[\w-]+)/(?P<repo>[\w-]+)@(?P<cur_tag>[\w.]+)" # noqa: E501 def main(): args = parse_args() patterns: List[str] = args.patterns token: Optional[str] = args.token if args.root: root = Path(args.root).resolve() else: root = Path(__file__).parent.resolve() update_actions(patterns, root, token) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument( "patterns", metavar="PATTERN", nargs="+", help="Neuro-flow workflow file, which should be scanned for action updates.", ) parser.add_argument("--token", nargs="?", help="GitHub token to use.") parser.add_argument( "--root", nargs="?", help="Directory, where to start searching for workflow files", ) return parser.parse_args() def update_actions(patterns: List[str], root_dir: Path, gh_token: Optional[str]): github_client = Github(gh_token) action_string_pattern = re.compile(ACTION_PATTERN) # action_file_rel_path: [found_actions, updated_actions] update_stats: Dict[str, List[int, int]] = {} for pattern in patterns: for file_path in root_dir.rglob(pattern): found_actions = 0 updated_actions = 0 new_file_content = [] rel_path = str(file_path.relative_to(root_dir)) for line in file_path.read_text().splitlines(keepends=True): match = action_string_pattern.match(line) if match: found_actions += 1 gh_repo = github_client.get_repo(f"{match['org']}/{match['repo']}") current_tag = match["cur_tag"] release_tags = [rel.tag_name for rel in gh_repo.get_releases()] if not release_tags: print(f"No releases found for '{gh_repo.full_name}' action") elif current_tag not in release_tags: print( f"Ignoring '{gh_repo.full_name}' action in '{rel_path}'," " since it is not refferenced by the release tag," f" but by '{current_tag}'." ) else: latest_tag = release_tags[0] if latest_tag != current_tag: updated_actions += 1 line = line.replace(current_tag, latest_tag) new_file_content.append(line) file_path.write_text("".join(new_file_content)) update_stats[rel_path] = [found_actions, updated_actions] pr_body_lines = [ "::set-output name=updated_files::", ] for filename in update_stats: pr_body_lines.append( f"{filename}: found {update_stats[filename][0]} " f"updated {update_stats[filename][1]} actions; " ) # The output afterwards will be used by GH CI to submit a PR. print("".join(pr_body_lines)) if __name__ == "__main__": main()
from pipeline import * def make_index_html(D):# {{{ source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np.array(auth.filter_papers.reshape([-1])[idx]) if FP.size>0: S = [] for i, x in enumerate(FP.reshape([-1])): ck = 'checked' if bool(x) else '' S.append(f'{s1}{str(i+1).zfill(3)}" value="" {ck}{s2}') df['include'] = S else: df['include'] = [] url = [f'{s3}{r}{s4}{t}{s5}' for r, t in zip(df.adsurl, df.Título)] df['linkurl'] = url title_links = df.apply(lambda x: x.linkurl.replace('link', x.Título), axis=1) if FP.size>0: df['title_links'] = title_links else: df['title_links'] = [] df['counter'] = np.arange(1,df.shape[0]+1) dfo = df.iloc[:, [9,3,4,8,6,1,2]].copy() for k in dfo.index: aut = focus_authors(dfo.Autores[k], auth.auth_pos[k]) dfo.at[k, 'Autores'] = aut aff = focus_authors(dfo.Afiliaciones[k], auth.auth_pos[k]) dfo.at[k, 'Afiliaciones'] = aff dfo = dfo.assign(Autores=dfo.Autores.apply(lambda x: '<br>'.join(x))) dfo = dfo.assign(Afiliaciones=dfo.Afiliaciones.apply(lambda x: '<br>'.join(x))) N = df.shape[0] Ni = sum(FP) #--- template str_io = StringIO() dfo.to_html(buf=str_io, index=False, index_names=False, escape=False) html_str = str_io.getvalue() #fname = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(' ', '_')}_{auth.nombre[0]}.html') #fout = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(' ', '_')}_{auth.nombre[0]}.txt') filename = fnames(auth, source_dir, '.html') fout = fnames(auth, source_dir, '.txt', False) target = open(filename, 'w') target.write(template_page.render(N=N, Ni=Ni, html_str=html_str, auth=auth, filedata=fout)) target.close()# }}} def S04_make_pages(D):# {{{ source_dir = '../../models/' template_file = 'template.html' templateLoader = jinja2.FileSystemLoader(searchpath=source_dir) latex_jinja_env = jinja2.Environment( block_start_string=r"\BLOCK{", block_end_string='}', variable_start_string=r'\VAR{', variable_end_string='}', comment_start_string=r'\#{', comment_end_string='}', line_statement_prefix='%%', line_comment_prefix='%#', trim_blocks=True, autoescape=False, loader=templateLoader ) template_page = latex_jinja_env.get_template(template_file) s1 = '<input type="checkbox" name="check' s2 = ' /><br>' s3 = '<a href="' s4 = '">' s5 = '</a>' source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np.array(auth.filter_papers.reshape([-1])[idx]) if FP.size>0: S = [] for i, x in enumerate(FP.reshape([-1])): ck = 'checked' if bool(x) else '' S.append(f'{s1}{str(i+1).zfill(3)}" value="" {ck}{s2}') df['include'] = S else: df['include'] = [] url = [f'{s3}{r}{s4}{t}{s5}' for r, t in zip(df.adsurl, df.Título)] df['linkurl'] = url title_links = df.apply(lambda x: x.linkurl.replace('link', x.Título), axis=1) if FP.size>0: df['title_links'] = title_links else: df['title_links'] = [] df['counter'] = np.arange(1,df.shape[0]+1) dfo = df.iloc[:, [9,3,4,8,6,1,2]].copy() for k in dfo.index: aut = focus_authors(dfo.Autores[k], auth.auth_pos[k]) dfo.at[k, 'Autores'] = aut aff = focus_authors(dfo.Afiliaciones[k], auth.auth_pos[k]) dfo.at[k, 'Afiliaciones'] = aff dfo = dfo.assign(Autores=dfo.Autores.apply(lambda x: '<br>'.join(x))) dfo = dfo.assign(Afiliaciones=dfo.Afiliaciones.apply(lambda x: '<br>'.join(x))) N = df.shape[0] Ni = sum(FP) #--- template str_io = StringIO() dfo.to_html(buf=str_io, index=False, index_names=False, escape=False) html_str = str_io.getvalue() #fname = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(' ', '_')}_{auth.nombre[0]}.html') #fout = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(' ', '_')}_{auth.nombre[0]}.txt') filename = fnames(auth, source_dir, '.html') fout = fnames(auth, source_dir, '.txt', False) target = open(filename, 'w') target.write(template_page.render(N=N, Ni=Ni, html_str=html_str, auth=auth, filedata=fout)) target.close()# }}} # read authors with open('../../data/redux/astrogen_DB_labelled.pk', 'rb') as f: D = pickle.load(f) # select authors conn = sqlite3.connect('../../data/redux/astrogen_DB_labelled.db') script = """ select *, COUNT(*) as cc, MAX(p.year) as ymx, SUM(CASE WHEN p.inar=1 then 1 else 0 END) as N_inar, SUM(CASE WHEN p.inar=1 then 1 else 0 END) / (1.*COUNT(*)) as q FROM papers as p INNER JOIN people as g WHERE p.ID==g.ID AND g.yob BETWEEN 1951 AND 2001 AND p.journal_Q==1 AND p.author_count<51 GROUP BY p.ID HAVING ymx>2016 AND q>0.75 """ sql_query = pd.read_sql_query (script, conn) df = pd.DataFrame(sql_query) conn.close() ids = df.ID.values[:,0] ids = np.random.permutation(ids) ddf = D.iloc[ids, :] D = S04_load_check_filters(ddf); ddf = next(D) S04_make_pages(ddf) # make index page source_dir = '../../models/' target_dir = './' template_file = 'template_list.html' templateLoader = jinja2.FileSystemLoader(searchpath=source_dir) latex_jinja_env = jinja2.Environment( block_start_string=r"\BLOCK{", block_end_string='}', variable_start_string=r'\VAR{', variable_end_string='}', comment_start_string=r'\#{', comment_end_string='}', line_statement_prefix='%%', line_comment_prefix='%#', trim_blocks=True, autoescape=False, loader=templateLoader ) template_page = latex_jinja_env.get_template(template_file) htmlfilename, authname, authobj = [], [], [] for i in ddf.index: auth = ddf.loc[i] filename = fnames(auth, target_dir, '.html') htmlfilename.append(filename) authname.append(f'{auth.apellido}, {auth.nombre}') authobj.append(auth) lst = zip(htmlfilename, authname, authobj) filename = '../../data/interim/htmls/index.html' target = open(filename, 'w') target.write(template_page.render(lst=lst)) target.close()
from pipeline import * def make_index_html(D):# {{{ source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np.array(auth.filter_papers.reshape([-1])[idx]) if FP.size>0: S = [] for i, x in enumerate(FP.reshape([-1])): ck = 'checked' if bool(x) else '' S.append(f'{s1}{str(i+1).zfill(3)}" value="" {ck}{s2}') df['include'] = S else: df['include'] = [] url = [f'{s3}{r}{s4}{t}{s5}' for r, t in zip(df.adsurl, df.Título)] df['linkurl'] = url title_links = df.apply(lambda x: x.linkurl.replace('link', x.Título), axis=1) if FP.size>0: df['title_links'] = title_links else: df['title_links'] = [] df['counter'] = np.arange(1,df.shape[0]+1) dfo = df.iloc[:, [9,3,4,8,6,1,2]].copy() for k in dfo.index: aut = focus_authors(dfo.Autores[k], auth.auth_pos[k]) dfo.at[k, 'Autores'] = aut aff = focus_authors(dfo.Afiliaciones[k], auth.auth_pos[k]) dfo.at[k, 'Afiliaciones'] = aff dfo = dfo.assign(Autores=dfo.Autores.apply(lambda x: '<br>'.join(x))) dfo = dfo.assign(Afiliaciones=dfo.Afiliaciones.apply(lambda x: '<br>'.join(x))) N = df.shape[0] Ni = sum(FP) #--- template str_io = StringIO() dfo.to_html(buf=str_io, index=False, index_names=False, escape=False) html_str = str_io.getvalue() #fname = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(" ", "_")}_{auth.nombre[0]}.html') #fout = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(" ", "_")}_{auth.nombre[0]}.txt') filename = fnames(auth, source_dir, '.html') fout = fnames(auth, source_dir, '.txt', False) target = open(filename, 'w') target.write(template_page.render(N=N, Ni=Ni, html_str=html_str, auth=auth, filedata=fout)) target.close()# }}} def S04_make_pages(D):# {{{ source_dir = '../../models/' template_file = 'template.html' templateLoader = jinja2.FileSystemLoader(searchpath=source_dir) latex_jinja_env = jinja2.Environment( block_start_string=r"\BLOCK{", block_end_string='}', variable_start_string=r'\VAR{', variable_end_string='}', comment_start_string=r'\#{', comment_end_string='}', line_statement_prefix='%%', line_comment_prefix='%#', trim_blocks=True, autoescape=False, loader=templateLoader ) template_page = latex_jinja_env.get_template(template_file) s1 = '<input type="checkbox" name="check' s2 = ' /><br>' s3 = '<a href="' s4 = '">' s5 = '</a>' source_dir = '../../data/interim/htmls/' for i in tqdm(D.index): auth = D.loc[i] papers = get_papers_from_df(auth) df = gen_spreadsheet(auth, papers) idx = np.argsort(df.Año.values) df = df.loc[idx, :] FP = np.array(auth.filter_papers.reshape([-1])[idx]) if FP.size>0: S = [] for i, x in enumerate(FP.reshape([-1])): ck = 'checked' if bool(x) else '' S.append(f'{s1}{str(i+1).zfill(3)}" value="" {ck}{s2}') df['include'] = S else: df['include'] = [] url = [f'{s3}{r}{s4}{t}{s5}' for r, t in zip(df.adsurl, df.Título)] df['linkurl'] = url title_links = df.apply(lambda x: x.linkurl.replace('link', x.Título), axis=1) if FP.size>0: df['title_links'] = title_links else: df['title_links'] = [] df['counter'] = np.arange(1,df.shape[0]+1) dfo = df.iloc[:, [9,3,4,8,6,1,2]].copy() for k in dfo.index: aut = focus_authors(dfo.Autores[k], auth.auth_pos[k]) dfo.at[k, 'Autores'] = aut aff = focus_authors(dfo.Afiliaciones[k], auth.auth_pos[k]) dfo.at[k, 'Afiliaciones'] = aff dfo = dfo.assign(Autores=dfo.Autores.apply(lambda x: '<br>'.join(x))) dfo = dfo.assign(Afiliaciones=dfo.Afiliaciones.apply(lambda x: '<br>'.join(x))) N = df.shape[0] Ni = sum(FP) #--- template str_io = StringIO() dfo.to_html(buf=str_io, index=False, index_names=False, escape=False) html_str = str_io.getvalue() #fname = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(" ", "_")}_{auth.nombre[0]}.html') #fout = (f'{str(i).zfill(3)}_' # f'{auth.apellido.replace(" ", "_")}_{auth.nombre[0]}.txt') filename = fnames(auth, source_dir, '.html') fout = fnames(auth, source_dir, '.txt', False) target = open(filename, 'w') target.write(template_page.render(N=N, Ni=Ni, html_str=html_str, auth=auth, filedata=fout)) target.close()# }}} # read authors with open('../../data/redux/astrogen_DB_labelled.pk', 'rb') as f: D = pickle.load(f) # select authors conn = sqlite3.connect('../../data/redux/astrogen_DB_labelled.db') script = """ select *, COUNT(*) as cc, MAX(p.year) as ymx, SUM(CASE WHEN p.inar=1 then 1 else 0 END) as N_inar, SUM(CASE WHEN p.inar=1 then 1 else 0 END) / (1.*COUNT(*)) as q FROM papers as p INNER JOIN people as g WHERE p.ID==g.ID AND g.yob BETWEEN 1951 AND 2001 AND p.journal_Q==1 AND p.author_count<51 GROUP BY p.ID HAVING ymx>2016 AND q>0.75 """ sql_query = pd.read_sql_query (script, conn) df = pd.DataFrame(sql_query) conn.close() ids = df.ID.values[:,0] ids = np.random.permutation(ids) ddf = D.iloc[ids, :] D = S04_load_check_filters(ddf); ddf = next(D) S04_make_pages(ddf) # make index page source_dir = '../../models/' target_dir = './' template_file = 'template_list.html' templateLoader = jinja2.FileSystemLoader(searchpath=source_dir) latex_jinja_env = jinja2.Environment( block_start_string=r"\BLOCK{", block_end_string='}', variable_start_string=r'\VAR{', variable_end_string='}', comment_start_string=r'\#{', comment_end_string='}', line_statement_prefix='%%', line_comment_prefix='%#', trim_blocks=True, autoescape=False, loader=templateLoader ) template_page = latex_jinja_env.get_template(template_file) htmlfilename, authname, authobj = [], [], [] for i in ddf.index: auth = ddf.loc[i] filename = fnames(auth, target_dir, '.html') htmlfilename.append(filename) authname.append(f'{auth.apellido}, {auth.nombre}') authobj.append(auth) lst = zip(htmlfilename, authname, authobj) filename = '../../data/interim/htmls/index.html' target = open(filename, 'w') target.write(template_page.render(lst=lst)) target.close()
# SPDX-License-Identifier: MIT import itertools, fnmatch from construct import * from .utils import AddrLookup, FourCC, SafeGreedyRange __all__ = ["load_adt"] ADTPropertyStruct = Struct( "name" / PaddedString(32, "ascii"), "size" / Int32ul, "value" / Bytes(this.size & 0x7fffffff) ) ADTNodeStruct = Struct( "property_count" / Int32ul, "child_count" / Int32ul, "properties" / Array(this.property_count, Aligned(4, ADTPropertyStruct)), "children" / Array(this.child_count, LazyBound(lambda: ADTNodeStruct)) ) ADTStringList = SafeGreedyRange(CString("ascii")) ADT2Tuple = Array(2, Hex(Int64ul)) ADT3Tuple = Array(3, Hex(Int64ul)) Function = Struct( "phandle" / Int32ul, "name" / FourCC, "args" / SafeGreedyRange(Int32ul), ) STD_PROPERTIES = { "cpu-impl-reg": ADT2Tuple, "name": CString("ascii"), "compatible": ADTStringList, "model": CString("ascii"), "#size-cells": Int32ul, "#address-cells": Int32ul, "clock-ids": SafeGreedyRange(Int32ul), "clock-gates": SafeGreedyRange(Int32ul), "power-gates": SafeGreedyRange(Int32ul), } PMAPIORanges = SafeGreedyRange(Struct( "addr" / Hex(Int64ul), "size" / Hex(Int64ul), "flags" / Hex(Int32ul), "name" / FourCC, )) PMGRPSRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), )) PMGRPWRGateRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), "unk" / Hex(Int32ul), )) PMGRDevices = SafeGreedyRange(Struct( "flags" / Int8ul, "unk1_0" / Int8ul, "unk1_1" / Int8ul, "unk1_2" / Int8ul, "parents" / Array(2, Int16ul), "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "psidx" / Int8ul, "psreg" / Int8ul, "unk2_0" / Int16ul, "pd" / Int8ul, "ps_cfg16" / Int8ul, Const(0, Int32ul), Const(0, Int32ul), "unk2_3" / Int16ul, "id" / Int16ul, "unk3" / Int32ul, "name" / PaddedString(16, "ascii") )) PMGRClocks = SafeGreedyRange(Struct( "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "unk" / Int8ul, "id" / Int8ul, Const(0, Int32ul), "name" / PaddedString(16, "ascii"), )) PMGRPowerDomains = SafeGreedyRange(Struct( "unk" / Const(0, Int8ul), "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "id" / Int8ul, Const(0, Int32ul), "name" / PaddedString(16, "ascii"), )) PMGRDeviceBridges = SafeGreedyRange(Struct( "idx" / Int32ub, "subdevs" / HexDump(Bytes(0x48)), )) PMGREvents = SafeGreedyRange(Struct( "unk1" / Int8ul, "unk2" / Int8ul, "unk3" / Int8ul, "id" / Int8ul, "ctl2_idx" / Int8ul, "ctl2_block" / Int8ul, "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "name" / PaddedString(16, "ascii"), )) DEV_PROPERTIES = { "pmgr": { "*": { "clusters": SafeGreedyRange(Int32ul), "devices": PMGRDevices, "ps-regs": PMGRPSRegs, "pwrgate-regs": PMGRPWRGateRegs, "power-domains": PMGRPowerDomains, "clocks": PMGRClocks, "device-bridges": PMGRDeviceBridges, "voltage-states*": SafeGreedyRange(Int32ul), "events": PMGREvents, } }, "clpc": { "*": { "events": SafeGreedyRange(Int32ul), "devices": SafeGreedyRange(Int32ul), } }, "soc-tuner": { "*": { "device-set-*": SafeGreedyRange(Int32ul), "mcc-configs": SafeGreedyRange(Int32ul), } }, "mcc": { "*": { "dramcfg-data": SafeGreedyRange(Int32ul), "config-data": SafeGreedyRange(Int32ul), } }, "stockholm-spmi": { "*": { "required-functions": ADTStringList, }, }, "arm-io": { "*": { "clock-frequencies": SafeGreedyRange(Int32ul), "clock-frequencies-regs": SafeGreedyRange(Hex(Int64ul)), "clock-frequencies-nclk": SafeGreedyRange(Int32ul), }, }, "defaults": { "*": { "pmap-io-ranges": PMAPIORanges, } } } def parse_prop(node, path, node_name, name, v, is_template=False): t = None if is_template: t = CString("ascii") dev_props = DEV_PROPERTIES.get(path, DEV_PROPERTIES.get(node_name, None)) possible_match = False if dev_props: for compat_match, cprops in dev_props.items(): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): possible_match = True break if possible_match: try: compat = node.compatible[0] except AttributeError: compat = "" for compat_match, cprops in dev_props.items(): if fnmatch.fnmatch(compat, compat_match): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): t = pt break else: continue break if v == b'' or v is None: return None, None if name.startswith("function-"): if len(v) == 4: t = FourCC else: t = Function if name == "reg" and path != "/device-tree/memory": n = node._parent while n is not None and n._parent is not None: if "ranges" not in n._properties: break n = n._parent else: ac, sc = node._parent.address_cells, node._parent.size_cells at = Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)) st = Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) t = SafeGreedyRange(Struct("addr" / at, "size" / st)) if len(v) % ((ac + sc) * 4): t = None elif name == "ranges": try: ac, sc = node.address_cells, node.size_cells except AttributeError: return None, v pac, _ = node._parent.address_cells, node._parent.size_cells at = Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)) pat = Hex(Int64ul) if pac == 2 else Array(pac, Hex(Int32ul)) st = Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) t = SafeGreedyRange(Struct("bus_addr" / at, "parent_addr" / pat, "size" / st)) elif name == "interrupts": # parse "interrupts" as Array of Int32ul, wrong for nodes whose # "interrupt-parent" has "interrupt-cells" = 2 # parsing this correctly would require a second pass t = Array(len(v) // 4, Int32ul) if t is not None: v = Sequence(t, Terminated).parse(v)[0] return t, v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif v and v[-1] == 0 and all(0x20 <= i <= 0x7e for i in v[:-1]): t = CString("ascii") elif len(v) == 4: t = Int32ul elif len(v) == 8: t = Int64ul elif len(v) == 16 and all(v[i] == 0 for i in (6, 7, 14, 15)): t = ADT2Tuple if t is not None: try: v = Sequence(t, Terminated).parse(v)[0] except: print("Failed to parse:", path, name, v.hex()) raise return t, v def build_prop(path, name, v, t=None): if v is None: return b'' if t is not None: return t.build(v) if isinstance(v, bytes): return v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif isinstance(v, str): t = CString("ascii") elif isinstance(v, int): t = Int32ul elif isinstance(v, tuple) and all(isinstance(i, int) for i in v): t = Array(len(v), Int32ul) return t.build(v) class ADTNode: def __init__(self, val=None, path="/", parent=None): self._children = [] self._properties = {} self._types = {} self._parent_path = path self._parent = parent if val is not None: for p in val.properties: if p.name == "name": _name = p.value.decode("ascii").rstrip("\0") break else: raise ValueError(f"Node in {path} has no name!") path = self._parent_path + _name for p in val.properties: is_template = bool(p.size & 0x80000000) try: t, v = parse_prop(self, path, _name, p.name, p.value, is_template) self._types[p.name] = t, is_template self._properties[p.name] = v except Exception as e: print(f"Exception parsing {path}.{p.name} value {p.value.hex()}:", file=sys.stderr) raise # Second pass for k, (t, is_template) in self._types.items(): if t is None: t, v = parse_prop(self, path, _name, k, self._properties[k], is_template) self._types[k] = t, is_template self._properties[k] = v for c in val.children: node = ADTNode(c, f"{self._path}/", parent=self) self._children.append(node) @property def _path(self): return self._parent_path + self.name def __getitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) return self[a][b] for i in self._children: if i.name == item: return i raise KeyError(f"Child node '{item}' not found") return self._children[item] def __setitem__(self, item, value): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) self[a][b] = value return for i, c in enumerate(self._children): if c.name == item: self._children[i] = value break else: self._children.append(value) else: self._children[item] = value def __delitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) del self[a][b] return for i, c in enumerate(self._children): if c.name == item: del self._children[i] return raise KeyError(f"Child node '{item}' not found") del self._children[item] def __getattr__(self, attr): attr = attr.replace("_", "-") if attr in self._properties: return self._properties[attr] raise AttributeError(attr) def __setattr__(self, attr, value): if attr[0] == "_": self.__dict__[attr] = value return attr = attr.replace("_", "-") self._properties[attr] = value def __delattr__(self, attr): if attr[0] == "_": del self.__dict__[attr] return del self._properties[attr] @property def address_cells(self): try: return self._properties["#address-cells"] except KeyError: raise AttributeError("#address-cells") @property def size_cells(self): try: return self._properties["#size-cells"] except KeyError: raise AttributeError("#size-cells") @property def interrupt_cells(self): try: return self._properties["#interrupt-cells"] except KeyError: raise AttributeError("#interrupt-cells") def _fmt_prop(self, k, v): t, is_template = self._types[k] if is_template: return f"<< {v} >>" elif isinstance(v, ListContainer): return f"[{", ".join(self._fmt_prop(k, i) for i in v)}]" elif isinstance(v, bytes): if all(i == 0 for i in v): return f"zeroes({len(v):#x})" else: return v.hex() elif k.startswith("function-"): if isinstance(v, str): return f"{v}()" elif v is None: return f"None" else: args = [] for arg in v.args: b = arg.to_bytes(4, "big") is_ascii = all(0x20 <= c <= 0x7e for c in b) args.append(f"{arg:#x}" if not is_ascii else f""{b.decode("ascii")}'") return f"{v.phandle}:{v.name}({", ".join(args)})" name.startswith("function-") else: return str(v) def __str__(self, t=""): return "\n".join([ t + f"{self.name} {{", *(t + f" {k} = {self._fmt_prop(k, v)}" for k, v in self._properties.items() if k != "name"), "", *(i.__str__(t + " ") for i in self._children), t + "}" ]) def __repr__(self): return f"<ADTNode {self.name}>" def __iter__(self): return iter(self._children) def get_reg(self, idx): reg = self.reg[idx] addr = reg.addr size = reg.size node = self._parent while node is not None: if "ranges" not in node._properties: break for r in node.ranges: if r.bus_addr <= addr < (r.bus_addr + r.size): addr = addr - r.bus_addr + r.parent_addr break node = node._parent return addr, size def tostruct(self): properties = [] for k,v in itertools.chain(self._properties.items()): t, is_template = self._types.get(k, (None, False)) value = build_prop(self._path, k, v, t=t) properties.append({ "name": k, "size": len(value) | (0x80000000 if is_template else 0), "value": value }) data = { "property_count": len(self._properties), "child_count": len(self._children), "properties": properties, "children": [c.tostruct() for c in self._children] } return data def build(self): return ADTNodeStruct.build(self.tostruct()) def walk_tree(self): yield self for child in self: yield from child def build_addr_lookup(self): lookup = AddrLookup() for node in self.walk_tree(): reg = getattr(node, 'reg', None) if not isinstance(reg, list): continue for index in range(len(reg)): try: addr, size = node.get_reg(index) except AttributeError: continue if size == 0: continue lookup.add(range(addr, addr + size), node.name + f"[{index}]") return lookup def load_adt(data): return ADTNode(ADTNodeStruct.parse(data)) if __name__ == "__main__": import sys, argparse, pathlib parser = argparse.ArgumentParser(description='ADT test for m1n1') parser.add_argument('input', type=pathlib.Path) parser.add_argument('output', nargs='?', type=pathlib.Path) parser.add_argument('-r', '--retrieve', help='retrieve and store the adt from m1n1', action='store_true') parser.add_argument('-a', '--dump-addr', help='dump address lookup table', action='store_true') args = parser.parse_args() if args.retrieve: if args.input.exists(): print('Error "{}" exists!'.format(args.input)) sys.exit() from .setup import * adt_data = u.get_adt() args.input.write_bytes(adt_data) else: adt_data = args.input.read_bytes() adt = load_adt(adt_data) print(adt) new_data = adt.build() if args.output is not None: args.output.write_bytes(new_data) assert new_data == adt_data[:len(new_data)] assert adt_data[len(new_data):] == bytes(len(adt_data) - len(new_data)) if args.dump_addr: print("Address lookup table:") print(adt.build_addr_lookup())
# SPDX-License-Identifier: MIT import itertools, fnmatch from construct import * from .utils import AddrLookup, FourCC, SafeGreedyRange __all__ = ["load_adt"] ADTPropertyStruct = Struct( "name" / PaddedString(32, "ascii"), "size" / Int32ul, "value" / Bytes(this.size & 0x7fffffff) ) ADTNodeStruct = Struct( "property_count" / Int32ul, "child_count" / Int32ul, "properties" / Array(this.property_count, Aligned(4, ADTPropertyStruct)), "children" / Array(this.child_count, LazyBound(lambda: ADTNodeStruct)) ) ADTStringList = SafeGreedyRange(CString("ascii")) ADT2Tuple = Array(2, Hex(Int64ul)) ADT3Tuple = Array(3, Hex(Int64ul)) Function = Struct( "phandle" / Int32ul, "name" / FourCC, "args" / SafeGreedyRange(Int32ul), ) STD_PROPERTIES = { "cpu-impl-reg": ADT2Tuple, "name": CString("ascii"), "compatible": ADTStringList, "model": CString("ascii"), "#size-cells": Int32ul, "#address-cells": Int32ul, "clock-ids": SafeGreedyRange(Int32ul), "clock-gates": SafeGreedyRange(Int32ul), "power-gates": SafeGreedyRange(Int32ul), } PMAPIORanges = SafeGreedyRange(Struct( "addr" / Hex(Int64ul), "size" / Hex(Int64ul), "flags" / Hex(Int32ul), "name" / FourCC, )) PMGRPSRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), )) PMGRPWRGateRegs = SafeGreedyRange(Struct( "reg" / Int32ul, "offset" / Hex(Int32ul), "mask" / Hex(Int32ul), "unk" / Hex(Int32ul), )) PMGRDevices = SafeGreedyRange(Struct( "flags" / Int8ul, "unk1_0" / Int8ul, "unk1_1" / Int8ul, "unk1_2" / Int8ul, "parents" / Array(2, Int16ul), "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "psidx" / Int8ul, "psreg" / Int8ul, "unk2_0" / Int16ul, "pd" / Int8ul, "ps_cfg16" / Int8ul, Const(0, Int32ul), Const(0, Int32ul), "unk2_3" / Int16ul, "id" / Int16ul, "unk3" / Int32ul, "name" / PaddedString(16, "ascii") )) PMGRClocks = SafeGreedyRange(Struct( "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "unk" / Int8ul, "id" / Int8ul, Const(0, Int32ul), "name" / PaddedString(16, "ascii"), )) PMGRPowerDomains = SafeGreedyRange(Struct( "unk" / Const(0, Int8ul), "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "id" / Int8ul, Const(0, Int32ul), "name" / PaddedString(16, "ascii"), )) PMGRDeviceBridges = SafeGreedyRange(Struct( "idx" / Int32ub, "subdevs" / HexDump(Bytes(0x48)), )) PMGREvents = SafeGreedyRange(Struct( "unk1" / Int8ul, "unk2" / Int8ul, "unk3" / Int8ul, "id" / Int8ul, "ctl2_idx" / Int8ul, "ctl2_block" / Int8ul, "ctl_idx" / Int8ul, "ctl_block" / Int8ul, "name" / PaddedString(16, "ascii"), )) DEV_PROPERTIES = { "pmgr": { "*": { "clusters": SafeGreedyRange(Int32ul), "devices": PMGRDevices, "ps-regs": PMGRPSRegs, "pwrgate-regs": PMGRPWRGateRegs, "power-domains": PMGRPowerDomains, "clocks": PMGRClocks, "device-bridges": PMGRDeviceBridges, "voltage-states*": SafeGreedyRange(Int32ul), "events": PMGREvents, } }, "clpc": { "*": { "events": SafeGreedyRange(Int32ul), "devices": SafeGreedyRange(Int32ul), } }, "soc-tuner": { "*": { "device-set-*": SafeGreedyRange(Int32ul), "mcc-configs": SafeGreedyRange(Int32ul), } }, "mcc": { "*": { "dramcfg-data": SafeGreedyRange(Int32ul), "config-data": SafeGreedyRange(Int32ul), } }, "stockholm-spmi": { "*": { "required-functions": ADTStringList, }, }, "arm-io": { "*": { "clock-frequencies": SafeGreedyRange(Int32ul), "clock-frequencies-regs": SafeGreedyRange(Hex(Int64ul)), "clock-frequencies-nclk": SafeGreedyRange(Int32ul), }, }, "defaults": { "*": { "pmap-io-ranges": PMAPIORanges, } } } def parse_prop(node, path, node_name, name, v, is_template=False): t = None if is_template: t = CString("ascii") dev_props = DEV_PROPERTIES.get(path, DEV_PROPERTIES.get(node_name, None)) possible_match = False if dev_props: for compat_match, cprops in dev_props.items(): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): possible_match = True break if possible_match: try: compat = node.compatible[0] except AttributeError: compat = "" for compat_match, cprops in dev_props.items(): if fnmatch.fnmatch(compat, compat_match): for k, pt in cprops.items(): if fnmatch.fnmatch(name, k): t = pt break else: continue break if v == b'' or v is None: return None, None if name.startswith("function-"): if len(v) == 4: t = FourCC else: t = Function if name == "reg" and path != "/device-tree/memory": n = node._parent while n is not None and n._parent is not None: if "ranges" not in n._properties: break n = n._parent else: ac, sc = node._parent.address_cells, node._parent.size_cells at = Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)) st = Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) t = SafeGreedyRange(Struct("addr" / at, "size" / st)) if len(v) % ((ac + sc) * 4): t = None elif name == "ranges": try: ac, sc = node.address_cells, node.size_cells except AttributeError: return None, v pac, _ = node._parent.address_cells, node._parent.size_cells at = Hex(Int64ul) if ac == 2 else Array(ac, Hex(Int32ul)) pat = Hex(Int64ul) if pac == 2 else Array(pac, Hex(Int32ul)) st = Hex(Int64ul) if sc == 2 else Array(sc, Hex(Int32ul)) t = SafeGreedyRange(Struct("bus_addr" / at, "parent_addr" / pat, "size" / st)) elif name == "interrupts": # parse "interrupts" as Array of Int32ul, wrong for nodes whose # "interrupt-parent" has "interrupt-cells" = 2 # parsing this correctly would require a second pass t = Array(len(v) // 4, Int32ul) if t is not None: v = Sequence(t, Terminated).parse(v)[0] return t, v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif v and v[-1] == 0 and all(0x20 <= i <= 0x7e for i in v[:-1]): t = CString("ascii") elif len(v) == 4: t = Int32ul elif len(v) == 8: t = Int64ul elif len(v) == 16 and all(v[i] == 0 for i in (6, 7, 14, 15)): t = ADT2Tuple if t is not None: try: v = Sequence(t, Terminated).parse(v)[0] except: print("Failed to parse:", path, name, v.hex()) raise return t, v def build_prop(path, name, v, t=None): if v is None: return b'' if t is not None: return t.build(v) if isinstance(v, bytes): return v if name in STD_PROPERTIES: t = STD_PROPERTIES[name] elif isinstance(v, str): t = CString("ascii") elif isinstance(v, int): t = Int32ul elif isinstance(v, tuple) and all(isinstance(i, int) for i in v): t = Array(len(v), Int32ul) return t.build(v) class ADTNode: def __init__(self, val=None, path="/", parent=None): self._children = [] self._properties = {} self._types = {} self._parent_path = path self._parent = parent if val is not None: for p in val.properties: if p.name == "name": _name = p.value.decode("ascii").rstrip("\0") break else: raise ValueError(f"Node in {path} has no name!") path = self._parent_path + _name for p in val.properties: is_template = bool(p.size & 0x80000000) try: t, v = parse_prop(self, path, _name, p.name, p.value, is_template) self._types[p.name] = t, is_template self._properties[p.name] = v except Exception as e: print(f"Exception parsing {path}.{p.name} value {p.value.hex()}:", file=sys.stderr) raise # Second pass for k, (t, is_template) in self._types.items(): if t is None: t, v = parse_prop(self, path, _name, k, self._properties[k], is_template) self._types[k] = t, is_template self._properties[k] = v for c in val.children: node = ADTNode(c, f"{self._path}/", parent=self) self._children.append(node) @property def _path(self): return self._parent_path + self.name def __getitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) return self[a][b] for i in self._children: if i.name == item: return i raise KeyError(f"Child node '{item}' not found") return self._children[item] def __setitem__(self, item, value): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) self[a][b] = value return for i, c in enumerate(self._children): if c.name == item: self._children[i] = value break else: self._children.append(value) else: self._children[item] = value def __delitem__(self, item): if isinstance(item, str): while item.startswith("/"): item = item[1:] if "/" in item: a, b = item.split("/", 1) del self[a][b] return for i, c in enumerate(self._children): if c.name == item: del self._children[i] return raise KeyError(f"Child node '{item}' not found") del self._children[item] def __getattr__(self, attr): attr = attr.replace("_", "-") if attr in self._properties: return self._properties[attr] raise AttributeError(attr) def __setattr__(self, attr, value): if attr[0] == "_": self.__dict__[attr] = value return attr = attr.replace("_", "-") self._properties[attr] = value def __delattr__(self, attr): if attr[0] == "_": del self.__dict__[attr] return del self._properties[attr] @property def address_cells(self): try: return self._properties["#address-cells"] except KeyError: raise AttributeError("#address-cells") @property def size_cells(self): try: return self._properties["#size-cells"] except KeyError: raise AttributeError("#size-cells") @property def interrupt_cells(self): try: return self._properties["#interrupt-cells"] except KeyError: raise AttributeError("#interrupt-cells") def _fmt_prop(self, k, v): t, is_template = self._types[k] if is_template: return f"<< {v} >>" elif isinstance(v, ListContainer): return f"[{', '.join(self._fmt_prop(k, i) for i in v)}]" elif isinstance(v, bytes): if all(i == 0 for i in v): return f"zeroes({len(v):#x})" else: return v.hex() elif k.startswith("function-"): if isinstance(v, str): return f"{v}()" elif v is None: return f"None" else: args = [] for arg in v.args: b = arg.to_bytes(4, "big") is_ascii = all(0x20 <= c <= 0x7e for c in b) args.append(f"{arg:#x}" if not is_ascii else f"'{b.decode('ascii')}'") return f"{v.phandle}:{v.name}({', '.join(args)})" name.startswith("function-") else: return str(v) def __str__(self, t=""): return "\n".join([ t + f"{self.name} {{", *(t + f" {k} = {self._fmt_prop(k, v)}" for k, v in self._properties.items() if k != "name"), "", *(i.__str__(t + " ") for i in self._children), t + "}" ]) def __repr__(self): return f"<ADTNode {self.name}>" def __iter__(self): return iter(self._children) def get_reg(self, idx): reg = self.reg[idx] addr = reg.addr size = reg.size node = self._parent while node is not None: if "ranges" not in node._properties: break for r in node.ranges: if r.bus_addr <= addr < (r.bus_addr + r.size): addr = addr - r.bus_addr + r.parent_addr break node = node._parent return addr, size def tostruct(self): properties = [] for k,v in itertools.chain(self._properties.items()): t, is_template = self._types.get(k, (None, False)) value = build_prop(self._path, k, v, t=t) properties.append({ "name": k, "size": len(value) | (0x80000000 if is_template else 0), "value": value }) data = { "property_count": len(self._properties), "child_count": len(self._children), "properties": properties, "children": [c.tostruct() for c in self._children] } return data def build(self): return ADTNodeStruct.build(self.tostruct()) def walk_tree(self): yield self for child in self: yield from child def build_addr_lookup(self): lookup = AddrLookup() for node in self.walk_tree(): reg = getattr(node, 'reg', None) if not isinstance(reg, list): continue for index in range(len(reg)): try: addr, size = node.get_reg(index) except AttributeError: continue if size == 0: continue lookup.add(range(addr, addr + size), node.name + f"[{index}]") return lookup def load_adt(data): return ADTNode(ADTNodeStruct.parse(data)) if __name__ == "__main__": import sys, argparse, pathlib parser = argparse.ArgumentParser(description='ADT test for m1n1') parser.add_argument('input', type=pathlib.Path) parser.add_argument('output', nargs='?', type=pathlib.Path) parser.add_argument('-r', '--retrieve', help='retrieve and store the adt from m1n1', action='store_true') parser.add_argument('-a', '--dump-addr', help='dump address lookup table', action='store_true') args = parser.parse_args() if args.retrieve: if args.input.exists(): print('Error "{}" exists!'.format(args.input)) sys.exit() from .setup import * adt_data = u.get_adt() args.input.write_bytes(adt_data) else: adt_data = args.input.read_bytes() adt = load_adt(adt_data) print(adt) new_data = adt.build() if args.output is not None: args.output.write_bytes(new_data) assert new_data == adt_data[:len(new_data)] assert adt_data[len(new_data):] == bytes(len(adt_data) - len(new_data)) if args.dump_addr: print("Address lookup table:") print(adt.build_addr_lookup())
#Import Libraries #Web Scraping tools from bs4 import BeautifulSoup as bs from selenium import webdriver #from splinter import Browser #DataFrame tools import pandas as pd #Misc tools for web scraping import time import requests #Function to initianilze browser. def init_browser(): #Settings for headless mode. options = webdriver.ChromeOptions() options.add_argument('headless') #Splinter option - using absolute path #executable_path = {'executable_path': '/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver'} #browser = Browser('chrome', **executable_path, headless = True) #path to the driver and load the options. browser = webdriver.Chrome("/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver",chrome_options = options) #returns the brower. return browser def scrapper(): #Call browser function browser = init_browser() #Dictionary to store all the results. marsInfo_dict = {} #Code to get NASA Mars News ---------------------------------------------------------------------------------------------- try: url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&year=2020%3Apublish_date&category=19%2C165%2C184%2C204&blank_scope=Latest" #splinter option - open url #browser.visit(url) #Open url. browser.get(url) #Time to let the website load all the elements time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") #Collect the latest news title news_title = soup.find_all('li', class_="slide")[0].find(class_="content_title").text news_p = soup.find_all('li', class_="slide")[0].text marsInfo_dict['news_title'] = news_title marsInfo_dict['news_p'] = news_p except : print(f"Problem at website {url}") #Code to get JPL Mars Space Images - Featured Image --------------------------------------------------------------------------------- try: url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" #splinter option - open url #browser.visit(url) #Opens the url. browser.get(url) #splinter option - FULL IMAGE BUTTON #browser.click_link_by_id("full_image") #Interact with the FULL IMAGE BUTTON browser.find_element_by_id("full_image").click() time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") featured_image_url = "https://www.jpl.nasa.gov/" + soup.find_all('img', class_="fancybox-image")[0]['src'] marsInfo_dict['featured_image_url'] = featured_image_url except : print(f"Problem at website {url}") #Mars Weather ------------------------------------------------------------------------------------------------------------------------ try: url = "https://twitter.com/marswxreport?lang=en" #splinter option - open url #browser.visit(url) #Open the url. browser.get(url) #Time to let the website load all the elements time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") mars_weather = soup.find_all('article', class_="css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-o7ynqc r-6416eg")[0].text.strip().replace('Mars Weather@MarsWxReport·19hInSight ','') marsInfo_dict['mars_weather'] = mars_weather except : print(mars_weather) print(f"Problem at website {url}") # Mars Facts-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- try: url = 'http://space-facts.com/mars/' #Load url to pandas read html. tables = pd.read_html(url) #Tables marsFacts_df = tables[0] earthMars_df = tables[1] #Rename columns marsFacts_df.columns = ['Facts', 'Values'] #Outpout html_outputFacts = marsFacts_df.to_html(index = False) html_outputFacts = html_outputFacts.replace('\n', '') html_outputMarsEarth = earthMars_df.to_html(index = False) html_outputMarsEarth = html_outputMarsEarth.replace('\n', '') marsInfo_dict['html_outputFacts'] = html_outputFacts marsInfo_dict['html_outputMarsEarth'] = html_outputMarsEarth except : print(f"Problem at website {url}") #hemisphereImages ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- try: temp_list = [] url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" #splinter option - open url #browser.visit(url) #Opens the url. browser.get(url) time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source # close web browser browser.close() #Use bs4 to parse the html response. soup = bs(html, "html.parser") links = soup.find_all('div', class_="description") for link in links: highDef_url = f"https://astrogeology.usgs.gov{link.find("a")["href"]}" responseHighDef = requests.get(highDef_url) soupHighDef = bs(responseHighDef.text, 'html.parser') highDef_url = soupHighDef.find_all("div", class_="downloads")[0].find('a')['href'] title = link.find('h3').text temp_list.append({"title" : title, "img_url" : highDef_url}) marsInfo_dict['hemisphere_image_urls'] = temp_list except : print(f"Problem at website {url}") return marsInfo_dict
#Import Libraries #Web Scraping tools from bs4 import BeautifulSoup as bs from selenium import webdriver #from splinter import Browser #DataFrame tools import pandas as pd #Misc tools for web scraping import time import requests #Function to initianilze browser. def init_browser(): #Settings for headless mode. options = webdriver.ChromeOptions() options.add_argument('headless') #Splinter option - using absolute path #executable_path = {'executable_path': '/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver'} #browser = Browser('chrome', **executable_path, headless = True) #path to the driver and load the options. browser = webdriver.Chrome("/Users/Sebastian/Documents/GitHub/Data Visualization Bootcamp/Sebastian Homework/Web-Scraping-Challenge/chromedriver",chrome_options = options) #returns the brower. return browser def scrapper(): #Call browser function browser = init_browser() #Dictionary to store all the results. marsInfo_dict = {} #Code to get NASA Mars News ---------------------------------------------------------------------------------------------- try: url = "https://mars.nasa.gov/news/?page=0&per_page=40&order=publish_date+desc%2Ccreated_at+desc&search=&year=2020%3Apublish_date&category=19%2C165%2C184%2C204&blank_scope=Latest" #splinter option - open url #browser.visit(url) #Open url. browser.get(url) #Time to let the website load all the elements time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") #Collect the latest news title news_title = soup.find_all('li', class_="slide")[0].find(class_="content_title").text news_p = soup.find_all('li', class_="slide")[0].text marsInfo_dict['news_title'] = news_title marsInfo_dict['news_p'] = news_p except : print(f"Problem at website {url}") #Code to get JPL Mars Space Images - Featured Image --------------------------------------------------------------------------------- try: url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars" #splinter option - open url #browser.visit(url) #Opens the url. browser.get(url) #splinter option - FULL IMAGE BUTTON #browser.click_link_by_id("full_image") #Interact with the FULL IMAGE BUTTON browser.find_element_by_id("full_image").click() time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") featured_image_url = "https://www.jpl.nasa.gov/" + soup.find_all('img', class_="fancybox-image")[0]['src'] marsInfo_dict['featured_image_url'] = featured_image_url except : print(f"Problem at website {url}") #Mars Weather ------------------------------------------------------------------------------------------------------------------------ try: url = "https://twitter.com/marswxreport?lang=en" #splinter option - open url #browser.visit(url) #Open the url. browser.get(url) #Time to let the website load all the elements time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source #Use bs4 to parse the html response. soup = bs(html, "html.parser") mars_weather = soup.find_all('article', class_="css-1dbjc4n r-1loqt21 r-18u37iz r-1ny4l3l r-o7ynqc r-6416eg")[0].text.strip().replace('Mars Weather@MarsWxReport·19hInSight ','') marsInfo_dict['mars_weather'] = mars_weather except : print(mars_weather) print(f"Problem at website {url}") # Mars Facts-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- try: url = 'http://space-facts.com/mars/' #Load url to pandas read html. tables = pd.read_html(url) #Tables marsFacts_df = tables[0] earthMars_df = tables[1] #Rename columns marsFacts_df.columns = ['Facts', 'Values'] #Outpout html_outputFacts = marsFacts_df.to_html(index = False) html_outputFacts = html_outputFacts.replace('\n', '') html_outputMarsEarth = earthMars_df.to_html(index = False) html_outputMarsEarth = html_outputMarsEarth.replace('\n', '') marsInfo_dict['html_outputFacts'] = html_outputFacts marsInfo_dict['html_outputMarsEarth'] = html_outputMarsEarth except : print(f"Problem at website {url}") #hemisphereImages ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- try: temp_list = [] url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars" #splinter option - open url #browser.visit(url) #Opens the url. browser.get(url) time.sleep(4) #splinter option - save HTML #html = browser.html #save the html source. html = browser.page_source # close web browser browser.close() #Use bs4 to parse the html response. soup = bs(html, "html.parser") links = soup.find_all('div', class_="description") for link in links: highDef_url = f"https://astrogeology.usgs.gov{link.find('a')['href']}" responseHighDef = requests.get(highDef_url) soupHighDef = bs(responseHighDef.text, 'html.parser') highDef_url = soupHighDef.find_all("div", class_="downloads")[0].find('a')['href'] title = link.find('h3').text temp_list.append({"title" : title, "img_url" : highDef_url}) marsInfo_dict['hemisphere_image_urls'] = temp_list except : print(f"Problem at website {url}") return marsInfo_dict
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # TheCyberUserBot - Luciferxz import io import re import userbot.modules.sql_helper.blacklist_sql as sql from userbot import CMD_HELP from userbot.events import register from requests import get from userbot.cmdhelp import CmdHelp # ██████ LANGUAGE CONSTANTS ██████ # from userbot.language import get_value LANG = get_value("blacklist") # ████████████████████████████████ # KUFURLER = get('https://raw.githubusercontent.com/FaridDadashzade/deploy/main/forbidden.json').json() @register(incoming=True, disable_edited=True, disable_errors=True) async def on_new_message(event): name = event.raw_text snips = sql.get_chat_blacklist(event.chat_id) for snip in snips: if snip == "küfür": for kufur in KUFURLER: pattern = r"( |^|[^\w])" + re.escape(kufur) + r"( |$|[^\w])" if re.search(pattern, name, flags=re.IGNORECASE): try: await event.delete() except: await event.reply(LANG['FORBIDDEN_KUFUR']) sql.rm_from_blacklist(event.chat_id, "kufur") break pass continue else: pattern = r"( |^|[^\w])" + re.escape(snip) + r"( |$|[^\w])" if re.search(pattern, name, flags=re.IGNORECASE): try: await event.delete() except Exception as e: await event.reply(LANG['HAVENT_PERMISSION']) sql.rm_from_blacklist(event.chat_id, snip.lower()) break pass @register(outgoing=True, pattern="^.küfür ?(.*)") @register(outgoing=True, pattern="^.otoblist ?(.*)") @register(outgoing=True, pattern="^.s[oö]y[üu]ş ?(.*)") async def kufur(event): kufur = event.pattern_match.group(1) if len(kufur) < 1: await event.edit(LANG['USAGE_KUFUR']) if kufur == "aç": sql.add_to_blacklist(event.chat_id, "küfür") await event.edit(LANG['OPENED_KUFUR']) elif kufur == "bağla": if sql.rm_from_blacklist(event.chat_id, "küfür"): await event.edit(LANG['CLOSED_KUFUR']) else: await event.edit(LANG['ALREADY_CLOSED_KUFUR']) @register(outgoing=True, pattern="^.addblacklist(?: |$)(.*)") async def on_add_black_list(addbl): if addbl.is_reply: reply = await addbl.get_reply_message() text = reply.text else: text = addbl.pattern_match.group(1) to_blacklist = text.split() for trigger in to_blacklist: sql.add_to_blacklist(addbl.chat_id, trigger) await addbl.edit("{} **{}**".format(len(to_blacklist), LANG['ADDED'])) @register(outgoing=True, pattern="^.listblacklist(?: |$)(.*)") async def on_view_blacklist(listbl): all_blacklisted = sql.get_chat_blacklist(listbl.chat_id) OUT_STR = f"**{LANG["BLACKLIST"]}**\n" if len(all_blacklisted) > 0: for trigger in all_blacklisted: OUT_STR += f"`{trigger}`\n" else: OUT_STR = LANG['NOT_FOUND'] if len(OUT_STR) > 4096: with io.BytesIO(str.encode(OUT_STR)) as out_file: out_file.name = "blacklist.text" await listbl.client.send_file( listbl.chat_id, out_file, force_document=True, allow_cache=False, caption=LANG['BLACKLIST_FILE'], reply_to=listbl ) await listbl.delete() else: await listbl.edit(OUT_STR) @register(outgoing=True, pattern="^.rmblacklist(?: |$)(.*)") async def on_delete_blacklist(rmbl): text = rmbl.pattern_match.group(1) to_unblacklist = list(set(trigger.strip() for trigger in text.split("\n") if trigger.strip())) successful = 0 for trigger in to_unblacklist: if sql.rm_from_blacklist(rmbl.chat_id, trigger.lower()): successful += 1 await rmbl.edit(LANG['REMOVED']) CmdHelp('blacklist').add_command( 'listblacklist', None, 'Bir söhbətdəki aktiv blacklist-i göstərər.' ).add_command( 'addblacklist', '<söz(lər)/cavab>', 'Mesajı \'qara list bölməsinə\' qeyd edər. \'Kara liste anahtar kelimesinden\' bahsedildiğinde bot iletiyi siler.', '.addblacklist amk' ).add_command( 'rmblacklist', '<söz>', 'Belirtilen kara listeyi durdurur.', '.rmblacklist amk' ).add_command( 'söyüş', '<aç/bağla>', 'Oto Blacklisti açar grupda söyüş söyən olsa silər', '.söyüş aç' ).add_warning('Bu işlemleri gerçekleştirmek için yönetici olmalı ve **Mesaj Silme** yetkiniz olmalı.').add()
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # # TheCyberUserBot - Luciferxz import io import re import userbot.modules.sql_helper.blacklist_sql as sql from userbot import CMD_HELP from userbot.events import register from requests import get from userbot.cmdhelp import CmdHelp # ██████ LANGUAGE CONSTANTS ██████ # from userbot.language import get_value LANG = get_value("blacklist") # ████████████████████████████████ # KUFURLER = get('https://raw.githubusercontent.com/FaridDadashzade/deploy/main/forbidden.json').json() @register(incoming=True, disable_edited=True, disable_errors=True) async def on_new_message(event): name = event.raw_text snips = sql.get_chat_blacklist(event.chat_id) for snip in snips: if snip == "küfür": for kufur in KUFURLER: pattern = r"( |^|[^\w])" + re.escape(kufur) + r"( |$|[^\w])" if re.search(pattern, name, flags=re.IGNORECASE): try: await event.delete() except: await event.reply(LANG['FORBIDDEN_KUFUR']) sql.rm_from_blacklist(event.chat_id, "kufur") break pass continue else: pattern = r"( |^|[^\w])" + re.escape(snip) + r"( |$|[^\w])" if re.search(pattern, name, flags=re.IGNORECASE): try: await event.delete() except Exception as e: await event.reply(LANG['HAVENT_PERMISSION']) sql.rm_from_blacklist(event.chat_id, snip.lower()) break pass @register(outgoing=True, pattern="^.küfür ?(.*)") @register(outgoing=True, pattern="^.otoblist ?(.*)") @register(outgoing=True, pattern="^.s[oö]y[üu]ş ?(.*)") async def kufur(event): kufur = event.pattern_match.group(1) if len(kufur) < 1: await event.edit(LANG['USAGE_KUFUR']) if kufur == "aç": sql.add_to_blacklist(event.chat_id, "küfür") await event.edit(LANG['OPENED_KUFUR']) elif kufur == "bağla": if sql.rm_from_blacklist(event.chat_id, "küfür"): await event.edit(LANG['CLOSED_KUFUR']) else: await event.edit(LANG['ALREADY_CLOSED_KUFUR']) @register(outgoing=True, pattern="^.addblacklist(?: |$)(.*)") async def on_add_black_list(addbl): if addbl.is_reply: reply = await addbl.get_reply_message() text = reply.text else: text = addbl.pattern_match.group(1) to_blacklist = text.split() for trigger in to_blacklist: sql.add_to_blacklist(addbl.chat_id, trigger) await addbl.edit("{} **{}**".format(len(to_blacklist), LANG['ADDED'])) @register(outgoing=True, pattern="^.listblacklist(?: |$)(.*)") async def on_view_blacklist(listbl): all_blacklisted = sql.get_chat_blacklist(listbl.chat_id) OUT_STR = f"**{LANG['BLACKLIST']}**\n" if len(all_blacklisted) > 0: for trigger in all_blacklisted: OUT_STR += f"`{trigger}`\n" else: OUT_STR = LANG['NOT_FOUND'] if len(OUT_STR) > 4096: with io.BytesIO(str.encode(OUT_STR)) as out_file: out_file.name = "blacklist.text" await listbl.client.send_file( listbl.chat_id, out_file, force_document=True, allow_cache=False, caption=LANG['BLACKLIST_FILE'], reply_to=listbl ) await listbl.delete() else: await listbl.edit(OUT_STR) @register(outgoing=True, pattern="^.rmblacklist(?: |$)(.*)") async def on_delete_blacklist(rmbl): text = rmbl.pattern_match.group(1) to_unblacklist = list(set(trigger.strip() for trigger in text.split("\n") if trigger.strip())) successful = 0 for trigger in to_unblacklist: if sql.rm_from_blacklist(rmbl.chat_id, trigger.lower()): successful += 1 await rmbl.edit(LANG['REMOVED']) CmdHelp('blacklist').add_command( 'listblacklist', None, 'Bir söhbətdəki aktiv blacklist-i göstərər.' ).add_command( 'addblacklist', '<söz(lər)/cavab>', 'Mesajı \'qara list bölməsinə\' qeyd edər. \'Kara liste anahtar kelimesinden\' bahsedildiğinde bot iletiyi siler.', '.addblacklist amk' ).add_command( 'rmblacklist', '<söz>', 'Belirtilen kara listeyi durdurur.', '.rmblacklist amk' ).add_command( 'söyüş', '<aç/bağla>', 'Oto Blacklisti açar grupda söyüş söyən olsa silər', '.söyüş aç' ).add_warning('Bu işlemleri gerçekleştirmek için yönetici olmalı ve **Mesaj Silme** yetkiniz olmalı.').add()
import typing as t from abc import ABC, abstractmethod from types import SimpleNamespace from .exceptions import BadMethod, FinalizationError, NoMethod, NotFound from .line import Line from .patterns import REGEX_TYPES from .route import Route from .tree import Tree from .utils import parts_to_path, path_to_parts # The below functions might be called by the compiled source code, and # therefore should be made available here by import import re # noqa isort:skip from datetime import datetime # noqa isort:skip from urllib.parse import unquote # noqa isort:skip from uuid import UUID # noqa isort:skip from .patterns import parse_date # noqa isort:skip class BaseRouter(ABC): DEFAULT_METHOD = "BASE" ALLOWED_METHODS: t.Tuple[str, ...] = tuple() def __init__( self, delimiter: str = "/", exception: t.Type[NotFound] = NotFound, method_handler_exception: t.Type[NoMethod] = NoMethod, route_class: t.Type[Route] = Route, stacking: bool = False, cascade_not_found: bool = False, ) -> None: self._find_route = None self._matchers = None self.static_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.dynamic_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.regex_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.name_index: t.Dict[str, Route] = {} self.delimiter = delimiter self.exception = exception self.method_handler_exception = method_handler_exception self.route_class = route_class self.tree = Tree() self.finalized = False self.stacking = stacking self.ctx = SimpleNamespace() self.cascade_not_found = cascade_not_found @abstractmethod def get(self, **kwargs): ... def resolve( self, path: str, *, method: t.Optional[str] = None, orig: t.Optional[str] = None, extra: t.Optional[t.Dict[str, str]] = None, ): try: route, param_basket = self.find_route( path, self, {"__handler_idx__": 0, "__params__": {}}, extra ) except NotFound as e: if path.endswith(self.delimiter): return self.resolve( path=path[:-1], method=method, orig=path, extra=extra, ) raise self.exception(str(e), path=path) handler = None handler_idx = param_basket.pop("__handler_idx__") raw_path = param_basket.pop("__raw_path__") params = param_basket.pop("__params__") if route.strict and orig and orig[-1] != route.path[-1]: raise self.exception("Path not found", path=path) handler = route.get_handler(raw_path, method, handler_idx) return route, handler, params def add( self, path: str, handler: t.Callable, methods: t.Optional[t.Union[t.Iterable[str], str]] = None, name: t.Optional[str] = None, requirements: t.Optional[t.Dict[str, t.Any]] = None, strict: bool = False, unquote: bool = False, # noqa overwrite: bool = False, ) -> Route: if not methods: methods = [self.DEFAULT_METHOD] if hasattr(methods, "__iter__") and not isinstance(methods, frozenset): methods = frozenset(methods) elif isinstance(methods, str): methods = frozenset([methods]) if self.ALLOWED_METHODS and any( method not in self.ALLOWED_METHODS for method in methods ): bad = [ method for method in methods if method not in self.ALLOWED_METHODS ] raise BadMethod( f"Bad method: {bad}. Must be one of: {self.ALLOWED_METHODS}" ) if self.finalized: raise FinalizationError("Cannot finalize router more than once.") static = "<" not in path and requirements is None regex = self._is_regex(path) if regex: routes = self.regex_routes elif static: routes = self.static_routes else: routes = self.dynamic_routes # Only URL encode the static parts of the path path = parts_to_path( path_to_parts(path, self.delimiter), self.delimiter ) strip = path.lstrip if strict else path.strip path = strip(self.delimiter) route = self.route_class( self, path, name or "", strict=strict, unquote=unquote, static=static, regex=regex, ) # Catch the scenario where a route is overloaded with and # and without requirements, first as dynamic then as static if static and route.parts in self.dynamic_routes: routes = self.dynamic_routes # Catch the reverse scenario where a route is overload first as static # and then as dynamic if not static and route.parts in self.static_routes: route = self.static_routes.pop(route.parts) self.dynamic_routes[route.parts] = route else: if route.parts in routes: route = routes[route.parts] else: routes[route.parts] = route if name: self.name_index[name] = route for method in methods: route.add_handler(path, handler, method, requirements, overwrite) return route def finalize(self, do_compile: bool = True): if self.finalized: raise FinalizationError("Cannot finalize router more than once.") if not self.routes: raise FinalizationError("Cannot finalize with no routes defined.") self.finalized = True for route in self.routes.values(): route.finalize() self._generate_tree() self._render(do_compile) def reset(self): self.finalized = False self.tree = Tree() self._find_route = None for route in self.routes.values(): route.reset() def _generate_tree(self) -> None: self.tree.generate(self.dynamic_routes) self.tree.finalize() def _render(self, do_compile: bool = True) -> None: src = [ Line("def find_route(path, router, basket, extra):", 0), Line("parts = tuple(path[1:].split(router.delimiter))", 1), ] delayed = [] if self.static_routes: # TODO: # - future improvement would be to decide which option to use # at runtime based upon the makeup of the router since this # potentially has an impact on performance src += [ Line("try:", 1), Line("route = router.static_routes[parts]", 2), Line("basket['__raw_path__'] = path", 2), Line("return route, basket", 2), Line("except KeyError:", 1), Line("pass", 2), ] # src += [ # Line("if parts in router.static_routes:", 1), # Line("route = router.static_routes[parts]", 2), # Line("basket['__raw_path__'] = route.path", 2), # Line("return route, basket", 2), # ] # src += [ # Line("if path in router.static_routes:", 1), # Line("route = router.static_routes.get(path)", 2), # Line("basket['__raw_path__'] = route.path", 2), # Line("return route, basket", 2), # ] if self.dynamic_routes: src += [Line("num = len(parts)", 1)] src += self.tree.render() if self.regex_routes: routes = sorted( self.regex_routes.values(), key=lambda route: len(route.parts), reverse=True, ) delayed.append(Line("matchers = [", 0)) for idx, route in enumerate(routes): delayed.append(Line(f"re.compile(r'^{route.pattern}$'),", 1)) src.extend( [ Line(f"match = router.matchers[{idx}].match(path)", 1), Line("if match:", 1), Line("basket['__params__'] = match.groupdict()", 2), Line(f"basket['__raw_path__'] = '{route.path}'", 2), Line( ( f"return router.name_index['{route.name}'], " "basket" ), 2, ), ] ) delayed.append(Line("]", 0)) src.append(Line("raise NotFound", 1)) src.extend(delayed) self.optimize(src) self.find_route_src = "".join( map(str, filter(lambda x: x.render, src)) ) if do_compile: try: compiled_src = compile( self.find_route_src, "", "exec", ) except SyntaxError as se: syntax_error = ( f"Line {se.lineno}: {se.msg}\n{se.text}" f"{" "*max(0,int(se.offset or 0)-1) + "^"}" ) raise FinalizationError( f"Cannot compile route AST:\n{self.find_route_src}" f"\n{syntax_error}" ) ctx: t.Dict[t.Any, t.Any] = {} exec(compiled_src, None, ctx) self._find_route = ctx["find_route"] self._matchers = ctx.get("matchers") @property def find_route(self): return self._find_route @property def matchers(self): return self._matchers @property def routes(self): return { **self.static_routes, **self.dynamic_routes, **self.regex_routes, } def optimize(self, src: t.List[Line]) -> None: """ Insert NotFound exceptions to be able to bail as quick as possible, and realign lines to proper indentation """ offset = 0 current = 0 insert_at = set() for num, line in enumerate(src): if line.indent < current: if not line.src.startswith("."): if offset < 0: offset += 1 else: offset = 0 if ( line.src.startswith("if") or line.src.startswith("elif") or line.src.startswith("return") or line.src.startswith("basket") or line.src.startswith("try") ): idnt = line.indent + 1 prev_line = src[num - 1] while idnt < prev_line.indent: insert_at.add((num, idnt)) idnt += 1 offset += line.offset line.indent += offset current = line.indent idnt = 1 prev_line = src[-1] while idnt < prev_line.indent: insert_at.add((len(src), idnt)) idnt += 1 if self.cascade_not_found: for num, indent in sorted( insert_at, key=lambda x: (x[0] * -1, x[1]) ): src.insert(num, Line("raise NotFound", indent)) def _is_regex(self, path: str): parts = path_to_parts(path, self.delimiter) def requires(part): if not part.startswith("<") or ":" not in part: return False _, pattern_type = part[1:-1].split(":", 1) return ( part.endswith(":path>") or self.delimiter in part or pattern_type not in REGEX_TYPES ) return any(requires(part) for part in parts)
import typing as t from abc import ABC, abstractmethod from types import SimpleNamespace from .exceptions import BadMethod, FinalizationError, NoMethod, NotFound from .line import Line from .patterns import REGEX_TYPES from .route import Route from .tree import Tree from .utils import parts_to_path, path_to_parts # The below functions might be called by the compiled source code, and # therefore should be made available here by import import re # noqa isort:skip from datetime import datetime # noqa isort:skip from urllib.parse import unquote # noqa isort:skip from uuid import UUID # noqa isort:skip from .patterns import parse_date # noqa isort:skip class BaseRouter(ABC): DEFAULT_METHOD = "BASE" ALLOWED_METHODS: t.Tuple[str, ...] = tuple() def __init__( self, delimiter: str = "/", exception: t.Type[NotFound] = NotFound, method_handler_exception: t.Type[NoMethod] = NoMethod, route_class: t.Type[Route] = Route, stacking: bool = False, cascade_not_found: bool = False, ) -> None: self._find_route = None self._matchers = None self.static_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.dynamic_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.regex_routes: t.Dict[t.Tuple[str, ...], Route] = {} self.name_index: t.Dict[str, Route] = {} self.delimiter = delimiter self.exception = exception self.method_handler_exception = method_handler_exception self.route_class = route_class self.tree = Tree() self.finalized = False self.stacking = stacking self.ctx = SimpleNamespace() self.cascade_not_found = cascade_not_found @abstractmethod def get(self, **kwargs): ... def resolve( self, path: str, *, method: t.Optional[str] = None, orig: t.Optional[str] = None, extra: t.Optional[t.Dict[str, str]] = None, ): try: route, param_basket = self.find_route( path, self, {"__handler_idx__": 0, "__params__": {}}, extra ) except NotFound as e: if path.endswith(self.delimiter): return self.resolve( path=path[:-1], method=method, orig=path, extra=extra, ) raise self.exception(str(e), path=path) handler = None handler_idx = param_basket.pop("__handler_idx__") raw_path = param_basket.pop("__raw_path__") params = param_basket.pop("__params__") if route.strict and orig and orig[-1] != route.path[-1]: raise self.exception("Path not found", path=path) handler = route.get_handler(raw_path, method, handler_idx) return route, handler, params def add( self, path: str, handler: t.Callable, methods: t.Optional[t.Union[t.Iterable[str], str]] = None, name: t.Optional[str] = None, requirements: t.Optional[t.Dict[str, t.Any]] = None, strict: bool = False, unquote: bool = False, # noqa overwrite: bool = False, ) -> Route: if not methods: methods = [self.DEFAULT_METHOD] if hasattr(methods, "__iter__") and not isinstance(methods, frozenset): methods = frozenset(methods) elif isinstance(methods, str): methods = frozenset([methods]) if self.ALLOWED_METHODS and any( method not in self.ALLOWED_METHODS for method in methods ): bad = [ method for method in methods if method not in self.ALLOWED_METHODS ] raise BadMethod( f"Bad method: {bad}. Must be one of: {self.ALLOWED_METHODS}" ) if self.finalized: raise FinalizationError("Cannot finalize router more than once.") static = "<" not in path and requirements is None regex = self._is_regex(path) if regex: routes = self.regex_routes elif static: routes = self.static_routes else: routes = self.dynamic_routes # Only URL encode the static parts of the path path = parts_to_path( path_to_parts(path, self.delimiter), self.delimiter ) strip = path.lstrip if strict else path.strip path = strip(self.delimiter) route = self.route_class( self, path, name or "", strict=strict, unquote=unquote, static=static, regex=regex, ) # Catch the scenario where a route is overloaded with and # and without requirements, first as dynamic then as static if static and route.parts in self.dynamic_routes: routes = self.dynamic_routes # Catch the reverse scenario where a route is overload first as static # and then as dynamic if not static and route.parts in self.static_routes: route = self.static_routes.pop(route.parts) self.dynamic_routes[route.parts] = route else: if route.parts in routes: route = routes[route.parts] else: routes[route.parts] = route if name: self.name_index[name] = route for method in methods: route.add_handler(path, handler, method, requirements, overwrite) return route def finalize(self, do_compile: bool = True): if self.finalized: raise FinalizationError("Cannot finalize router more than once.") if not self.routes: raise FinalizationError("Cannot finalize with no routes defined.") self.finalized = True for route in self.routes.values(): route.finalize() self._generate_tree() self._render(do_compile) def reset(self): self.finalized = False self.tree = Tree() self._find_route = None for route in self.routes.values(): route.reset() def _generate_tree(self) -> None: self.tree.generate(self.dynamic_routes) self.tree.finalize() def _render(self, do_compile: bool = True) -> None: src = [ Line("def find_route(path, router, basket, extra):", 0), Line("parts = tuple(path[1:].split(router.delimiter))", 1), ] delayed = [] if self.static_routes: # TODO: # - future improvement would be to decide which option to use # at runtime based upon the makeup of the router since this # potentially has an impact on performance src += [ Line("try:", 1), Line("route = router.static_routes[parts]", 2), Line("basket['__raw_path__'] = path", 2), Line("return route, basket", 2), Line("except KeyError:", 1), Line("pass", 2), ] # src += [ # Line("if parts in router.static_routes:", 1), # Line("route = router.static_routes[parts]", 2), # Line("basket['__raw_path__'] = route.path", 2), # Line("return route, basket", 2), # ] # src += [ # Line("if path in router.static_routes:", 1), # Line("route = router.static_routes.get(path)", 2), # Line("basket['__raw_path__'] = route.path", 2), # Line("return route, basket", 2), # ] if self.dynamic_routes: src += [Line("num = len(parts)", 1)] src += self.tree.render() if self.regex_routes: routes = sorted( self.regex_routes.values(), key=lambda route: len(route.parts), reverse=True, ) delayed.append(Line("matchers = [", 0)) for idx, route in enumerate(routes): delayed.append(Line(f"re.compile(r'^{route.pattern}$'),", 1)) src.extend( [ Line(f"match = router.matchers[{idx}].match(path)", 1), Line("if match:", 1), Line("basket['__params__'] = match.groupdict()", 2), Line(f"basket['__raw_path__'] = '{route.path}'", 2), Line( ( f"return router.name_index['{route.name}'], " "basket" ), 2, ), ] ) delayed.append(Line("]", 0)) src.append(Line("raise NotFound", 1)) src.extend(delayed) self.optimize(src) self.find_route_src = "".join( map(str, filter(lambda x: x.render, src)) ) if do_compile: try: compiled_src = compile( self.find_route_src, "", "exec", ) except SyntaxError as se: syntax_error = ( f"Line {se.lineno}: {se.msg}\n{se.text}" f"{' '*max(0,int(se.offset or 0)-1) + '^'}" ) raise FinalizationError( f"Cannot compile route AST:\n{self.find_route_src}" f"\n{syntax_error}" ) ctx: t.Dict[t.Any, t.Any] = {} exec(compiled_src, None, ctx) self._find_route = ctx["find_route"] self._matchers = ctx.get("matchers") @property def find_route(self): return self._find_route @property def matchers(self): return self._matchers @property def routes(self): return { **self.static_routes, **self.dynamic_routes, **self.regex_routes, } def optimize(self, src: t.List[Line]) -> None: """ Insert NotFound exceptions to be able to bail as quick as possible, and realign lines to proper indentation """ offset = 0 current = 0 insert_at = set() for num, line in enumerate(src): if line.indent < current: if not line.src.startswith("."): if offset < 0: offset += 1 else: offset = 0 if ( line.src.startswith("if") or line.src.startswith("elif") or line.src.startswith("return") or line.src.startswith("basket") or line.src.startswith("try") ): idnt = line.indent + 1 prev_line = src[num - 1] while idnt < prev_line.indent: insert_at.add((num, idnt)) idnt += 1 offset += line.offset line.indent += offset current = line.indent idnt = 1 prev_line = src[-1] while idnt < prev_line.indent: insert_at.add((len(src), idnt)) idnt += 1 if self.cascade_not_found: for num, indent in sorted( insert_at, key=lambda x: (x[0] * -1, x[1]) ): src.insert(num, Line("raise NotFound", indent)) def _is_regex(self, path: str): parts = path_to_parts(path, self.delimiter) def requires(part): if not part.startswith("<") or ":" not in part: return False _, pattern_type = part[1:-1].split(":", 1) return ( part.endswith(":path>") or self.delimiter in part or pattern_type not in REGEX_TYPES ) return any(requires(part) for part in parts)
# Copyright (c) 2021 Cybereason Inc # This code is licensed under MIT license (see LICENSE.md for details) import json import requests import oci import io import base64 import logging import hashlib from fdk import response from cybereason_connection import get_cybereason_connection from cybereason_machine_suspicions import is_suspicious from cybereason_isolate_machine import isolate_machine from oci_utils import * from constants import * def get_private_ips(machine_type, signer, compartment_id, resource_id): # Getting the instances private IPs private_ips = [] if machine_type == MT_INSTANCE: private_ips = get_instance_private_ips(signer,compartment_id,resource_id) elif machine_type == MT_DATABASE: db_system_id = get_db_system_from_database(signer, resource_id) private_ips = get_database_ip(signer, compartment_id, db_system_id) elif machine_type == MT_DATABASE_SYSTEM: private_ips = get_database_ip(signer, compartment_id,resource_id) if not private_ips: print("No IPs found for resource: " + resource_id, flush=True) private_ips = [] return private_ips def send_notification(signer, ctx, body, remediated): try: ctx_data = dict(ctx.Config()) topic_id = ctx_data.get('ONS_TOPIC_OCID') if not topic_id: print('WARNING: No ONS topic OCID provided. Cannot publish message to topic.', flush=True) return cloud_guard_problem = body["data"]["resourceName"] if remediated: message_title = "Cloud Guard Problem " + cloud_guard_problem + " Isolated by Cybereason" message_body = f'Cloud Guard has detected problem with {body['data']['resourceName'].lower()}. Cybereason also detected suspicious activity and has isolated the machine to remediate the Cloud Guard Problem.' message_body = message_body + f'\nFor more information go to the OCI Cloud Guard Console and look for {cloud_guard_problem}' else: message_title = "Cloud Guard Finding " + cloud_guard_problem + " Suspicious Activity Detected by Cybereason" message_body = f'Cloud Guard has detected a {body['data']['resourceName'].lower()} and Cybereason also detected suspicious activity.' message_body = message_body + f'\nFor more information go to the OCI Cloud Guard Console and look for {cloud_guard_problem}' notification_message = {"default": "Cloud Guard Finding", "body": message_body, "title": message_title} ons = oci.ons.NotificationDataPlaneClient(config={}, signer=signer) ons.publish_message(topic_id, notification_message) except (Exception) as ex: print('ERROR: Failed to publish message to topic', ex, flush=True) raise def machine_event_handler(ctx, handler_options, data: io.BytesIO=None): print("Cloud Guard Response I support", flush=True) signer = get_signer() number_of_findings = 0 # The number of findings from the Cybereason console private_ips = [] # Private IPs associate with the OCI Instance body = get_request_body(data) # Getting Instance's IP to query Cybereason resource_id = body["data"]["additionalDetails"]["resourceId"] compartment_id = body["data"]["compartmentId"] private_ips = get_private_ips(handler_options['machine_type'], signer, compartment_id, resource_id) try: ctx_data = dict(ctx.Config()) server = ctx_data['CYBEREASON_SERVER'] port = ctx_data['CYBEREASON_PORT'] username = ctx_data['CYBEREASON_USERNAME'] password = get_password_from_secrets(signer, ctx_data['CYBEREASON_SECRET_OCID']) cr_isolate_machine = ctx_data.get('ISOLATE_MACHINE', 'False').lower() send_notifications = ctx_data.get('SEND_NOTIFICATIONS', 'False').lower() except Exception as ex: print("ERROR: Failed to retrieve function configuration data", ex, flush=True) raise # We can have multiple IP addresses. Loop through each one of them. cr_connection = get_cybereason_connection(server, port, username, password) for ipaddr in private_ips: number_of_findings = is_suspicious(cr_connection, ipaddr) if number_of_findings > 0: # We have some suspicious findings from Cybereason print('Cybereason found {number_of_findings} issues in the machine specified by ip address {ip_address}'.format(ip_address=ipaddr, number_of_findings=number_of_findings), flush=True) if handler_options['isolate_machine'] and (cr_isolate_machine == 'true'): isolate_machine(cr_connection, ipaddr) cloud_guard_remediate_problem(signer, body["data"]["resourceId"]) # Determining if what notification to send to the user if handler_options['send_notifications'] and (send_notifications == 'true') and handler_options['isolate_machine'] and (cr_isolate_machine == 'true'): send_notification(signer, ctx, body, True) if handler_options['send_notifications'] and (send_notifications == 'true'): send_notification(signer, ctx, body, False) return response.Response( ctx, response_data={"Private_IPs" : private_ips, "Number_of_findings" : number_of_findings}, headers={"Content-Type": "application/json"} )
# Copyright (c) 2021 Cybereason Inc # This code is licensed under MIT license (see LICENSE.md for details) import json import requests import oci import io import base64 import logging import hashlib from fdk import response from cybereason_connection import get_cybereason_connection from cybereason_machine_suspicions import is_suspicious from cybereason_isolate_machine import isolate_machine from oci_utils import * from constants import * def get_private_ips(machine_type, signer, compartment_id, resource_id): # Getting the instances private IPs private_ips = [] if machine_type == MT_INSTANCE: private_ips = get_instance_private_ips(signer,compartment_id,resource_id) elif machine_type == MT_DATABASE: db_system_id = get_db_system_from_database(signer, resource_id) private_ips = get_database_ip(signer, compartment_id, db_system_id) elif machine_type == MT_DATABASE_SYSTEM: private_ips = get_database_ip(signer, compartment_id,resource_id) if not private_ips: print("No IPs found for resource: " + resource_id, flush=True) private_ips = [] return private_ips def send_notification(signer, ctx, body, remediated): try: ctx_data = dict(ctx.Config()) topic_id = ctx_data.get('ONS_TOPIC_OCID') if not topic_id: print('WARNING: No ONS topic OCID provided. Cannot publish message to topic.', flush=True) return cloud_guard_problem = body["data"]["resourceName"] if remediated: message_title = "Cloud Guard Problem " + cloud_guard_problem + " Isolated by Cybereason" message_body = f'Cloud Guard has detected problem with {body["data"]["resourceName"].lower()}. Cybereason also detected suspicious activity and has isolated the machine to remediate the Cloud Guard Problem.' message_body = message_body + f'\nFor more information go to the OCI Cloud Guard Console and look for {cloud_guard_problem}' else: message_title = "Cloud Guard Finding " + cloud_guard_problem + " Suspicious Activity Detected by Cybereason" message_body = f'Cloud Guard has detected a {body["data"]["resourceName"].lower()} and Cybereason also detected suspicious activity.' message_body = message_body + f'\nFor more information go to the OCI Cloud Guard Console and look for {cloud_guard_problem}' notification_message = {"default": "Cloud Guard Finding", "body": message_body, "title": message_title} ons = oci.ons.NotificationDataPlaneClient(config={}, signer=signer) ons.publish_message(topic_id, notification_message) except (Exception) as ex: print('ERROR: Failed to publish message to topic', ex, flush=True) raise def machine_event_handler(ctx, handler_options, data: io.BytesIO=None): print("Cloud Guard Response I support", flush=True) signer = get_signer() number_of_findings = 0 # The number of findings from the Cybereason console private_ips = [] # Private IPs associate with the OCI Instance body = get_request_body(data) # Getting Instance's IP to query Cybereason resource_id = body["data"]["additionalDetails"]["resourceId"] compartment_id = body["data"]["compartmentId"] private_ips = get_private_ips(handler_options['machine_type'], signer, compartment_id, resource_id) try: ctx_data = dict(ctx.Config()) server = ctx_data['CYBEREASON_SERVER'] port = ctx_data['CYBEREASON_PORT'] username = ctx_data['CYBEREASON_USERNAME'] password = get_password_from_secrets(signer, ctx_data['CYBEREASON_SECRET_OCID']) cr_isolate_machine = ctx_data.get('ISOLATE_MACHINE', 'False').lower() send_notifications = ctx_data.get('SEND_NOTIFICATIONS', 'False').lower() except Exception as ex: print("ERROR: Failed to retrieve function configuration data", ex, flush=True) raise # We can have multiple IP addresses. Loop through each one of them. cr_connection = get_cybereason_connection(server, port, username, password) for ipaddr in private_ips: number_of_findings = is_suspicious(cr_connection, ipaddr) if number_of_findings > 0: # We have some suspicious findings from Cybereason print('Cybereason found {number_of_findings} issues in the machine specified by ip address {ip_address}'.format(ip_address=ipaddr, number_of_findings=number_of_findings), flush=True) if handler_options['isolate_machine'] and (cr_isolate_machine == 'true'): isolate_machine(cr_connection, ipaddr) cloud_guard_remediate_problem(signer, body["data"]["resourceId"]) # Determining if what notification to send to the user if handler_options['send_notifications'] and (send_notifications == 'true') and handler_options['isolate_machine'] and (cr_isolate_machine == 'true'): send_notification(signer, ctx, body, True) if handler_options['send_notifications'] and (send_notifications == 'true'): send_notification(signer, ctx, body, False) return response.Response( ctx, response_data={"Private_IPs" : private_ips, "Number_of_findings" : number_of_findings}, headers={"Content-Type": "application/json"} )
import aiohttp from flask import Flask from aio_executor import run_with_asyncio app = Flask(__name__) async def get_random_quote(): async with aiohttp.ClientSession() as session: async with session.get('https://api.quotable.io/random') as response: quote = await response.json() return f'{quote['content']} ({quote['author']})' @app.route('/') @run_with_asyncio async def index(): return await get_random_quote() if __name__ == '__main__': app.run()
import aiohttp from flask import Flask from aio_executor import run_with_asyncio app = Flask(__name__) async def get_random_quote(): async with aiohttp.ClientSession() as session: async with session.get('https://api.quotable.io/random') as response: quote = await response.json() return f'{quote["content"]} ({quote["author"]})' @app.route('/') @run_with_asyncio async def index(): return await get_random_quote() if __name__ == '__main__': app.run()
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import glob import json import urllib.parse import urllib.request import webbrowser from typing import Dict from .checker import * from .database import MongoDBHandler from .helper import handle_dot_in_keys from ..clients.python import ProgressBar from ..excepts import PeaFailToStart from ..helper import colored, get_readable_size, get_now_timestamp, get_full_version, random_name, expand_dict from ..logging import get_logger from ..logging.profile import TimeContext if False: import argparse _allowed = {'name', 'description', 'author', 'url', 'documentation', 'version', 'vendor', 'license', 'avatar', 'platform', 'update', 'keywords'} _repo_prefix = 'jinahub/' _label_prefix = 'ai.jina.hub.' class HubIO: """ :class:`HubIO` provides the way to interact with Jina Hub registry. You can use it with CLI to package a directory into a Jina Hub image and publish it to the world. Examples: - :command:`jina hub build my_pod/` build the image - :command:`jina hub build my_pod/ --push` build the image and push to the public registry - :command:`jina hub pull jinahub/pod.dummy_mwu_encoder:0.0.6` to download the image """ def __init__(self, args: 'argparse.Namespace'): self.logger = get_logger(self.__class__.__name__, **vars(args)) self.args = args try: import docker from docker import APIClient self._client = docker.from_env() # low-level client self._raw_client = APIClient(base_url='unix://var/run/docker.sock') except (ImportError, ModuleNotFoundError): self.logger.critical('requires "docker" dependency, please install it via "pip install jina[docker]"') raise def new(self) -> None: """Create a new executor using cookiecutter template """ try: from cookiecutter.main import cookiecutter except (ImportError, ModuleNotFoundError): self.logger.critical('requires "cookiecutter" dependency, please install it via "pip install cookiecutter"') raise import click cookiecutter_template = self.args.template if self.args.type == 'app': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina.git' elif self.args.type == 'pod': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina-hub.git' cookiecutter(cookiecutter_template, overwrite_if_exists=self.args.overwrite, output_dir=self.args.output_dir) try: cookiecutter(cookiecutter_template, overwrite_if_exists=self.args.overwrite, output_dir=self.args.output_dir) except click.exceptions.Abort: self.logger.info('nothing is created, bye!') def push(self, name: str = None, readme_path: str = None) -> None: """ A wrapper of docker push - Checks for the tempfile, returns without push if it cannot find - Pushes to docker hub, returns withput writing to db if it fails - Writes to the db """ name = name or self.args.name file_path = get_summary_path(name) if not os.path.isfile(file_path): self.logger.error(f'can not find the build summary file') return try: self._push_docker_hub(name, readme_path) except: self.logger.error('can not push to the docker hub registry') return with open(file_path) as f: result = json.load(f) if result['is_build_success']: self._write_summary_to_db(summary=result) def _push_docker_hub(self, name: str = None, readme_path: str = None) -> None: """ Helper push function """ check_registry(self.args.registry, name, _repo_prefix) self._check_docker_image(name) self.login() with ProgressBar(task_name=f'pushing {name}', batch_unit='') as t: for line in self._client.images.push(name, stream=True, decode=True): t.update(1) self.logger.debug(line) self.logger.success(f'🎉 {name} is now published!') if False and readme_path: # unfortunately Docker Hub Personal Access Tokens cannot be used as they are not supported by the API _volumes = {os.path.dirname(os.path.abspath(readme_path)): {'bind': '/workspace'}} _env = { 'DOCKERHUB_USERNAME': self.args.username, 'DOCKERHUB_PASSWORD': self.args.password, 'DOCKERHUB_REPOSITORY': name.split(':')[0], 'README_FILEPATH': '/workspace/README.md', } self._client.containers.run('peterevans/dockerhub-description:2.1', auto_remove=True, volumes=_volumes, environment=_env) share_link = f'https://api.jina.ai/hub/?jh={urllib.parse.quote_plus(name)}' try: webbrowser.open(share_link, new=2) except: pass finally: self.logger.info( f'Check out the usage {colored(share_link, 'cyan', attrs=['underline'])} and share it with others!') def pull(self) -> None: """A wrapper of docker pull """ check_registry(self.args.registry, self.args.name, _repo_prefix) self.login() try: with TimeContext(f'pulling {self.args.name}', self.logger): image = self._client.images.pull(self.args.name) if isinstance(image, list): image = image[0] image_tag = image.tags[0] if image.tags else '' self.logger.success( f'🎉 pulled {image_tag} ({image.short_id}) uncompressed size: {get_readable_size(image.attrs['Size'])}') except: self.logger.error(f'can not pull image {self.args.name} from {self.args.registry}') raise def _check_docker_image(self, name: str) -> None: # check local image image = self._client.images.get(name) for r in _allowed: if f'{_label_prefix}{r}' not in image.labels.keys(): self.logger.warning(f'{r} is missing in your docker image labels, you may want to check it') try: if name != safe_url_name( f'{_repo_prefix}' + '{type}.{kind}.{name}:{version}'.format( **{k.replace(_label_prefix, ''): v for k, v in image.labels.items()})): raise ValueError(f'image {name} does not match with label info in the image') except KeyError: self.logger.error('missing key in the label of the image') raise self.logger.info(f'✅ {name} is a valid Jina Hub image, ready to publish') def login(self) -> None: """A wrapper of docker login """ if self.args.username and self.args.password: self._client.login(username=self.args.username, password=self.args.password, registry=self.args.registry) else: raise ValueError('no username/password specified, docker login failed') def build(self) -> Dict: """A wrapper of docker build """ if self.args.dry_run: result = self.dry_run() else: is_build_success, is_push_success = True, False _logs = [] _excepts = [] with TimeContext(f'building {colored(self.args.path, 'green')}', self.logger) as tc: try: self._check_completeness() streamer = self._raw_client.build( decode=True, path=self.args.path, tag=self.tag, pull=self.args.pull, dockerfile=self.dockerfile_path_revised, rm=True ) for chunk in streamer: if 'stream' in chunk: for line in chunk['stream'].splitlines(): if is_error_message(line): self.logger.critical(line) _excepts.append(line) elif 'warning' in line.lower(): self.logger.warning(line) else: self.logger.info(line) _logs.append(line) except Exception as ex: # if pytest fails it should end up here as well is_build_success = False _excepts.append(str(ex)) if is_build_success: # compile it again, but this time don't show the log image, log = self._client.images.build(path=self.args.path, tag=self.tag, pull=self.args.pull, dockerfile=self.dockerfile_path_revised, rm=True) # success _details = { 'inspect': self._raw_client.inspect_image(image.tags[0]), 'tag': image.tags[0], 'hash': image.short_id, 'size': get_readable_size(image.attrs['Size']), } self.logger.success( '🎉 built {tag} ({hash}) uncompressed size: {size}'.format_map(_details)) else: self.logger.error(f'can not build the image, please double check the log') _details = {} if is_build_success: if self.args.test_uses: try: is_build_success = False from jina.flow import Flow p_name = random_name() with Flow().add(name=p_name, uses=image.tags[0], daemon=self.args.daemon): pass if self.args.daemon: self._raw_client.stop(p_name) self._raw_client.prune_containers() is_build_success = True except PeaFailToStart: self.logger.error(f'can not use it in the Flow, please check your file bundle') except Exception as ex: self.logger.error(f'something wrong but it is probably not your fault. {repr(ex)}') _version = self.manifest['version'] if 'version' in self.manifest else '0.0.1' info, env_info = get_full_version() _host_info = { 'jina': info, 'jina_envs': env_info, 'docker': self._raw_client.info(), 'build_args': vars(self.args) } _build_history = { 'time': get_now_timestamp(), 'host_info': _host_info if is_build_success and self.args.host_info else '', 'duration': tc.readable_duration, 'logs': _logs, 'exception': _excepts } if self.args.prune_images: self.logger.info('deleting unused images') self._raw_client.prune_images() result = { 'name': getattr(self, 'canonical_name', ''), 'version': self.manifest['version'] if is_build_success and 'version' in self.manifest else '0.0.1', 'path': self.args.path, 'manifest_info': self.manifest if is_build_success else '', 'details': _details, 'is_build_success': is_build_success, 'build_history': [_build_history] } # only successful build (NOT dry run) writes the summary to disk if result['is_build_success']: self._write_summary_to_file(summary=result) if self.args.push: try: self._push_docker_hub(image.tags[0], self.readme_path) self._write_summary_to_db(summary=result) self._write_slack_message(result, _details, _build_history) except Exception as ex: self.logger.error(f'can not complete the push due to {repr(ex)}') if not result['is_build_success'] and self.args.raise_error: # remove the very verbose build log when throw error result['build_history'][0].pop('logs') raise RuntimeError(result) return result def dry_run(self) -> Dict: try: s = self._check_completeness() s['is_build_success'] = True except Exception as ex: s = {'is_build_success': False, 'exception': str(ex)} return s def _write_summary_to_db(self, summary: Dict) -> None: """ Inserts / Updates summary document in mongodb """ if not is_db_envs_set(): self.logger.warning('MongoDB environment vars are not set! bookkeeping skipped.') return build_summary = handle_dot_in_keys(document=summary) _build_query = {'name': build_summary['name'], 'version': build_summary['version']} _current_build_history = build_summary['build_history'] with MongoDBHandler(hostname=os.environ['JINA_DB_HOSTNAME'], username=os.environ['JINA_DB_USERNAME'], password=os.environ['JINA_DB_PASSWORD'], database_name=os.environ['JINA_DB_NAME'], collection_name=os.environ['JINA_DB_COLLECTION']) as db: existing_doc = db.find(query=_build_query) if existing_doc: build_summary['build_history'] = existing_doc['build_history'] + _current_build_history _modified_count = db.replace(document=build_summary, query=_build_query) self.logger.debug(f'Updated the build + push summary in db. {_modified_count} documents modified') else: _inserted_id = db.insert(document=build_summary) self.logger.debug(f'Inserted the build + push summary in db with id {_inserted_id}') def _write_summary_to_file(self, summary: Dict) -> None: file_path = get_summary_path(f'{summary['name']}:{summary['version']}') with open(file_path, 'w+') as f: json.dump(summary, f) self.logger.debug(f'stored the summary from build to {file_path}') def _check_completeness(self) -> Dict: self.dockerfile_path = get_exist_path(self.args.path, 'Dockerfile') self.manifest_path = get_exist_path(self.args.path, 'manifest.yml') self.readme_path = get_exist_path(self.args.path, 'README.md') self.requirements_path = get_exist_path(self.args.path, 'requirements.txt') yaml_glob = glob.glob(os.path.join(self.args.path, '*.yml')) if yaml_glob: yaml_glob.remove(self.manifest_path) py_glob = glob.glob(os.path.join(self.args.path, '*.py')) test_glob = glob.glob(os.path.join(self.args.path, 'tests/test_*.py')) completeness = { 'Dockerfile': self.dockerfile_path, 'manifest.yml': self.manifest_path, 'README.md': self.readme_path, 'requirements.txt': self.requirements_path, '*.yml': yaml_glob, '*.py': py_glob, 'tests': test_glob } self.logger.info( f'completeness check\n' + '\n'.join('%4s %-20s %s' % (colored('✓', 'green') if v else colored('✗', 'red'), k, v) for k, v in completeness.items()) + '\n') if completeness['Dockerfile'] and completeness['manifest.yml']: pass else: self.logger.critical('Dockerfile or manifest.yml is not given, can not build') raise FileNotFoundError('Dockerfile or manifest.yml is not given, can not build') self.manifest = self._read_manifest(self.manifest_path) self.dockerfile_path_revised = self._get_revised_dockerfile(self.dockerfile_path, self.manifest) self.tag = safe_url_name(f'{_repo_prefix}' + '{type}.{kind}.{name}:{version}'.format(**self.manifest)) self.canonical_name = safe_url_name(f'{_repo_prefix}' + '{type}.{kind}.{name}'.format(**self.manifest)) return completeness def _read_manifest(self, path: str, validate: bool = True) -> Dict: with resource_stream('jina', '/'.join(('resources', 'hub-builder', 'manifest.yml'))) as fp: tmp = yaml.load(fp) # do not expand variables at here, i.e. DO NOT USE expand_dict(yaml.load(fp)) with open(path) as fp: tmp.update(yaml.load(fp)) if validate: self._validate_manifest(tmp) return tmp def _validate_manifest(self, manifest: Dict) -> None: required = {'name', 'type', 'version'} # check the required field in manifest for r in required: if r not in manifest: raise ValueError(f'{r} is missing in the manifest.yaml, it is required') # check if all fields are there for r in _allowed: if r not in manifest: self.logger.warning(f'{r} is missing in your manifest.yml, you may want to check it') # check name check_name(manifest['name']) # check_image_type check_image_type(manifest['type']) # check version number check_version(manifest['version']) # check version number check_license(manifest['license']) # check platform if not isinstance(manifest['platform'], list): manifest['platform'] = list(manifest['platform']) check_platform(manifest['platform']) # replace all chars in value to safe chars for k, v in manifest.items(): if v and isinstance(v, str): manifest[k] = remove_control_characters(v) # show manifest key-values for k, v in manifest.items(): self.logger.debug(f'{k}: {v}') def _get_revised_dockerfile(self, dockerfile_path: str, manifest: Dict) -> str: # modify dockerfile revised_dockerfile = [] with open(dockerfile_path) as fp: for l in fp: revised_dockerfile.append(l) if l.startswith('FROM'): revised_dockerfile.append('LABEL ') revised_dockerfile.append( ' \\ \n'.join(f'{_label_prefix}{k}="{v}"' for k, v in manifest.items())) f = tempfile.NamedTemporaryFile('w', delete=False).name with open(f, 'w', encoding='utf8') as fp: fp.writelines(revised_dockerfile) for k in revised_dockerfile: self.logger.debug(k) return f def _write_slack_message(self, *args): def _expand_fn(v): if isinstance(v, str): for d in args: try: v = v.format(**d) except KeyError: pass return v if 'JINAHUB_SLACK_WEBHOOK' in os.environ: with resource_stream('jina', '/'.join(('resources', 'hub-builder-success', 'slack-jinahub.json'))) as fp: tmp = expand_dict(json.load(fp), _expand_fn, resolve_cycle_ref=False) req = urllib.request.Request(os.environ['JINAHUB_SLACK_WEBHOOK']) req.add_header('Content-Type', 'application/json; charset=utf-8') jdb = json.dumps(tmp).encode('utf-8') # needs to be bytes req.add_header('Content-Length', str(len(jdb))) with urllib.request.urlopen(req, jdb) as f: res = f.read() self.logger.info(f'push to Slack: {res}') # alias of "new" in cli create = new init = new
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import glob import json import urllib.parse import urllib.request import webbrowser from typing import Dict from .checker import * from .database import MongoDBHandler from .helper import handle_dot_in_keys from ..clients.python import ProgressBar from ..excepts import PeaFailToStart from ..helper import colored, get_readable_size, get_now_timestamp, get_full_version, random_name, expand_dict from ..logging import get_logger from ..logging.profile import TimeContext if False: import argparse _allowed = {'name', 'description', 'author', 'url', 'documentation', 'version', 'vendor', 'license', 'avatar', 'platform', 'update', 'keywords'} _repo_prefix = 'jinahub/' _label_prefix = 'ai.jina.hub.' class HubIO: """ :class:`HubIO` provides the way to interact with Jina Hub registry. You can use it with CLI to package a directory into a Jina Hub image and publish it to the world. Examples: - :command:`jina hub build my_pod/` build the image - :command:`jina hub build my_pod/ --push` build the image and push to the public registry - :command:`jina hub pull jinahub/pod.dummy_mwu_encoder:0.0.6` to download the image """ def __init__(self, args: 'argparse.Namespace'): self.logger = get_logger(self.__class__.__name__, **vars(args)) self.args = args try: import docker from docker import APIClient self._client = docker.from_env() # low-level client self._raw_client = APIClient(base_url='unix://var/run/docker.sock') except (ImportError, ModuleNotFoundError): self.logger.critical('requires "docker" dependency, please install it via "pip install jina[docker]"') raise def new(self) -> None: """Create a new executor using cookiecutter template """ try: from cookiecutter.main import cookiecutter except (ImportError, ModuleNotFoundError): self.logger.critical('requires "cookiecutter" dependency, please install it via "pip install cookiecutter"') raise import click cookiecutter_template = self.args.template if self.args.type == 'app': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina.git' elif self.args.type == 'pod': cookiecutter_template = 'https://github.com/jina-ai/cookiecutter-jina-hub.git' cookiecutter(cookiecutter_template, overwrite_if_exists=self.args.overwrite, output_dir=self.args.output_dir) try: cookiecutter(cookiecutter_template, overwrite_if_exists=self.args.overwrite, output_dir=self.args.output_dir) except click.exceptions.Abort: self.logger.info('nothing is created, bye!') def push(self, name: str = None, readme_path: str = None) -> None: """ A wrapper of docker push - Checks for the tempfile, returns without push if it cannot find - Pushes to docker hub, returns withput writing to db if it fails - Writes to the db """ name = name or self.args.name file_path = get_summary_path(name) if not os.path.isfile(file_path): self.logger.error(f'can not find the build summary file') return try: self._push_docker_hub(name, readme_path) except: self.logger.error('can not push to the docker hub registry') return with open(file_path) as f: result = json.load(f) if result['is_build_success']: self._write_summary_to_db(summary=result) def _push_docker_hub(self, name: str = None, readme_path: str = None) -> None: """ Helper push function """ check_registry(self.args.registry, name, _repo_prefix) self._check_docker_image(name) self.login() with ProgressBar(task_name=f'pushing {name}', batch_unit='') as t: for line in self._client.images.push(name, stream=True, decode=True): t.update(1) self.logger.debug(line) self.logger.success(f'🎉 {name} is now published!') if False and readme_path: # unfortunately Docker Hub Personal Access Tokens cannot be used as they are not supported by the API _volumes = {os.path.dirname(os.path.abspath(readme_path)): {'bind': '/workspace'}} _env = { 'DOCKERHUB_USERNAME': self.args.username, 'DOCKERHUB_PASSWORD': self.args.password, 'DOCKERHUB_REPOSITORY': name.split(':')[0], 'README_FILEPATH': '/workspace/README.md', } self._client.containers.run('peterevans/dockerhub-description:2.1', auto_remove=True, volumes=_volumes, environment=_env) share_link = f'https://api.jina.ai/hub/?jh={urllib.parse.quote_plus(name)}' try: webbrowser.open(share_link, new=2) except: pass finally: self.logger.info( f'Check out the usage {colored(share_link, "cyan", attrs=["underline"])} and share it with others!') def pull(self) -> None: """A wrapper of docker pull """ check_registry(self.args.registry, self.args.name, _repo_prefix) self.login() try: with TimeContext(f'pulling {self.args.name}', self.logger): image = self._client.images.pull(self.args.name) if isinstance(image, list): image = image[0] image_tag = image.tags[0] if image.tags else '' self.logger.success( f'🎉 pulled {image_tag} ({image.short_id}) uncompressed size: {get_readable_size(image.attrs["Size"])}') except: self.logger.error(f'can not pull image {self.args.name} from {self.args.registry}') raise def _check_docker_image(self, name: str) -> None: # check local image image = self._client.images.get(name) for r in _allowed: if f'{_label_prefix}{r}' not in image.labels.keys(): self.logger.warning(f'{r} is missing in your docker image labels, you may want to check it') try: if name != safe_url_name( f'{_repo_prefix}' + '{type}.{kind}.{name}:{version}'.format( **{k.replace(_label_prefix, ''): v for k, v in image.labels.items()})): raise ValueError(f'image {name} does not match with label info in the image') except KeyError: self.logger.error('missing key in the label of the image') raise self.logger.info(f'✅ {name} is a valid Jina Hub image, ready to publish') def login(self) -> None: """A wrapper of docker login """ if self.args.username and self.args.password: self._client.login(username=self.args.username, password=self.args.password, registry=self.args.registry) else: raise ValueError('no username/password specified, docker login failed') def build(self) -> Dict: """A wrapper of docker build """ if self.args.dry_run: result = self.dry_run() else: is_build_success, is_push_success = True, False _logs = [] _excepts = [] with TimeContext(f'building {colored(self.args.path, "green")}', self.logger) as tc: try: self._check_completeness() streamer = self._raw_client.build( decode=True, path=self.args.path, tag=self.tag, pull=self.args.pull, dockerfile=self.dockerfile_path_revised, rm=True ) for chunk in streamer: if 'stream' in chunk: for line in chunk['stream'].splitlines(): if is_error_message(line): self.logger.critical(line) _excepts.append(line) elif 'warning' in line.lower(): self.logger.warning(line) else: self.logger.info(line) _logs.append(line) except Exception as ex: # if pytest fails it should end up here as well is_build_success = False _excepts.append(str(ex)) if is_build_success: # compile it again, but this time don't show the log image, log = self._client.images.build(path=self.args.path, tag=self.tag, pull=self.args.pull, dockerfile=self.dockerfile_path_revised, rm=True) # success _details = { 'inspect': self._raw_client.inspect_image(image.tags[0]), 'tag': image.tags[0], 'hash': image.short_id, 'size': get_readable_size(image.attrs['Size']), } self.logger.success( '🎉 built {tag} ({hash}) uncompressed size: {size}'.format_map(_details)) else: self.logger.error(f'can not build the image, please double check the log') _details = {} if is_build_success: if self.args.test_uses: try: is_build_success = False from jina.flow import Flow p_name = random_name() with Flow().add(name=p_name, uses=image.tags[0], daemon=self.args.daemon): pass if self.args.daemon: self._raw_client.stop(p_name) self._raw_client.prune_containers() is_build_success = True except PeaFailToStart: self.logger.error(f'can not use it in the Flow, please check your file bundle') except Exception as ex: self.logger.error(f'something wrong but it is probably not your fault. {repr(ex)}') _version = self.manifest['version'] if 'version' in self.manifest else '0.0.1' info, env_info = get_full_version() _host_info = { 'jina': info, 'jina_envs': env_info, 'docker': self._raw_client.info(), 'build_args': vars(self.args) } _build_history = { 'time': get_now_timestamp(), 'host_info': _host_info if is_build_success and self.args.host_info else '', 'duration': tc.readable_duration, 'logs': _logs, 'exception': _excepts } if self.args.prune_images: self.logger.info('deleting unused images') self._raw_client.prune_images() result = { 'name': getattr(self, 'canonical_name', ''), 'version': self.manifest['version'] if is_build_success and 'version' in self.manifest else '0.0.1', 'path': self.args.path, 'manifest_info': self.manifest if is_build_success else '', 'details': _details, 'is_build_success': is_build_success, 'build_history': [_build_history] } # only successful build (NOT dry run) writes the summary to disk if result['is_build_success']: self._write_summary_to_file(summary=result) if self.args.push: try: self._push_docker_hub(image.tags[0], self.readme_path) self._write_summary_to_db(summary=result) self._write_slack_message(result, _details, _build_history) except Exception as ex: self.logger.error(f'can not complete the push due to {repr(ex)}') if not result['is_build_success'] and self.args.raise_error: # remove the very verbose build log when throw error result['build_history'][0].pop('logs') raise RuntimeError(result) return result def dry_run(self) -> Dict: try: s = self._check_completeness() s['is_build_success'] = True except Exception as ex: s = {'is_build_success': False, 'exception': str(ex)} return s def _write_summary_to_db(self, summary: Dict) -> None: """ Inserts / Updates summary document in mongodb """ if not is_db_envs_set(): self.logger.warning('MongoDB environment vars are not set! bookkeeping skipped.') return build_summary = handle_dot_in_keys(document=summary) _build_query = {'name': build_summary['name'], 'version': build_summary['version']} _current_build_history = build_summary['build_history'] with MongoDBHandler(hostname=os.environ['JINA_DB_HOSTNAME'], username=os.environ['JINA_DB_USERNAME'], password=os.environ['JINA_DB_PASSWORD'], database_name=os.environ['JINA_DB_NAME'], collection_name=os.environ['JINA_DB_COLLECTION']) as db: existing_doc = db.find(query=_build_query) if existing_doc: build_summary['build_history'] = existing_doc['build_history'] + _current_build_history _modified_count = db.replace(document=build_summary, query=_build_query) self.logger.debug(f'Updated the build + push summary in db. {_modified_count} documents modified') else: _inserted_id = db.insert(document=build_summary) self.logger.debug(f'Inserted the build + push summary in db with id {_inserted_id}') def _write_summary_to_file(self, summary: Dict) -> None: file_path = get_summary_path(f'{summary["name"]}:{summary["version"]}') with open(file_path, 'w+') as f: json.dump(summary, f) self.logger.debug(f'stored the summary from build to {file_path}') def _check_completeness(self) -> Dict: self.dockerfile_path = get_exist_path(self.args.path, 'Dockerfile') self.manifest_path = get_exist_path(self.args.path, 'manifest.yml') self.readme_path = get_exist_path(self.args.path, 'README.md') self.requirements_path = get_exist_path(self.args.path, 'requirements.txt') yaml_glob = glob.glob(os.path.join(self.args.path, '*.yml')) if yaml_glob: yaml_glob.remove(self.manifest_path) py_glob = glob.glob(os.path.join(self.args.path, '*.py')) test_glob = glob.glob(os.path.join(self.args.path, 'tests/test_*.py')) completeness = { 'Dockerfile': self.dockerfile_path, 'manifest.yml': self.manifest_path, 'README.md': self.readme_path, 'requirements.txt': self.requirements_path, '*.yml': yaml_glob, '*.py': py_glob, 'tests': test_glob } self.logger.info( f'completeness check\n' + '\n'.join('%4s %-20s %s' % (colored('✓', 'green') if v else colored('✗', 'red'), k, v) for k, v in completeness.items()) + '\n') if completeness['Dockerfile'] and completeness['manifest.yml']: pass else: self.logger.critical('Dockerfile or manifest.yml is not given, can not build') raise FileNotFoundError('Dockerfile or manifest.yml is not given, can not build') self.manifest = self._read_manifest(self.manifest_path) self.dockerfile_path_revised = self._get_revised_dockerfile(self.dockerfile_path, self.manifest) self.tag = safe_url_name(f'{_repo_prefix}' + '{type}.{kind}.{name}:{version}'.format(**self.manifest)) self.canonical_name = safe_url_name(f'{_repo_prefix}' + '{type}.{kind}.{name}'.format(**self.manifest)) return completeness def _read_manifest(self, path: str, validate: bool = True) -> Dict: with resource_stream('jina', '/'.join(('resources', 'hub-builder', 'manifest.yml'))) as fp: tmp = yaml.load(fp) # do not expand variables at here, i.e. DO NOT USE expand_dict(yaml.load(fp)) with open(path) as fp: tmp.update(yaml.load(fp)) if validate: self._validate_manifest(tmp) return tmp def _validate_manifest(self, manifest: Dict) -> None: required = {'name', 'type', 'version'} # check the required field in manifest for r in required: if r not in manifest: raise ValueError(f'{r} is missing in the manifest.yaml, it is required') # check if all fields are there for r in _allowed: if r not in manifest: self.logger.warning(f'{r} is missing in your manifest.yml, you may want to check it') # check name check_name(manifest['name']) # check_image_type check_image_type(manifest['type']) # check version number check_version(manifest['version']) # check version number check_license(manifest['license']) # check platform if not isinstance(manifest['platform'], list): manifest['platform'] = list(manifest['platform']) check_platform(manifest['platform']) # replace all chars in value to safe chars for k, v in manifest.items(): if v and isinstance(v, str): manifest[k] = remove_control_characters(v) # show manifest key-values for k, v in manifest.items(): self.logger.debug(f'{k}: {v}') def _get_revised_dockerfile(self, dockerfile_path: str, manifest: Dict) -> str: # modify dockerfile revised_dockerfile = [] with open(dockerfile_path) as fp: for l in fp: revised_dockerfile.append(l) if l.startswith('FROM'): revised_dockerfile.append('LABEL ') revised_dockerfile.append( ' \\ \n'.join(f'{_label_prefix}{k}="{v}"' for k, v in manifest.items())) f = tempfile.NamedTemporaryFile('w', delete=False).name with open(f, 'w', encoding='utf8') as fp: fp.writelines(revised_dockerfile) for k in revised_dockerfile: self.logger.debug(k) return f def _write_slack_message(self, *args): def _expand_fn(v): if isinstance(v, str): for d in args: try: v = v.format(**d) except KeyError: pass return v if 'JINAHUB_SLACK_WEBHOOK' in os.environ: with resource_stream('jina', '/'.join(('resources', 'hub-builder-success', 'slack-jinahub.json'))) as fp: tmp = expand_dict(json.load(fp), _expand_fn, resolve_cycle_ref=False) req = urllib.request.Request(os.environ['JINAHUB_SLACK_WEBHOOK']) req.add_header('Content-Type', 'application/json; charset=utf-8') jdb = json.dumps(tmp).encode('utf-8') # needs to be bytes req.add_header('Content-Length', str(len(jdb))) with urllib.request.urlopen(req, jdb) as f: res = f.read() self.logger.info(f'push to Slack: {res}') # alias of "new" in cli create = new init = new
frase = str(input('Digite uma frase: ')).upper().strip() print(f'A letra "A" aparece {frase.count('A')} vezes na frase.') print(f'A primeira letra A apareceu na posição {frase.find('A')+1}.') print(f'A última letra A apareceu na posição {frase.rfind('A')+1}.') ## .join(frase.split()) juntar tudo, remover espaços
frase = str(input('Digite uma frase: ')).upper().strip() print(f'A letra "A" aparece {frase.count("A")} vezes na frase.') print(f'A primeira letra A apareceu na posição {frase.find("A")+1}.') print(f'A última letra A apareceu na posição {frase.rfind("A")+1}.') ## .join(frase.split()) juntar tudo, remover espaços
"""Tests for the Renault integration.""" from __future__ import annotations from types import MappingProxyType from typing import Any from unittest.mock import patch from renault_api.kamereon import schemas from renault_api.renault_account import RenaultAccount from homeassistant.components.renault.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import ( ATTR_ICON, ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_NAME, ATTR_SW_VERSION, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client from homeassistant.helpers.device_registry import DeviceRegistry from .const import ICON_FOR_EMPTY_VALUES, MOCK_CONFIG, MOCK_VEHICLES from tests.common import MockConfigEntry, load_fixture def get_mock_config_entry(): """Create the Renault integration.""" return MockConfigEntry( domain=DOMAIN, source=SOURCE_USER, data=MOCK_CONFIG, unique_id="account_id_1", options={}, entry_id="123456", ) def get_fixtures(vehicle_type: str) -> dict[str, Any]: """Create a vehicle proxy for testing.""" mock_vehicle = MOCK_VEHICLES.get(vehicle_type, {"endpoints": {}}) return { "battery_status": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle["endpoints"]["battery_status"]}") if "battery_status" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleBatteryStatusDataSchema), "charge_mode": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle["endpoints"]["charge_mode"]}") if "charge_mode" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleChargeModeDataSchema), "cockpit": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle["endpoints"]["cockpit"]}") if "cockpit" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleCockpitDataSchema), "hvac_status": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle["endpoints"]["hvac_status"]}") if "hvac_status" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleHvacStatusDataSchema), } def get_no_data_icon(expected_entity: MappingProxyType): """Check attribute for icon for inactive sensors.""" entity_id = expected_entity["entity_id"] return ICON_FOR_EMPTY_VALUES.get(entity_id, expected_entity.get(ATTR_ICON)) async def setup_renault_integration_simple(hass: HomeAssistant): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch("renault_api.renault_account.RenaultAccount.get_vehicles"): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle(hass: HomeAssistant, vehicle_type: str): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] mock_fixtures = get_fixtures(vehicle_type) with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", return_value=mock_fixtures["battery_status"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", return_value=mock_fixtures["charge_mode"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", return_value=mock_fixtures["cockpit"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", return_value=mock_fixtures["hvac_status"], ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle_with_no_data( hass: HomeAssistant, vehicle_type: str ): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] mock_fixtures = get_fixtures("") with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", return_value=mock_fixtures["battery_status"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", return_value=mock_fixtures["charge_mode"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", return_value=mock_fixtures["cockpit"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", return_value=mock_fixtures["hvac_status"], ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle_with_side_effect( hass: HomeAssistant, vehicle_type: str, side_effect: Any ): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", side_effect=side_effect, ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry def check_device_registry( device_registry: DeviceRegistry, expected_device: dict[str, Any] ) -> None: """Ensure that the expected_device is correctly registered.""" assert len(device_registry.devices) == 1 registry_entry = device_registry.async_get_device(expected_device[ATTR_IDENTIFIERS]) assert registry_entry is not None assert registry_entry.identifiers == expected_device[ATTR_IDENTIFIERS] assert registry_entry.manufacturer == expected_device[ATTR_MANUFACTURER] assert registry_entry.name == expected_device[ATTR_NAME] assert registry_entry.model == expected_device[ATTR_MODEL] assert registry_entry.sw_version == expected_device[ATTR_SW_VERSION]
"""Tests for the Renault integration.""" from __future__ import annotations from types import MappingProxyType from typing import Any from unittest.mock import patch from renault_api.kamereon import schemas from renault_api.renault_account import RenaultAccount from homeassistant.components.renault.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import ( ATTR_ICON, ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_NAME, ATTR_SW_VERSION, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client from homeassistant.helpers.device_registry import DeviceRegistry from .const import ICON_FOR_EMPTY_VALUES, MOCK_CONFIG, MOCK_VEHICLES from tests.common import MockConfigEntry, load_fixture def get_mock_config_entry(): """Create the Renault integration.""" return MockConfigEntry( domain=DOMAIN, source=SOURCE_USER, data=MOCK_CONFIG, unique_id="account_id_1", options={}, entry_id="123456", ) def get_fixtures(vehicle_type: str) -> dict[str, Any]: """Create a vehicle proxy for testing.""" mock_vehicle = MOCK_VEHICLES.get(vehicle_type, {"endpoints": {}}) return { "battery_status": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle['endpoints']['battery_status']}") if "battery_status" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleBatteryStatusDataSchema), "charge_mode": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle['endpoints']['charge_mode']}") if "charge_mode" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleChargeModeDataSchema), "cockpit": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle['endpoints']['cockpit']}") if "cockpit" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleCockpitDataSchema), "hvac_status": schemas.KamereonVehicleDataResponseSchema.loads( load_fixture(f"renault/{mock_vehicle['endpoints']['hvac_status']}") if "hvac_status" in mock_vehicle["endpoints"] else load_fixture("renault/no_data.json") ).get_attributes(schemas.KamereonVehicleHvacStatusDataSchema), } def get_no_data_icon(expected_entity: MappingProxyType): """Check attribute for icon for inactive sensors.""" entity_id = expected_entity["entity_id"] return ICON_FOR_EMPTY_VALUES.get(entity_id, expected_entity.get(ATTR_ICON)) async def setup_renault_integration_simple(hass: HomeAssistant): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch("renault_api.renault_account.RenaultAccount.get_vehicles"): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle(hass: HomeAssistant, vehicle_type: str): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] mock_fixtures = get_fixtures(vehicle_type) with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", return_value=mock_fixtures["battery_status"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", return_value=mock_fixtures["charge_mode"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", return_value=mock_fixtures["cockpit"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", return_value=mock_fixtures["hvac_status"], ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle_with_no_data( hass: HomeAssistant, vehicle_type: str ): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] mock_fixtures = get_fixtures("") with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", return_value=mock_fixtures["battery_status"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", return_value=mock_fixtures["charge_mode"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", return_value=mock_fixtures["cockpit"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", return_value=mock_fixtures["hvac_status"], ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry async def setup_renault_integration_vehicle_with_side_effect( hass: HomeAssistant, vehicle_type: str, side_effect: Any ): """Create the Renault integration.""" config_entry = get_mock_config_entry() config_entry.add_to_hass(hass) renault_account = RenaultAccount( config_entry.unique_id, websession=aiohttp_client.async_get_clientsession(hass), ) mock_vehicle = MOCK_VEHICLES[vehicle_type] with patch("renault_api.renault_session.RenaultSession.login"), patch( "renault_api.renault_client.RenaultClient.get_api_account", return_value=renault_account, ), patch( "renault_api.renault_account.RenaultAccount.get_vehicles", return_value=( schemas.KamereonVehiclesResponseSchema.loads( load_fixture(f"renault/vehicle_{vehicle_type}.json") ) ), ), patch( "renault_api.renault_vehicle.RenaultVehicle.supports_endpoint", side_effect=mock_vehicle["endpoints_available"], ), patch( "renault_api.renault_vehicle.RenaultVehicle.has_contract_for_endpoint", return_value=True, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_battery_status", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_charge_mode", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_cockpit", side_effect=side_effect, ), patch( "renault_api.renault_vehicle.RenaultVehicle.get_hvac_status", side_effect=side_effect, ): await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry def check_device_registry( device_registry: DeviceRegistry, expected_device: dict[str, Any] ) -> None: """Ensure that the expected_device is correctly registered.""" assert len(device_registry.devices) == 1 registry_entry = device_registry.async_get_device(expected_device[ATTR_IDENTIFIERS]) assert registry_entry is not None assert registry_entry.identifiers == expected_device[ATTR_IDENTIFIERS] assert registry_entry.manufacturer == expected_device[ATTR_MANUFACTURER] assert registry_entry.name == expected_device[ATTR_NAME] assert registry_entry.model == expected_device[ATTR_MODEL] assert registry_entry.sw_version == expected_device[ATTR_SW_VERSION]
import re import textwrap from core.exceptions import InvalidMemoryAddress, MemoryLimitExceeded class Hex: def __init__(self, data: str = "0x00", _bytes: str = 1, *args, **kwargs) -> None: self._bytes = _bytes self._base = 16 self._format_spec = f"#0{2 + _bytes * 2}x" self._format_spec_bin = f"#0{2 + _bytes * 8}b" self._memory_limit_hex = "FF" * _bytes self._memory_limit = int(self._memory_limit_hex, self._base) self.data = data return def __call__(self, value: str) -> None: self.data = value def __str__(self) -> str: return self._data def __repr__(self) -> str: return self._data def __int__(self) -> int: return int(self._data, self._base) def __index__(self) -> int: return int(self._data, self._base) def __format__(self, format_spec: str = None) -> str: if not format_spec: format_spec = self._format_spec return format(int(self._data, self._base), format_spec) def __next__(self): self._data = format(int(self._data, self._base) + 1, self._format_spec) return self._data def __add__(self, val: int): return Hex(format(int(self._data, self._base) + val, self._format_spec), _bytes=self._bytes) def __sub__(self, val: int): return Hex(format(int(self._data, self._base) - val, self._format_spec), _bytes=self._bytes) def __len__(self): return self._bytes def _verify(self, value: str): if not re.fullmatch("^0[x|X][0-9a-fA-F]+", str(value)): raise InvalidMemoryAddress() if int(str(value), self._base) > self._memory_limit: raise MemoryLimitExceeded() def bin(self) -> str: return format(int(self._data, self._base), self._format_spec_bin) @property def data(self) -> str: return self._data @data.setter def data(self, val: str) -> None: self._verify(val) self._data = format(int(str(val), self._base), self._format_spec) return def read(self, *args, **kwargs) -> str: return self def write(self, val: str, *args, **kwargs) -> bool: self.data = val return True def update(self, val: str, *args, **kwargs) -> bool: return self.write(val, *args, **kwargs) def replace(self, *args, **kwargs) -> None: return self._data.replace(*args, **kwargs) def lower(self, *args, **kwargs): return self._data.lower(*args, **kwargs) def upper(self, *args, **kwargs): return self._data.upper(*args, **kwargs) pass class Byte(Hex): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) pass class Memory(dict): def __init__(self, memory_size=65535, starting_address="0x0000", _bytes=2, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._bytes = 1 self._base = 16 self._memory_size = memory_size self._starting_address = starting_address self._default_mem = "0x00" self._format_spec = f"#0{2 + _bytes * 2}x" self._format_spec_bin = f"#0{2 + _bytes * 4}b" self._memory_limit = int(starting_address, 16) + memory_size self._memory_limit_hex = format(self._memory_limit, self._format_spec) return def __getitem__(self, addr: str) -> str: addr = self._verify(addr) if addr not in self: super().__setitem__(addr, Byte(self._default_mem)) return super().__getitem__(addr) def __setitem__(self, addr: str, value: str) -> None: addr = self._verify(addr) if addr not in self: super().__setitem__(addr, Byte(value)) return super().__getitem__(addr).write(value) def _verify(self, value: str) -> None: if not re.fullmatch("^0[x|X][0-9a-fA-F]+", str(value)): raise InvalidMemoryAddress() if int(str(value), self._base) > self._memory_limit: raise MemoryLimitExceeded() return format(int(value, self._base), self._format_spec) def sort(self): return dict(sorted(self.items(), key=lambda x: int(str(x[0]), 16))) def read(self, *args, **kwargs): return self.__getitem__(*args, **kwargs) def write(self, *args, **kwargs): return self.__setitem__(*args, **kwargs) pass class RegisterPair: def __init__(self, reg_1, reg_2, *args, **kwargs): super().__init__(*args, **kwargs) self._reg_1 = reg_1 self._reg_2 = reg_2 self._registers = { reg_1: Byte(), reg_2: Byte(), } self._bytes = 2 self._base = 16 self.keys = self._registers.keys self.values = self._registers.values self.items = self._registers.items return def __getitem__(self, key): return self._registers.get(key).read() def __setitem__(self, key, value): return self._registers.get(key).write(value) def __repr__(self): return f"{self._registers.get(self._reg_1)} {self._registers.get(self._reg_2)}" def read(self, addr) -> Byte: return self._registers.get(str(addr).upper()) def read_pair(self) -> str: bin1 = format(int(str(self._registers.get(self._reg_1).read()), self._base), f"0{self._bytes * 4}b") bin2 = format(int(str(self._registers.get(self._reg_2).read()), self._base), f"0{self._bytes * 4}b") bin_total = "".join(["0b", bin1, bin2]) return f'0x{format(int(bin_total, 2), f'0{self._bytes * 2}x')}' def write(self, data, addr) -> bool: return self._registers.get(str(addr).upper()).__call__(data) def write_pair(self, data) -> bool: mem_size = 8 binary_data = format(int(str(data), self._base), f"0{self._bytes*8}b") data_1, data_2 = [ format(int(binary_data[mem_size * x : mem_size * (x + 1)], 2), f"#0{int(mem_size/2)}x") for x in range(0, int(len(binary_data) / mem_size)) ] self._registers.get(str(self._reg_1).upper()).__call__(data_1) self._registers.get(str(self._reg_2).upper()).__call__(data_2) return True class StackPointer(Byte): def __init__(self, memory, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.memory = memory def __add__(self, val: int, *args, **kwargs) -> str: """ val: `int` """ data_int = int(self._data, self._base) + val if data_int > self._memory_limit: data_int -= self._memory_limit elif data_int < 0: data_int += self._memory_limit self._data = format(data_int, self._format_spec) return self._data def __sub__(self, val: int, *args, **kwargs) -> str: """ val: `int` """ data_int = int(self._data, self._base) - val if data_int > self._memory_limit: data_int -= self._memory_limit elif data_int < 0: data_int += self._memory_limit self._data = format(data_int, self._format_spec) return self._data def __next__(self): return self.__add__(1) def read(self, *args, **kwargs) -> Byte: """ POP rp """ bin1 = format(int(str(self.memory[self.__add__(1)]), self._base), f"0{8}b") # single byte bin2 = format(int(str(self.memory[self.__add__(1)]), self._base), f"0{8}b") # single byte bin_total = "".join(["0b", bin2, bin1]) return f'0x{format(int(bin_total, 2), f'0{4}x')}' def write(self, data, *args) -> Byte: """ PUSH rp rp = BC, DE, HL, or PSW """ mem_size = 8 binary_data = format(int(str(data), self._base), f"0{self._bytes*8}b") data_1, data_2 = [ format(int(binary_data[mem_size * x : mem_size * (x + 1)], 2), f"#0{int(mem_size/2)}x") for x in range(0, int(len(binary_data) / mem_size)) ] self.memory.write(self._data, data_1) _ = self.__sub__(1) self.memory.write(self._data, data_2) _ = self.__sub__(1) return True class ProgramCounter(Byte): def __init__(self, memory, _bytes=2, *args, **kwargs) -> None: super().__init__(_bytes=2, *args, **kwargs) self.memory = memory return def write(self, data): self.memory[self._data] = data self.__next__() return True class SuperMemory: def __init__(self) -> None: self.memory = Memory(65535, "0x0000") self.A = Byte() self.PSW = Byte() self.BC = RegisterPair("B", "C") self.DE = RegisterPair("D", "E") self.HL = RegisterPair("H", "L") self.SP = StackPointer(self.memory, "0xFFFF", _bytes=2) self.PC = ProgramCounter(self.memory) setattr(self.M.__func__, "read", lambda *args: self.memory[self.HL.read_pair()]) setattr(self.M.__func__, "write", lambda data, *args: self.memory.write(self.HL.read_pair(), data)) pass def M(self): return def _reg_inspect(self): return textwrap.dedent( f""" Registers --------- A/PSW = {self.A} {self.PSW} BC = {self.BC} DE = {self.DE} HL = {self.HL} SP = {self.SP} PC = {self.PC} """ ) def _registers_todict(self): return { "A/PSW": f"{self.A} {self.PSW}", "BC": f"{self.BC}", "DE": f"{self.DE}", "HL": f"{self.HL}", "SP": f"{self.SP}", "PC": f"{self.PC}", } def inspect(self): return "\n\n".join([self._reg_inspect(), str(self.memory.sort())]) pass
import re import textwrap from core.exceptions import InvalidMemoryAddress, MemoryLimitExceeded class Hex: def __init__(self, data: str = "0x00", _bytes: str = 1, *args, **kwargs) -> None: self._bytes = _bytes self._base = 16 self._format_spec = f"#0{2 + _bytes * 2}x" self._format_spec_bin = f"#0{2 + _bytes * 8}b" self._memory_limit_hex = "FF" * _bytes self._memory_limit = int(self._memory_limit_hex, self._base) self.data = data return def __call__(self, value: str) -> None: self.data = value def __str__(self) -> str: return self._data def __repr__(self) -> str: return self._data def __int__(self) -> int: return int(self._data, self._base) def __index__(self) -> int: return int(self._data, self._base) def __format__(self, format_spec: str = None) -> str: if not format_spec: format_spec = self._format_spec return format(int(self._data, self._base), format_spec) def __next__(self): self._data = format(int(self._data, self._base) + 1, self._format_spec) return self._data def __add__(self, val: int): return Hex(format(int(self._data, self._base) + val, self._format_spec), _bytes=self._bytes) def __sub__(self, val: int): return Hex(format(int(self._data, self._base) - val, self._format_spec), _bytes=self._bytes) def __len__(self): return self._bytes def _verify(self, value: str): if not re.fullmatch("^0[x|X][0-9a-fA-F]+", str(value)): raise InvalidMemoryAddress() if int(str(value), self._base) > self._memory_limit: raise MemoryLimitExceeded() def bin(self) -> str: return format(int(self._data, self._base), self._format_spec_bin) @property def data(self) -> str: return self._data @data.setter def data(self, val: str) -> None: self._verify(val) self._data = format(int(str(val), self._base), self._format_spec) return def read(self, *args, **kwargs) -> str: return self def write(self, val: str, *args, **kwargs) -> bool: self.data = val return True def update(self, val: str, *args, **kwargs) -> bool: return self.write(val, *args, **kwargs) def replace(self, *args, **kwargs) -> None: return self._data.replace(*args, **kwargs) def lower(self, *args, **kwargs): return self._data.lower(*args, **kwargs) def upper(self, *args, **kwargs): return self._data.upper(*args, **kwargs) pass class Byte(Hex): def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) pass class Memory(dict): def __init__(self, memory_size=65535, starting_address="0x0000", _bytes=2, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._bytes = 1 self._base = 16 self._memory_size = memory_size self._starting_address = starting_address self._default_mem = "0x00" self._format_spec = f"#0{2 + _bytes * 2}x" self._format_spec_bin = f"#0{2 + _bytes * 4}b" self._memory_limit = int(starting_address, 16) + memory_size self._memory_limit_hex = format(self._memory_limit, self._format_spec) return def __getitem__(self, addr: str) -> str: addr = self._verify(addr) if addr not in self: super().__setitem__(addr, Byte(self._default_mem)) return super().__getitem__(addr) def __setitem__(self, addr: str, value: str) -> None: addr = self._verify(addr) if addr not in self: super().__setitem__(addr, Byte(value)) return super().__getitem__(addr).write(value) def _verify(self, value: str) -> None: if not re.fullmatch("^0[x|X][0-9a-fA-F]+", str(value)): raise InvalidMemoryAddress() if int(str(value), self._base) > self._memory_limit: raise MemoryLimitExceeded() return format(int(value, self._base), self._format_spec) def sort(self): return dict(sorted(self.items(), key=lambda x: int(str(x[0]), 16))) def read(self, *args, **kwargs): return self.__getitem__(*args, **kwargs) def write(self, *args, **kwargs): return self.__setitem__(*args, **kwargs) pass class RegisterPair: def __init__(self, reg_1, reg_2, *args, **kwargs): super().__init__(*args, **kwargs) self._reg_1 = reg_1 self._reg_2 = reg_2 self._registers = { reg_1: Byte(), reg_2: Byte(), } self._bytes = 2 self._base = 16 self.keys = self._registers.keys self.values = self._registers.values self.items = self._registers.items return def __getitem__(self, key): return self._registers.get(key).read() def __setitem__(self, key, value): return self._registers.get(key).write(value) def __repr__(self): return f"{self._registers.get(self._reg_1)} {self._registers.get(self._reg_2)}" def read(self, addr) -> Byte: return self._registers.get(str(addr).upper()) def read_pair(self) -> str: bin1 = format(int(str(self._registers.get(self._reg_1).read()), self._base), f"0{self._bytes * 4}b") bin2 = format(int(str(self._registers.get(self._reg_2).read()), self._base), f"0{self._bytes * 4}b") bin_total = "".join(["0b", bin1, bin2]) return f'0x{format(int(bin_total, 2), f"0{self._bytes * 2}x")}' def write(self, data, addr) -> bool: return self._registers.get(str(addr).upper()).__call__(data) def write_pair(self, data) -> bool: mem_size = 8 binary_data = format(int(str(data), self._base), f"0{self._bytes*8}b") data_1, data_2 = [ format(int(binary_data[mem_size * x : mem_size * (x + 1)], 2), f"#0{int(mem_size/2)}x") for x in range(0, int(len(binary_data) / mem_size)) ] self._registers.get(str(self._reg_1).upper()).__call__(data_1) self._registers.get(str(self._reg_2).upper()).__call__(data_2) return True class StackPointer(Byte): def __init__(self, memory, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.memory = memory def __add__(self, val: int, *args, **kwargs) -> str: """ val: `int` """ data_int = int(self._data, self._base) + val if data_int > self._memory_limit: data_int -= self._memory_limit elif data_int < 0: data_int += self._memory_limit self._data = format(data_int, self._format_spec) return self._data def __sub__(self, val: int, *args, **kwargs) -> str: """ val: `int` """ data_int = int(self._data, self._base) - val if data_int > self._memory_limit: data_int -= self._memory_limit elif data_int < 0: data_int += self._memory_limit self._data = format(data_int, self._format_spec) return self._data def __next__(self): return self.__add__(1) def read(self, *args, **kwargs) -> Byte: """ POP rp """ bin1 = format(int(str(self.memory[self.__add__(1)]), self._base), f"0{8}b") # single byte bin2 = format(int(str(self.memory[self.__add__(1)]), self._base), f"0{8}b") # single byte bin_total = "".join(["0b", bin2, bin1]) return f'0x{format(int(bin_total, 2), f"0{4}x")}' def write(self, data, *args) -> Byte: """ PUSH rp rp = BC, DE, HL, or PSW """ mem_size = 8 binary_data = format(int(str(data), self._base), f"0{self._bytes*8}b") data_1, data_2 = [ format(int(binary_data[mem_size * x : mem_size * (x + 1)], 2), f"#0{int(mem_size/2)}x") for x in range(0, int(len(binary_data) / mem_size)) ] self.memory.write(self._data, data_1) _ = self.__sub__(1) self.memory.write(self._data, data_2) _ = self.__sub__(1) return True class ProgramCounter(Byte): def __init__(self, memory, _bytes=2, *args, **kwargs) -> None: super().__init__(_bytes=2, *args, **kwargs) self.memory = memory return def write(self, data): self.memory[self._data] = data self.__next__() return True class SuperMemory: def __init__(self) -> None: self.memory = Memory(65535, "0x0000") self.A = Byte() self.PSW = Byte() self.BC = RegisterPair("B", "C") self.DE = RegisterPair("D", "E") self.HL = RegisterPair("H", "L") self.SP = StackPointer(self.memory, "0xFFFF", _bytes=2) self.PC = ProgramCounter(self.memory) setattr(self.M.__func__, "read", lambda *args: self.memory[self.HL.read_pair()]) setattr(self.M.__func__, "write", lambda data, *args: self.memory.write(self.HL.read_pair(), data)) pass def M(self): return def _reg_inspect(self): return textwrap.dedent( f""" Registers --------- A/PSW = {self.A} {self.PSW} BC = {self.BC} DE = {self.DE} HL = {self.HL} SP = {self.SP} PC = {self.PC} """ ) def _registers_todict(self): return { "A/PSW": f"{self.A} {self.PSW}", "BC": f"{self.BC}", "DE": f"{self.DE}", "HL": f"{self.HL}", "SP": f"{self.SP}", "PC": f"{self.PC}", } def inspect(self): return "\n\n".join([self._reg_inspect(), str(self.memory.sort())]) pass
from typing import TYPE_CHECKING, List, Optional, Dict, Any from dis_snek.client.const import MISSING from dis_snek.client.utils.attr_utils import define, field from dis_snek.client.utils.converters import optional from dis_snek.models.discord.asset import Asset from dis_snek.models.discord.enums import ApplicationFlags from dis_snek.models.discord.snowflake import Snowflake_Type, to_snowflake from dis_snek.models.discord.team import Team from .base import DiscordObject if TYPE_CHECKING: from dis_snek.client import Snake from dis_snek.models import User __all__ = ["Application"] @define() class Application(DiscordObject): """Represents a discord application.""" name: str = field(repr=True) """The name of the application""" icon: Optional[Asset] = field(default=None) """The icon of the application""" description: Optional[str] = field(default=None) """The description of the application""" rpc_origins: Optional[List[str]] = field(default=None) """An array of rpc origin urls, if rpc is enabled""" bot_public: bool = field(default=True) """When false only app owner can join the app's bot to guilds""" bot_require_code_grant: bool = field(default=False) """When true the app's bot will only join upon completion of the full oauth2 code grant flow""" terms_of_service_url: Optional[str] = field(default=None) """The url of the app's terms of service""" privacy_policy_url: Optional[str] = field(default=None) """The url of the app's privacy policy""" owner_id: Optional[Snowflake_Type] = field(default=None, converter=optional(to_snowflake)) """The id of the owner of the application""" summary: str = field() """If this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku""" verify_key: Optional[str] = field(default=MISSING) """The hex encoded key for verification in interactions and the GameSDK's GetTicket""" team: Optional["Team"] = field(default=None) """If the application belongs to a team, this will be a list of the members of that team""" guild_id: Optional["Snowflake_Type"] = field(default=None) """If this application is a game sold on Discord, this field will be the guild to which it has been linked""" primary_sku_id: Optional["Snowflake_Type"] = field(default=None) """If this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists""" slug: Optional[str] = field(default=None) """If this application is a game sold on Discord, this field will be the URL slug that links to the store page""" cover_image: Optional[str] = field(default=None) """The application's default rich presence invite cover image hash""" flags: Optional["ApplicationFlags"] = field(default=None, converter=optional(ApplicationFlags)) """The application's public flags""" @classmethod def _process_dict(cls, data: Dict[str, Any], client: "Snake") -> Dict[str, Any]: if data.get("team"): data["team"] = Team.from_dict(data["team"], client) data["owner_id"] = data["team"].owner_user_id else: if "owner" in data: owner = client.cache.place_user_data(data.pop("owner")) data["owner_id"] = owner.id if data.get("icon"): data["icon"] = Asset.from_path_hash(client, f"app-icons/{data["id"]}/{{}}", data["icon"]) return data @property def owner(self) -> "User": """The user object for the owner of this application""" return self._client.cache.get_user(self.owner_id)
from typing import TYPE_CHECKING, List, Optional, Dict, Any from dis_snek.client.const import MISSING from dis_snek.client.utils.attr_utils import define, field from dis_snek.client.utils.converters import optional from dis_snek.models.discord.asset import Asset from dis_snek.models.discord.enums import ApplicationFlags from dis_snek.models.discord.snowflake import Snowflake_Type, to_snowflake from dis_snek.models.discord.team import Team from .base import DiscordObject if TYPE_CHECKING: from dis_snek.client import Snake from dis_snek.models import User __all__ = ["Application"] @define() class Application(DiscordObject): """Represents a discord application.""" name: str = field(repr=True) """The name of the application""" icon: Optional[Asset] = field(default=None) """The icon of the application""" description: Optional[str] = field(default=None) """The description of the application""" rpc_origins: Optional[List[str]] = field(default=None) """An array of rpc origin urls, if rpc is enabled""" bot_public: bool = field(default=True) """When false only app owner can join the app's bot to guilds""" bot_require_code_grant: bool = field(default=False) """When true the app's bot will only join upon completion of the full oauth2 code grant flow""" terms_of_service_url: Optional[str] = field(default=None) """The url of the app's terms of service""" privacy_policy_url: Optional[str] = field(default=None) """The url of the app's privacy policy""" owner_id: Optional[Snowflake_Type] = field(default=None, converter=optional(to_snowflake)) """The id of the owner of the application""" summary: str = field() """If this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku""" verify_key: Optional[str] = field(default=MISSING) """The hex encoded key for verification in interactions and the GameSDK's GetTicket""" team: Optional["Team"] = field(default=None) """If the application belongs to a team, this will be a list of the members of that team""" guild_id: Optional["Snowflake_Type"] = field(default=None) """If this application is a game sold on Discord, this field will be the guild to which it has been linked""" primary_sku_id: Optional["Snowflake_Type"] = field(default=None) """If this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists""" slug: Optional[str] = field(default=None) """If this application is a game sold on Discord, this field will be the URL slug that links to the store page""" cover_image: Optional[str] = field(default=None) """The application's default rich presence invite cover image hash""" flags: Optional["ApplicationFlags"] = field(default=None, converter=optional(ApplicationFlags)) """The application's public flags""" @classmethod def _process_dict(cls, data: Dict[str, Any], client: "Snake") -> Dict[str, Any]: if data.get("team"): data["team"] = Team.from_dict(data["team"], client) data["owner_id"] = data["team"].owner_user_id else: if "owner" in data: owner = client.cache.place_user_data(data.pop("owner")) data["owner_id"] = owner.id if data.get("icon"): data["icon"] = Asset.from_path_hash(client, f"app-icons/{data['id']}/{{}}", data["icon"]) return data @property def owner(self) -> "User": """The user object for the owner of this application""" return self._client.cache.get_user(self.owner_id)
import re import sys from collections import defaultdict from typing import TYPE_CHECKING, AbstractSet, List, NamedTuple, Optional from dagster.core.definitions.dependency import DependencyStructure, Node from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvalidSubsetError from dagster.utils import check MAX_NUM = sys.maxsize if TYPE_CHECKING: from dagster.core.execution.plan.plan import ExecutionPlan class OpSelectionData( NamedTuple( "_OpSelectionData", [ ("resolved_op_selection", Optional[AbstractSet[str]]), ("ignored_solids", List[Node]), ], ) ): """The data about op selection. Attributes: resolved_op_selection (Optional[AbstractSet[str]])): The names of selected ops. ignored_solids (List[Node]): The solids in the original full graph but outside the current selection. This is used in run config resolution to handle unsatisfied inputs correctly. """ def __new__(cls, resolved_op_selection=None, ignored_solids=None): return super(OpSelectionData, cls).__new__( cls, resolved_op_selection=check.opt_set_param( resolved_op_selection, "resolved_op_selection", str ), ignored_solids=check.opt_list_param(ignored_solids, "ignored_solids", Node), ) def generate_dep_graph(pipeline_def): """'pipeline to dependency graph. It currently only supports top-level solids. Args: pipeline (PipelineDefinition): The pipeline to execute. Returns: graph (Dict[str, Dict[str, Set[str]]]): the input and output dependency graph. e.g. ``` { "upstream": { "solid_one_1": set(), "solid_one_2": set(), "solid_two": {"solid_one_1", "solid_one_2"}, "solid_three": {"solid_two"}, }, "downstream": { "solid_one_1": {"solid_two"}, "solid_one_2": {"solid_two"}, "solid_two": {"solid_three"}, "solid_three": set(), }, } ``` """ dependency_structure = check.inst_param( pipeline_def.dependency_structure, "dependency_structure", DependencyStructure ) item_names = [i.name for i in pipeline_def.solids] # defaultdict isn't appropriate because we also want to include items without dependencies graph = {"upstream": {}, "downstream": {}} for item_name in item_names: graph["upstream"][item_name] = set() upstream_dep = dependency_structure.input_to_upstream_outputs_for_solid(item_name) for upstreams in upstream_dep.values(): for up in upstreams: graph["upstream"][item_name].add(up.solid_name) graph["downstream"][item_name] = set() downstream_dep = dependency_structure.output_to_downstream_inputs_for_solid(item_name) for downstreams in downstream_dep.values(): for down in downstreams: graph["downstream"][item_name].add(down.solid_name) return graph class Traverser: def __init__(self, graph): self.graph = graph def _fetch_items(self, item_name, depth, direction): dep_graph = self.graph[direction] stack = [item_name] result = set() curr_depth = 0 while stack: # stop when reach the given depth if curr_depth >= depth: break curr_level_len = len(stack) while stack and curr_level_len > 0: curr_item = stack.pop() for item in dep_graph.get(curr_item, set()): curr_level_len -= 1 if item not in result: stack.append(item) result.add(item) curr_depth += 1 return result def fetch_upstream(self, item_name, depth): # return a set of ancestors of the given item, up to the given depth return self._fetch_items(item_name, depth, "upstream") def fetch_downstream(self, item_name, depth): # return a set of descendants of the given item, down to the given depth return self._fetch_items(item_name, depth, "downstream") def parse_clause(clause): def _get_depth(part): if part == "": return 0 if "*" in part: return MAX_NUM if set(part) == set("+"): return len(part) return None token_matching = re.compile(r"^(\*?\+*)?([.\w\d\[\]?_-]+)(\+*\*?)?$").search(clause.strip()) # return None if query is invalid parts = token_matching.groups() if token_matching is not None else [] if len(parts) != 3: return None ancestor_part, item_name, descendant_part = parts up_depth = _get_depth(ancestor_part) down_depth = _get_depth(descendant_part) return (up_depth, item_name, down_depth) def parse_items_from_selection(selection): items = [] for clause in selection: parts = parse_clause(clause) if parts is None: continue _u, item, _d = parts items.append(item) return items def clause_to_subset(graph, clause): """Take a selection query and return a list of the selected and qualified items. Args: graph (Dict[str, Dict[str, Set[str]]]): the input and output dependency graph. clause (str): the subselection query in model selection syntax, e.g. "*some_solid+" will select all of some_solid's upstream dependencies and its direct downstream dependecies. Returns: subset_list (List[str]): a list of selected and qualified solid names, empty if input is invalid. """ # parse cluase if not isinstance(clause, str): return [] parts = parse_clause(clause) if parts is None: return [] up_depth, item_name, down_depth = parts # item_name invalid if item_name not in graph["upstream"]: return [] subset_list = [] traverser = Traverser(graph=graph) subset_list.append(item_name) # traverse graph to get up/downsteam items subset_list += traverser.fetch_upstream(item_name, up_depth) subset_list += traverser.fetch_downstream(item_name, down_depth) return subset_list def parse_solid_selection(pipeline_def, solid_selection): """Take pipeline definition and a list of solid selection queries (inlcuding names of solid invocations. See syntax examples below) and return a set of the qualified solid names. It currently only supports top-level solids. Query syntax examples: - "some_solid": select "some_solid" itself - "*some_solid": select "some_solid" and all ancestors (upstream dependencies) - "some_solid*": select "some_solid" and all descendants (downstream dependencies) - "*some_solid*": select "some_solid" and all of its ancestors and descendants - "+some_solid": select "some_solid" and its ancestors at 1 level up - "some_solid+++": select "some_solid" and its descendants within 3 levels down Note: - If one of the query clauses is invalid, we will skip that one and continue to parse the valid ones. Args: pipeline_def (PipelineDefinition): the pipeline to execute. solid_selection (List[str]): a list of the solid selection queries (including single solid names) to execute. Returns: FrozenSet[str]: a frozenset of qualified deduplicated solid names, empty if no qualified subset selected. """ check.list_param(solid_selection, "solid_selection", of_type=str) # special case: select all if len(solid_selection) == 1 and solid_selection[0] == "*": return frozenset(pipeline_def.graph.node_names()) graph = generate_dep_graph(pipeline_def) solids_set = set() # loop over clauses for clause in solid_selection: subset = clause_to_subset(graph, clause) if len(subset) == 0: raise DagsterInvalidSubsetError( "No qualified solids to execute found for solid_selection={requested}".format( requested=solid_selection ) ) solids_set.update(subset) return frozenset(solids_set) def parse_step_selection(step_deps, step_selection): """Take the dependency dictionary generated while building execution plan and a list of step key selection queries and return a set of the qualified step keys. It currently only supports top-level solids. Args: step_deps (Dict[str, Set[str]]): a dictionary of execution step dependency where the key is a step key and the value is a set of direct upstream dependency of the step. step_selection (List[str]): a list of the step key selection queries (including single step key) to execute. Returns: FrozenSet[str]: a frozenset of qualified deduplicated solid names, empty if no qualified subset selected. """ check.list_param(step_selection, "step_selection", of_type=str) # reverse step_deps to get the downstream_deps # make sure we have all items as keys, including the ones without downstream dependencies downstream_deps = defaultdict(set, {k: set() for k in step_deps.keys()}) for downstream_key, upstream_keys in step_deps.items(): for step_key in upstream_keys: downstream_deps[step_key].add(downstream_key) # generate dep graph graph = {"upstream": step_deps, "downstream": downstream_deps} steps_set = set() step_keys = parse_items_from_selection(step_selection) invalid_keys = [key for key in step_keys if key not in step_deps] if invalid_keys: raise DagsterExecutionStepNotFoundError( f"Step selection refers to unknown step{"s" if len(invalid_keys)> 1 else ""}: {", ".join(invalid_keys)}", step_keys=invalid_keys, ) # loop over clauses for clause in step_selection: subset = clause_to_subset(graph, clause) if len(subset) == 0: raise DagsterInvalidSubsetError( "No qualified steps to execute found for step_selection={requested}".format( requested=step_selection ), ) steps_set.update(subset) return frozenset(steps_set)
import re import sys from collections import defaultdict from typing import TYPE_CHECKING, AbstractSet, List, NamedTuple, Optional from dagster.core.definitions.dependency import DependencyStructure, Node from dagster.core.errors import DagsterExecutionStepNotFoundError, DagsterInvalidSubsetError from dagster.utils import check MAX_NUM = sys.maxsize if TYPE_CHECKING: from dagster.core.execution.plan.plan import ExecutionPlan class OpSelectionData( NamedTuple( "_OpSelectionData", [ ("resolved_op_selection", Optional[AbstractSet[str]]), ("ignored_solids", List[Node]), ], ) ): """The data about op selection. Attributes: resolved_op_selection (Optional[AbstractSet[str]])): The names of selected ops. ignored_solids (List[Node]): The solids in the original full graph but outside the current selection. This is used in run config resolution to handle unsatisfied inputs correctly. """ def __new__(cls, resolved_op_selection=None, ignored_solids=None): return super(OpSelectionData, cls).__new__( cls, resolved_op_selection=check.opt_set_param( resolved_op_selection, "resolved_op_selection", str ), ignored_solids=check.opt_list_param(ignored_solids, "ignored_solids", Node), ) def generate_dep_graph(pipeline_def): """'pipeline to dependency graph. It currently only supports top-level solids. Args: pipeline (PipelineDefinition): The pipeline to execute. Returns: graph (Dict[str, Dict[str, Set[str]]]): the input and output dependency graph. e.g. ``` { "upstream": { "solid_one_1": set(), "solid_one_2": set(), "solid_two": {"solid_one_1", "solid_one_2"}, "solid_three": {"solid_two"}, }, "downstream": { "solid_one_1": {"solid_two"}, "solid_one_2": {"solid_two"}, "solid_two": {"solid_three"}, "solid_three": set(), }, } ``` """ dependency_structure = check.inst_param( pipeline_def.dependency_structure, "dependency_structure", DependencyStructure ) item_names = [i.name for i in pipeline_def.solids] # defaultdict isn't appropriate because we also want to include items without dependencies graph = {"upstream": {}, "downstream": {}} for item_name in item_names: graph["upstream"][item_name] = set() upstream_dep = dependency_structure.input_to_upstream_outputs_for_solid(item_name) for upstreams in upstream_dep.values(): for up in upstreams: graph["upstream"][item_name].add(up.solid_name) graph["downstream"][item_name] = set() downstream_dep = dependency_structure.output_to_downstream_inputs_for_solid(item_name) for downstreams in downstream_dep.values(): for down in downstreams: graph["downstream"][item_name].add(down.solid_name) return graph class Traverser: def __init__(self, graph): self.graph = graph def _fetch_items(self, item_name, depth, direction): dep_graph = self.graph[direction] stack = [item_name] result = set() curr_depth = 0 while stack: # stop when reach the given depth if curr_depth >= depth: break curr_level_len = len(stack) while stack and curr_level_len > 0: curr_item = stack.pop() for item in dep_graph.get(curr_item, set()): curr_level_len -= 1 if item not in result: stack.append(item) result.add(item) curr_depth += 1 return result def fetch_upstream(self, item_name, depth): # return a set of ancestors of the given item, up to the given depth return self._fetch_items(item_name, depth, "upstream") def fetch_downstream(self, item_name, depth): # return a set of descendants of the given item, down to the given depth return self._fetch_items(item_name, depth, "downstream") def parse_clause(clause): def _get_depth(part): if part == "": return 0 if "*" in part: return MAX_NUM if set(part) == set("+"): return len(part) return None token_matching = re.compile(r"^(\*?\+*)?([.\w\d\[\]?_-]+)(\+*\*?)?$").search(clause.strip()) # return None if query is invalid parts = token_matching.groups() if token_matching is not None else [] if len(parts) != 3: return None ancestor_part, item_name, descendant_part = parts up_depth = _get_depth(ancestor_part) down_depth = _get_depth(descendant_part) return (up_depth, item_name, down_depth) def parse_items_from_selection(selection): items = [] for clause in selection: parts = parse_clause(clause) if parts is None: continue _u, item, _d = parts items.append(item) return items def clause_to_subset(graph, clause): """Take a selection query and return a list of the selected and qualified items. Args: graph (Dict[str, Dict[str, Set[str]]]): the input and output dependency graph. clause (str): the subselection query in model selection syntax, e.g. "*some_solid+" will select all of some_solid's upstream dependencies and its direct downstream dependecies. Returns: subset_list (List[str]): a list of selected and qualified solid names, empty if input is invalid. """ # parse cluase if not isinstance(clause, str): return [] parts = parse_clause(clause) if parts is None: return [] up_depth, item_name, down_depth = parts # item_name invalid if item_name not in graph["upstream"]: return [] subset_list = [] traverser = Traverser(graph=graph) subset_list.append(item_name) # traverse graph to get up/downsteam items subset_list += traverser.fetch_upstream(item_name, up_depth) subset_list += traverser.fetch_downstream(item_name, down_depth) return subset_list def parse_solid_selection(pipeline_def, solid_selection): """Take pipeline definition and a list of solid selection queries (inlcuding names of solid invocations. See syntax examples below) and return a set of the qualified solid names. It currently only supports top-level solids. Query syntax examples: - "some_solid": select "some_solid" itself - "*some_solid": select "some_solid" and all ancestors (upstream dependencies) - "some_solid*": select "some_solid" and all descendants (downstream dependencies) - "*some_solid*": select "some_solid" and all of its ancestors and descendants - "+some_solid": select "some_solid" and its ancestors at 1 level up - "some_solid+++": select "some_solid" and its descendants within 3 levels down Note: - If one of the query clauses is invalid, we will skip that one and continue to parse the valid ones. Args: pipeline_def (PipelineDefinition): the pipeline to execute. solid_selection (List[str]): a list of the solid selection queries (including single solid names) to execute. Returns: FrozenSet[str]: a frozenset of qualified deduplicated solid names, empty if no qualified subset selected. """ check.list_param(solid_selection, "solid_selection", of_type=str) # special case: select all if len(solid_selection) == 1 and solid_selection[0] == "*": return frozenset(pipeline_def.graph.node_names()) graph = generate_dep_graph(pipeline_def) solids_set = set() # loop over clauses for clause in solid_selection: subset = clause_to_subset(graph, clause) if len(subset) == 0: raise DagsterInvalidSubsetError( "No qualified solids to execute found for solid_selection={requested}".format( requested=solid_selection ) ) solids_set.update(subset) return frozenset(solids_set) def parse_step_selection(step_deps, step_selection): """Take the dependency dictionary generated while building execution plan and a list of step key selection queries and return a set of the qualified step keys. It currently only supports top-level solids. Args: step_deps (Dict[str, Set[str]]): a dictionary of execution step dependency where the key is a step key and the value is a set of direct upstream dependency of the step. step_selection (List[str]): a list of the step key selection queries (including single step key) to execute. Returns: FrozenSet[str]: a frozenset of qualified deduplicated solid names, empty if no qualified subset selected. """ check.list_param(step_selection, "step_selection", of_type=str) # reverse step_deps to get the downstream_deps # make sure we have all items as keys, including the ones without downstream dependencies downstream_deps = defaultdict(set, {k: set() for k in step_deps.keys()}) for downstream_key, upstream_keys in step_deps.items(): for step_key in upstream_keys: downstream_deps[step_key].add(downstream_key) # generate dep graph graph = {"upstream": step_deps, "downstream": downstream_deps} steps_set = set() step_keys = parse_items_from_selection(step_selection) invalid_keys = [key for key in step_keys if key not in step_deps] if invalid_keys: raise DagsterExecutionStepNotFoundError( f"Step selection refers to unknown step{'s' if len(invalid_keys)> 1 else ''}: {', '.join(invalid_keys)}", step_keys=invalid_keys, ) # loop over clauses for clause in step_selection: subset = clause_to_subset(graph, clause) if len(subset) == 0: raise DagsterInvalidSubsetError( "No qualified steps to execute found for step_selection={requested}".format( requested=step_selection ), ) steps_set.update(subset) return frozenset(steps_set)
# makes a string of 50 equals signs for a line break separator = "=" * 50 if True: print("hi") else: print("no") # creates a 2d list with 10 rows car_park = [[] for i in range(10)] # filling the car park for i in range(10): for j in range(6): car_park[i].append("E") # e stands for empty # creates the interface for allowing the user to leave def leave_menu(): print(separator) print("Do you want to try again or exit to main menu?") print("1 = Try again.") print("2 = Exit to main menu.") print(separator) exit_choice = input(">>> ") if exit_choice == "2": return True else: return False # goes through each index of the park and makes it "e" def empty_park(): for i in range(10): for j in range(6): car_park[i][j] = "E" print(separator) print("Success, all spaces now are empty.") # allows the user to remove a car based on its plate def remove_car(): removed = False while not(removed): print(separator) print("What is the number plate of the car?") print(separator) plate_number = input(">>> ") for index_i, i in enumerate(car_park): for index_j, j in enumerate(i): if j == plate_number: car_park[index_i][index_j] = "E"; removed = True if not(removed): print(separator) print(f"Could not find car with registration '{plate_number}', please try again.") if leave_menu(): break else: continue else: print(separator) print(f"Congratulations car with registration '{plate_number}' has\nsuccessfully been removed.") # allows the user to add a number plate to the garage def park_car(): while True: print(separator) print("What row are you parking in?") print("Rows must be between 1 and 10.") print(separator) row = input(">>> ") print(separator) print("What space are you parking in?") print("Spaces must be between 1 and 6.") print(separator) column = input(">>> ") print(separator) print("What is your registration number?") print(separator) plate_number = input(">>> ") print(separator) print(f"Car with registration '{plate_number}' has\nsuccessfully been parked in row {row}, column {column}.") try: row = int(row) column = int(column) column_arr = [] car_park[row - 1][column - 1] = plate_number for c, i in enumerate(car_park): column_arr.append(car_park[c][column - 1]) max_length = len(max(column_arr, key=len)) for c, i in enumerate(car_park): i[column - 1] = i[column - 1] + (" " * (max_length - len(i[column - 1]))) break except: print(separator) print(f"Invalid input detected, please try again.") if leave_menu(): break else: continue # displays the entire garage in a neat format for the user def show_park(): print(separator) print("Parking Garage: ") print(" ") for c, i in enumerate(car_park): print(f"[ {" ".join(i)} ]") print("\n* E stands for empty.") while True: print(separator) print("What would you like to do?") print("1 = Set all spaces to empty.") print("2 = Park a car.") print("3 = Remove a car.") print("4 = Display the parking grid.") print("5 = Quit.") print(separator) option_chosen = input(">>> ") if option_chosen == "1": empty_park() elif option_chosen == "2": park_car() elif option_chosen == "3": remove_car() elif option_chosen == "4": show_park() elif option_chosen == "5": print(separator) print("Success, program has quit.") print(separator) quit() else: print(separator) print("Option not recognised, please try again")
# makes a string of 50 equals signs for a line break separator = "=" * 50 if True: print("hi") else: print("no") # creates a 2d list with 10 rows car_park = [[] for i in range(10)] # filling the car park for i in range(10): for j in range(6): car_park[i].append("E") # e stands for empty # creates the interface for allowing the user to leave def leave_menu(): print(separator) print("Do you want to try again or exit to main menu?") print("1 = Try again.") print("2 = Exit to main menu.") print(separator) exit_choice = input(">>> ") if exit_choice == "2": return True else: return False # goes through each index of the park and makes it "e" def empty_park(): for i in range(10): for j in range(6): car_park[i][j] = "E" print(separator) print("Success, all spaces now are empty.") # allows the user to remove a car based on its plate def remove_car(): removed = False while not(removed): print(separator) print("What is the number plate of the car?") print(separator) plate_number = input(">>> ") for index_i, i in enumerate(car_park): for index_j, j in enumerate(i): if j == plate_number: car_park[index_i][index_j] = "E"; removed = True if not(removed): print(separator) print(f"Could not find car with registration '{plate_number}', please try again.") if leave_menu(): break else: continue else: print(separator) print(f"Congratulations car with registration '{plate_number}' has\nsuccessfully been removed.") # allows the user to add a number plate to the garage def park_car(): while True: print(separator) print("What row are you parking in?") print("Rows must be between 1 and 10.") print(separator) row = input(">>> ") print(separator) print("What space are you parking in?") print("Spaces must be between 1 and 6.") print(separator) column = input(">>> ") print(separator) print("What is your registration number?") print(separator) plate_number = input(">>> ") print(separator) print(f"Car with registration '{plate_number}' has\nsuccessfully been parked in row {row}, column {column}.") try: row = int(row) column = int(column) column_arr = [] car_park[row - 1][column - 1] = plate_number for c, i in enumerate(car_park): column_arr.append(car_park[c][column - 1]) max_length = len(max(column_arr, key=len)) for c, i in enumerate(car_park): i[column - 1] = i[column - 1] + (" " * (max_length - len(i[column - 1]))) break except: print(separator) print(f"Invalid input detected, please try again.") if leave_menu(): break else: continue # displays the entire garage in a neat format for the user def show_park(): print(separator) print("Parking Garage: ") print(" ") for c, i in enumerate(car_park): print(f"[ {' '.join(i)} ]") print("\n* E stands for empty.") while True: print(separator) print("What would you like to do?") print("1 = Set all spaces to empty.") print("2 = Park a car.") print("3 = Remove a car.") print("4 = Display the parking grid.") print("5 = Quit.") print(separator) option_chosen = input(">>> ") if option_chosen == "1": empty_park() elif option_chosen == "2": park_car() elif option_chosen == "3": remove_car() elif option_chosen == "4": show_park() elif option_chosen == "5": print(separator) print("Success, program has quit.") print(separator) quit() else: print(separator) print("Option not recognised, please try again")
import numpy as np import cv2 import random import warnings import scipy from scipy.linalg.basic import solve_circulant import skimage import skimage.transform from distutils.version import LooseVersion import torch import math import json from torch.functional import Tensor np.random.seed(42) def load_points_dataset(f_p): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] file = line[3] first_point = None second_point = None if label == "head": first_point = (int(line[1]), int(line[2])) elif label == "tail": second_point = (int(line[1]), int(line[2])) i += 1 if i < len(all_lines): line2 = all_lines[i].split(",") if line2[3] == file: if line2[0] == "head": first_point = (int(line2[1]), int(line2[2])) elif line2[0] == "tail": second_point = (int(line2[1]), int(line2[2])) i += 1 if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") points[file].append([first_point, second_point]) else: points[file] = [[first_point, second_point]] return points def load_points_dataset_2(f_p,label_name=["head","tail"]): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] file = line[3] first_point = None second_point = None if label == label_name[0]: first_point = (int(line[1]), int(line[2])) elif label == label_name[1]: second_point = (int(line[1]), int(line[2])) i += 1 if i < len(all_lines): line2 = all_lines[i].split(",") if line2[3] == file: if line2[0] == label_name[0]: first_point = (int(line2[1]), int(line2[2])) elif line2[0] == label_name[1]: second_point = (int(line2[1]), int(line2[2])) i += 1 if not first_point and not second_point: continue if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") points[file].append([first_point, second_point]) else: points[file] = [[first_point, second_point]] return points def load_class_dataset(f_p,label_name=["rating","neck"]): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] splitted_labels=label.split("_") file = line[3] coords= None if splitted_labels[0] in label_name: coords = (int(line[1]), int(line[2])) i += 1 if coords is None: continue if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") if splitted_labels[0] in points[file]: points[file][splitted_labels[0]].append([coords,int(splitted_labels[1])]) else: points[file][splitted_labels[0]]=[[coords,int(splitted_labels[1])]] else: points[file]={splitted_labels[0]:[[coords, int(splitted_labels[1])]]} return points def load_segmentation_dataset(f_p,label_names=None): """" Returns: [dict]: Dictionary of list with names """ data=load_json(f_p) cat_map={} for cat in data["categories"]: if cat["name"] in label_names: cat_map[cat['id']]=cat["name"] image_map={} for cat in data["images"]: image_map[cat['id']]=cat["file_name"] annos={} for d in data["annotations"]: tmp=[] seg=d["segmentation"][0] for i in range(0,len(seg)-1,2): tmp.append([seg[i],seg[i+1]]) if image_map[d["image_id"]] not in annos: annos[image_map[d["image_id"]]]=[{"class_id":cat_map[d["category_id"]],"annotation":tmp}] else: annos[image_map[d["image_id"]]].append({"class_id":cat_map[d["category_id"]],"annotation":tmp}) return annos def load_backbone(filename): with open(filename) as f: back_annotation = json.load(f) return back_annotation def load_json(filename): with open(filename) as f: annotation = json.load(f) return annotation def extract_bboxes(mask): """Compute bounding boxes from masks. mask: [height, width, num_instances]. Mask pixels are either 1 or 0. Returns: bbox array [num_instances, (y1, x1, y2, x2)]. """ #print(np.max(mask)) #print(np.min(mask)) boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32) for i in range(mask.shape[-1]): m = mask[:, :, i] # Bounding box. horizontal_indicies = np.where(np.any(m, axis=0))[0] vertical_indicies = np.where(np.any(m, axis=1))[0] if horizontal_indicies.shape[0]: x1, x2 = horizontal_indicies[[0, -1]] y1, y2 = vertical_indicies[[0, -1]] # x2 and y2 should not be part of the box. Increment by 1. x2 += 1 y2 += 1 else: # No mask for this instance. Might happen due to # resizing or cropping. Set bbox to zeros x1, x2, y1, y2 = 0, 0, 0, 0 boxes[i] = np.array([x1,y1,x2,y2]) return boxes.astype(np.int32) def resize( image, output_shape, order=1, mode="constant", cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None, ): """A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the right parameters. The right parameters depend on the version of skimage. This solves the problem by using different parameters per version. And it provides a central place to control resizing defaults. """ if LooseVersion(skimage.__version__) >= LooseVersion("0.14"): # New in 0.14: anti_aliasing. Default it to False for backward # compatibility with skimage 0.13. return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, anti_aliasing=anti_aliasing, anti_aliasing_sigma=anti_aliasing_sigma, ) else: return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, ) def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"): """Resizes an image keeping the aspect ratio unchanged. min_dim: if provided, resizes the image such that it's smaller dimension == min_dim max_dim: if provided, ensures that the image longest side doesn't exceed this value. min_scale: if provided, ensure that the image is scaled up by at least this percent even if min_dim doesn't require it. mode: Resizing mode. none: No resizing. Return the image unchanged. square: Resize and pad with zeros to get a square image of size [max_dim, max_dim]. pad64: Pads width and height with zeros to make them multiples of 64. If min_dim or min_scale are provided, it scales the image up before padding. max_dim is ignored in this mode. The multiple of 64 is needed to ensure smooth scaling of feature maps up and down the 6 levels of the FPN pyramid (2**6=64). crop: Picks random crops from the image. First, scales the image based on min_dim and min_scale, then picks a random crop of size min_dim x min_dim. Can be used in training only. max_dim is not used in this mode. Returns: image: the resized image window: (y1, x1, y2, x2). If max_dim is provided, padding might be inserted in the returned image. If so, this window is the coordinates of the image part of the full image (excluding the padding). The x2, y2 pixels are not included. scale: The scale factor used to resize the image padding: Padding added to the image [(top, bottom), (left, right), (0, 0)] """ # Keep track of image dtype and return results in the same dtype image_dtype = image.dtype # Default window (y1, x1, y2, x2) and default scale == 1. h, w = image.shape[:2] window = (0, 0, h, w) scale = 1 padding = [(0, 0), (0, 0), (0, 0)] crop = None if mode == "none": return image, window, scale, padding, crop # Scale? if min_dim: # Scale up but not down scale = max(1, min_dim / min(h, w)) if min_scale and scale < min_scale: scale = min_scale # Does it exceed max dim? if max_dim and mode == "square": image_max = max(h, w) if round(image_max * scale) > max_dim: scale = max_dim / image_max # Resize image using bilinear interpolation if scale != 1: image = resize(image, (round(h * scale), round(w * scale)), preserve_range=True) # Need padding or cropping? if mode == "square": # Get new height and width h, w = image.shape[:2] top_pad = (max_dim - h) // 2 bottom_pad = max_dim - h - top_pad left_pad = (max_dim - w) // 2 right_pad = max_dim - w - left_pad padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode="constant", constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "pad64": h, w = image.shape[:2] # Both sides must be divisible by 64 assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64" # Height if h % 64 > 0: max_h = h - (h % 64) + 64 top_pad = (max_h - h) // 2 bottom_pad = max_h - h - top_pad else: top_pad = bottom_pad = 0 # Width if w % 64 > 0: max_w = w - (w % 64) + 64 left_pad = (max_w - w) // 2 right_pad = max_w - w - left_pad else: left_pad = right_pad = 0 padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode="constant", constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "crop": # Pick a random crop h, w = image.shape[:2] y = random.randint(0, (h - min_dim)) x = random.randint(0, (w - min_dim)) crop = (y, x, min_dim, min_dim) image = image[y : y + min_dim, x : x + min_dim] window = (0, 0, min_dim, min_dim) else: raise Exception("Mode {} not supported".format(mode)) return image.astype(image_dtype), window, scale, padding, crop def resize_mask(mask, scale, padding, crop=None): """Resizes a mask using the given scale and padding. Typically, you get the scale and padding from resize_image() to ensure both, the image and the mask, are resized consistently. scale: mask scaling factor padding: Padding to add to the mask in the form [(top, bottom), (left, right), (0, 0)] """ # Suppress warning from scipy 0.13.0, the output shape of zoom() is # calculated with round() instead of int() with warnings.catch_warnings(): warnings.simplefilter("ignore") mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0) if crop is not None: y, x, h, w = crop mask = mask[y : y + h, x : x + w] else: mask = np.pad(mask, padding, mode="constant", constant_values=0) return mask def vis_mask(vis_img,indicies,color=(255,120,0)): for j in range(len(indicies[0])): x = indicies[1][j] y = indicies[0][j] # viusalize masks cv2.circle(vis_img, (x, y), 1, color, 1) def resize_images_cv(img): scale_percent = 40 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) return resized def write_text(image,text,point=(0,0),color=(255,0,0)): # font font = cv2.FONT_HERSHEY_SIMPLEX # fontScale fontScale = 1 # Line thickness of 2 px thickness = 3 # Using cv2.putText() method image = cv2.putText(image, text, point, font, fontScale, color, thickness, cv2.LINE_AA) return image def vis_data(image, masks, bboxs,classes,keypoints=None,**kwargs): vis_img = (image.detach().numpy()*255).astype(np.uint8) vis_img=np.moveaxis(vis_img, 0, -1) vis_img=vis_img.copy() class_color={i:[random.uniform(0,255) for _ in range(3)] for i in np.unique(classes)} # offset for drawing text off_x=20 off_y=50 for i in range(masks.shape[0]): mask = masks[i][...,None].detach().numpy() bbox = np.int0(bboxs[i].detach().numpy().copy()) indicies = np.where(mask >= 0.5) vis_mask(vis_img,indicies=indicies,color=class_color[classes[i]]) # Visualize bounding box cv2.rectangle(vis_img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), class_color[classes[i]], 2) # write class name write_text(vis_img,classes[i],((bbox[0], bbox[1]))) # Visualize segm classes if "other_masks" in kwargs and "seg_labels" in kwargs: for j,k in enumerate(kwargs["other_masks"].keys(),start=1): if classes[i] in kwargs["seg_labels"][j]: m=kwargs["other_masks"][k][i][...,None].detach().numpy() indicies = np.where(m >= 0.1) vis_mask(vis_img,indicies=indicies,color=(0,0,255)) #other_mask_id+=1 ## Visualize keypoints if "kp_labels" in kwargs and keypoints is not None: if classes[i] in kwargs["kp_labels"]: keypoint = np.int0(keypoints[i].detach().numpy()) # Visualize Keypoints cv2.circle(vis_img, (keypoint[0][0], keypoint[0][1]), 1, (0, 255, 255), 20) write_text(vis_img,"Head",(keypoint[0][0]+off_x, keypoint[0][1]+off_y)) cv2.circle(vis_img, (keypoint[1][0], keypoint[1][1]), 1, (0, 255, 255), 20) write_text(vis_img,"Tail",(keypoint[1][0]+off_x, keypoint[1][1]+off_y)) # visualize classification if "clas" in kwargs and "clas_labels" in kwargs: for j,k in enumerate(kwargs["clas"].keys(),start=0): if classes[i] in kwargs["clas_labels"][j]: cl=kwargs["clas"][k][i].cpu().item() point=(bbox[0]+(bbox[2]-bbox[0])//2+j*off_x,bbox[1]+(bbox[3]-bbox[1])//2+j*off_y) write_text(vis_img,f"{k}: {cl}",point=point,color=(0,0,255)) vis_img=resize_images_cv(vis_img) #if"" kwargs["DEBUG"]: if "epoch" in kwargs: cv2.imwrite("/home/ec2-user/SageMaker/SMN/res_images/"+f"{kwargs["epoch"]}"+".png",vis_img) #cv2.imshow("Input and labels", vis_img) #cv2.waitKey(0) def resize_points(points, scale, window): # window: (y1, x1, y2, x2) scaled_points = [] for i in range(len(points)): two_point = np.array(points[i]) two_point = scale * two_point two_point[0][0] = two_point[0][0] + window[1] two_point[0][1] = two_point[0][1] + window[0] two_point[1][0] = two_point[1][0] + window[1] two_point[1][1] = two_point[1][1] + window[0] scaled_points.append(two_point) return np.int0(scaled_points) def generate_anchors_tensor(scales, ratios, shape, feature_stride, anchor_stride,device="cpu"): """ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_stride: Stride of anchors on the feature map. For example, if the value is 2 then generate anchors for every other feature map pixel. """ # Get all combinations of scales and ratios scales, ratios = np.meshgrid(np.array(scales), np.array(ratios)) scales = scales.flatten() ratios = ratios.flatten() # Enumerate heights and widths from scales and ratios heights = scales / np.sqrt(ratios) widths = scales * np.sqrt(ratios) # Enumerate shifts in feature space shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y) # Enumerate combinations of shifts, widths, and heights box_widths, box_centers_x = np.meshgrid(widths, shifts_x) box_heights, box_centers_y = np.meshgrid(heights, shifts_y) # Reshape to get a list of (y, x) and a list of (h, w) box_centers = np.stack([box_centers_y, box_centers_x], axis=2).reshape([-1, 2]) box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2]) # Convert to corner coordinates (y1, x1, y2, x2) boxes = np.concatenate( [box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], axis=1 ) boxes=torch.tensor(boxes,dtype=torch.float32) return boxes def visualize_anchors( img, anchors, backbone_shapes, RPN_ANCHOR_RATIOS, RPN_ANCHOR_STRIDE, RPN_ANCHOR_SCALES, ): vis_img = img.copy() num_levels = len(backbone_shapes) anchors_per_cell = len(RPN_ANCHOR_RATIOS) print("Anchors Count: ", anchors.shape[0]) print("Scales: ", RPN_ANCHOR_SCALES) print("ratios: ", RPN_ANCHOR_RATIOS) print("Anchors per Cell: ", anchors_per_cell) print("Levels: ", num_levels) anchors_per_level = [] for l in range(num_levels): num_cells = backbone_shapes[l][0] * backbone_shapes[l][1] anchors_per_level.append(anchors_per_cell * num_cells // RPN_ANCHOR_STRIDE ** 2) print("Anchors in Level {}: {}".format(l, anchors_per_level[l])) for level in range(num_levels): colors = [[0, 255, 0]] # Compute the index of the anchors at the center of the image level_start = sum( anchors_per_level[:level] ) # sum of anchors of previous levels level_anchors = anchors[level_start : level_start + anchors_per_level[level]] print( "Level {}. Anchors: {:6} Feature map Shape: {}".format( level, level_anchors.shape[0], backbone_shapes[level] ) ) center_cell = np.array(backbone_shapes[level]) // 2 center_cell_index = center_cell[0] * backbone_shapes[level][1] + center_cell[1] level_center = center_cell_index * anchors_per_cell center_anchor = anchors_per_cell * ( (center_cell[0] * backbone_shapes[level][1] / RPN_ANCHOR_STRIDE ** 2) + center_cell[1] / RPN_ANCHOR_STRIDE ) level_center = int(center_anchor) # Draw anchors. Brightness show the order in the array, dark to bright. for i, rect in enumerate( level_anchors[level_center : level_center + anchors_per_cell] ): y1, x1, y2, x2 = rect cv2.rectangle( vis_img, (int(x1), int(y1)), (int(x2), int(y2)), colors[level], 2 ) cv2.imshow("Center Anchor Boxes", vis_img) cv2.waitKey(0) def generate_pyramid_anchors_tensor(scales, ratios, feature_shapes, feature_strides, anchor_stride,device="cpu"): """Generate anchors at different levels of a feature pyramid. Each scale is associated with a level of the pyramid, but each ratio is used in all levels of the pyramid. Returns: anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted with the same order of the given scales. So, anchors of scale[0] come first, then anchors of scale[1], and so on. """ # Anchors # [anchor_count, (y1, x1, y2, x2)] anchors = [] for i in range(len(scales)): anchors.append(generate_anchors_tensor(scales[i], ratios, feature_shapes[i], feature_strides[i], anchor_stride,device=device)) return torch.cat(anchors, axis=0).to(device=device) def compute_iou_tensor(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas y1 = torch.maximum(box[0], boxes[:, 0]) y2 = torch.minimum(box[2], boxes[:, 2]) x1 = torch.maximum(box[1], boxes[:, 1]) x2 = torch.minimum(box[3], boxes[:, 3]) intersection = torch.maximum(x2 - x1, torch.tensor(0)) * torch.maximum(y2 - y1, torch.tensor(0)) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_overlaps_tesnor(boxes1, boxes2,device="cpu"): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. For better performance, pass the largest set first and the smaller second. """ # Areas of anchors and GT boxes area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) # Compute overlaps to generate matrix [boxes1 count, boxes2 count] # Each cell contains the IoU value. overlaps = torch.zeros((boxes1.shape[0], boxes2.shape[0])).to(device=device) for i in range(overlaps.shape[1]): box2 = boxes2[i] overlaps[:, i] = compute_iou_tensor(box2, boxes1, area2[i], area1) return overlaps def apply_box_deltas_tesnor(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box. deltas: [N, (dy, dx, log(dh), log(dw))] """ # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] center_y = boxes[:, 0] + 0.5 * height center_x = boxes[:, 1] + 0.5 * width # Apply deltas center_y += deltas[:, 0] * height center_x += deltas[:, 1] * width height *= torch.exp(deltas[:, 2]) width *= torch.exp(deltas[:, 3]) # Convert back to y1, x1, y2, x2 y1 = center_y - 0.5 * height x1 = center_x - 0.5 * width y2 = y1 + height x2 = x1 + width return torch.stack([y1, x1, y2, x2], axis=1) def vis_anchors_refined_anchors_(img, anchors, refined_anchors): vis_img = img.copy() for i, rect in enumerate(anchors): y1, x1, y2, x2 = rect cv2.rectangle(vis_img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2) y1, x1, y2, x2 = refined_anchors[i] cv2.rectangle(vis_img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) break cv2.imshow("Matched Anchor Boxes", vis_img) cv2.waitKey(0) def build_rpn_targets_tensor(anchors, gt_boxes, config): """Given the anchors and GT boxes, compute overlaps and identify positive anchors and deltas to refine them to match their corresponding GT boxes. anchors: [num_anchors, (y1, x1, y2, x2)] gt_class_ids: [num_gt_boxes] Integer class IDs. gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)] Returns: rpn_match: [N] (int32) matches between anchors and GT boxes. 1 = positive anchor, -1 = negative anchor, 0 = neutral rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas. """ # RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral rpn_match = torch.zeros([anchors.shape[0]], dtype=torch.int32).to(device=config.DEVICE) # RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))] rpn_bbox = torch.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4)).to(device=config.DEVICE) no_crowd_bool = torch.ones([anchors.shape[0]], dtype=torch.bool).to(device=config.DEVICE) # Compute overlaps [num_anchors, num_gt_boxes] overlaps = compute_overlaps_tesnor(anchors, gt_boxes,config.DEVICE) # Match anchors to GT Boxes # If an anchor overlaps a GT box with IoU >= 0.7 then it's positive. # If an anchor overlaps a GT box with IoU < 0.3 then it's negative. # Neutral anchors are those that don't match the conditions above, # and they don't influence the loss function. # However, don't keep any GT box unmatched (rare, but happens). Instead, # match it to the closest anchor (even if its max IoU is < 0.3). # # 1. Set negative anchors first. They get overwritten below if a GT box is # matched to them. Skip boxes in crowd areas. anchor_iou_argmax = torch.argmax(overlaps, axis=1) anchor_iou_max = overlaps[torch.arange(overlaps.shape[0]), anchor_iou_argmax] rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1 # 2. Set an anchor for each GT box (regardless of IoU value). # If multiple anchors have the same IoU match all of them # original was argwhere # gt_iou_argmax = torch.where(torch.tensor(overlaps == torch.max(overlaps, axis=0)))[:, 0] a = torch.max(overlaps, axis=0)[0] gt_iou_argmax = torch.where(overlaps == a)[0] rpn_match[gt_iou_argmax] = 1 # 3. Set anchors with high overlap as positive. rpn_match[anchor_iou_max >= 0.7] = 1 # Subsample to balance positive and negative anchors # Don't let positives be more than half the anchors ids = torch.where(rpn_match == 1)[0] extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2) if extra > 0: # Reset the extra ones to neutral unif = torch.ones(ids.shape[0]).to(device=config.DEVICE) idx = unif.multinomial(extra, replacement=False) ids = ids[idx] # ids = np.random.choice(ids, extra, replace=False) rpn_match[ids] = 0 # Same for negative proposals ids = torch.where(rpn_match == -1)[0] extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE - torch.sum(rpn_match == 1)) if extra > 0: # Rest the extra ones to neutral # ids = np.random.choice(ids, extra, replace=False) unif = torch.ones(ids.shape[0]).to(device=config.DEVICE) idx = unif.multinomial(extra, replacement=False) ids = ids[idx] rpn_match[ids] = 0 # For positive anchors, compute shift and scale needed to transform them # to match the corresponding GT boxes. ids = torch.where(rpn_match == 1)[0] ix = 0 # index into rpn_bbox for i, a in zip(ids, anchors[ids]): # Closest gt box (it might have IoU < 0.7) gt = gt_boxes[anchor_iou_argmax[i]] # Convert coordinates to center plus width/height. # GT Box gt_h = gt[2] - gt[0] gt_w = gt[3] - gt[1] gt_center_y = gt[0] + 0.5 * gt_h gt_center_x = gt[1] + 0.5 * gt_w # Anchor a_h = a[2] - a[0] a_w = a[3] - a[1] a_center_y = a[0] + 0.5 * a_h a_center_x = a[1] + 0.5 * a_w # Compute the bbox refinement that the RPN should predict. rpn_bbox[ix] = torch.tensor( [ (gt_center_y - a_center_y) / a_h, (gt_center_x - a_center_x) / a_w, torch.log(gt_h / a_h), torch.log(gt_w / a_w), ] ) # Normalize #rpn_bbox[ix] /= torch.tensor(config.RPN_BBOX_STD_DEV, dtype=torch.float32).to(device=config.DEVICE) ix += 1 return rpn_match, rpn_bbox def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is assumed to be outside the box. """ box = box.type(torch.float32) gt_box = gt_box.type(torch.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = torch.log(gt_height / height) dw = torch.log(gt_width / width) return torch.stack([dy, dx, dh, dw], axis=1) def process_box(box, score, image_shape, min_size): """ Clip boxes in the image size and remove boxes which are too small. """ box[:, [0, 2]] = box[:, [0, 2]].clamp(0, image_shape[0]) box[:, [1, 3]] = box[:, [1, 3]].clamp(0, image_shape[1]) w, h = box[:, 2] - box[:, 0], box[:, 3] - box[:, 1] keep = torch.where((w >= min_size) & (h >= min_size))[0] box, score = box[keep], score[keep] return box, score def roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio ): if torch.__version__ >= "1.5.0": return torch.ops.torchvision.roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, False, ) else: return torch.ops.torchvision.roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio ) class RoIAlign: """ Performs Region of Interest (RoI) Align operator described in Mask R-CNN """ def __init__(self, output_size, sampling_ratio): """ Arguments: output_size (Tuple[int, int]): the size of the output after the cropping is performed, as (height, width) sampling_ratio (int): number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height). Default: -1 """ self.output_size = output_size self.sampling_ratio = sampling_ratio self.spatial_scale = None def setup_scale(self, feature_shape, image_shape): if self.spatial_scale is not None: return possible_scales = [] for s1, s2 in zip(feature_shape, image_shape): scale = 2 ** int(math.log2(s1 / s2)) possible_scales.append(scale) assert possible_scales[0] == possible_scales[1] self.spatial_scale = possible_scales[0] def __call__(self, feature, proposal, image_shape): """ Arguments: feature (Tensor[N, C, H, W]) proposal (Tensor[K, 4]) image_shape (Torch.Size([H, W])) Returns: output (Tensor[K, C, self.output_size[0], self.output_size[1]]) """ idx = proposal.new_full((proposal.shape[0], 1), 0) roi = torch.cat((idx, proposal), dim=1) self.setup_scale(feature.shape[-2:], image_shape) return roi_align( feature.to(roi), roi, self.spatial_scale, self.output_size[0], self.output_size[1], self.sampling_ratio, ) class Matcher: def __init__(self, high_threshold, low_threshold, allow_low_quality_matches=False): self.high_threshold = high_threshold self.low_threshold = low_threshold self.allow_low_quality_matches = allow_low_quality_matches def __call__(self, iou): """ Arguments: iou (Tensor[M, N]): containing the pairwise quality between M ground-truth boxes and N predicted boxes. Returns: label (Tensor[N]): positive (1) or negative (0) label for each predicted box, -1 means ignoring this box. matched_idx (Tensor[N]): indices of gt box matched by each predicted box. """ value, matched_idx = iou.max(dim=0) label = torch.full((iou.shape[1],), -1, dtype=torch.float, device=iou.device) label[value >= self.high_threshold] = 1 label[value < self.low_threshold] = 0 if self.allow_low_quality_matches: highest_quality = iou.max(dim=1)[0] gt_pred_pairs = torch.where(iou == highest_quality[:, None])[1] label[gt_pred_pairs] = 1 return label, matched_idx class BalancedPositiveNegativeSampler: def __init__(self, num_samples, positive_fraction): self.num_samples = num_samples self.positive_fraction = positive_fraction def __call__(self, label): positive = torch.where(label == 1)[0] negative = torch.where(label == 0)[0] num_pos = int(self.num_samples * self.positive_fraction) num_pos = min(positive.numel(), num_pos) num_neg = self.num_samples - num_pos num_neg = min(negative.numel(), num_neg) pos_perm = torch.randperm(positive.numel(), device=positive.device)[:num_pos] neg_perm = torch.randperm(negative.numel(), device=negative.device)[:num_neg] pos_idx = positive[pos_perm] neg_idx = negative[neg_perm] return pos_idx, neg_idx def visualize_inference(in_img, inv_normalize,results): vis_img = in_img.clone() vis_img = (inv_normalize(vis_img).data.numpy() * 255).astype(np.uint8) vis_img = np.ascontiguousarray(np.moveaxis(vis_img, 0, -1)) boxes=np.int0(results["boxes"]) labels=results["labels"] scores=results["scores"] print(f"Labels max {labels.max()}") print(f"label min {labels.min()}") print(f"scores max {scores.max()}") print(f"scores min {scores.min()}") for i in range(boxes.shape[0]): bbox=boxes[i] cv2.rectangle(vis_img, (bbox[1], bbox[0]), (bbox[3], bbox[2]), (255, 255, 0), 2) cv2.imshow("Results",vis_img) cv2.waitKey(0)
import numpy as np import cv2 import random import warnings import scipy from scipy.linalg.basic import solve_circulant import skimage import skimage.transform from distutils.version import LooseVersion import torch import math import json from torch.functional import Tensor np.random.seed(42) def load_points_dataset(f_p): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] file = line[3] first_point = None second_point = None if label == "head": first_point = (int(line[1]), int(line[2])) elif label == "tail": second_point = (int(line[1]), int(line[2])) i += 1 if i < len(all_lines): line2 = all_lines[i].split(",") if line2[3] == file: if line2[0] == "head": first_point = (int(line2[1]), int(line2[2])) elif line2[0] == "tail": second_point = (int(line2[1]), int(line2[2])) i += 1 if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") points[file].append([first_point, second_point]) else: points[file] = [[first_point, second_point]] return points def load_points_dataset_2(f_p,label_name=["head","tail"]): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] file = line[3] first_point = None second_point = None if label == label_name[0]: first_point = (int(line[1]), int(line[2])) elif label == label_name[1]: second_point = (int(line[1]), int(line[2])) i += 1 if i < len(all_lines): line2 = all_lines[i].split(",") if line2[3] == file: if line2[0] == label_name[0]: first_point = (int(line2[1]), int(line2[2])) elif line2[0] == label_name[1]: second_point = (int(line2[1]), int(line2[2])) i += 1 if not first_point and not second_point: continue if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") points[file].append([first_point, second_point]) else: points[file] = [[first_point, second_point]] return points def load_class_dataset(f_p,label_name=["rating","neck"]): """load keypoints(head/tail)from the text file Args: f_p ([str]): File path containing the head and tail points (x,y) of each fruit in the image. Each Image can have multiple fruits Returns: [dict]: Dictionary of file names as keys and corresponding fruit points as values """ with open(f_p, "r") as f: all_lines = f.readlines() points = {} i = 0 while i < len(all_lines): if i > len(all_lines): break line = all_lines[i].split(",") label = line[0] splitted_labels=label.split("_") file = line[3] coords= None if splitted_labels[0] in label_name: coords = (int(line[1]), int(line[2])) i += 1 if coords is None: continue if file in points: # file already in dictionary append the list # print(f"Appending the file to existing one {file}") if splitted_labels[0] in points[file]: points[file][splitted_labels[0]].append([coords,int(splitted_labels[1])]) else: points[file][splitted_labels[0]]=[[coords,int(splitted_labels[1])]] else: points[file]={splitted_labels[0]:[[coords, int(splitted_labels[1])]]} return points def load_segmentation_dataset(f_p,label_names=None): """" Returns: [dict]: Dictionary of list with names """ data=load_json(f_p) cat_map={} for cat in data["categories"]: if cat["name"] in label_names: cat_map[cat['id']]=cat["name"] image_map={} for cat in data["images"]: image_map[cat['id']]=cat["file_name"] annos={} for d in data["annotations"]: tmp=[] seg=d["segmentation"][0] for i in range(0,len(seg)-1,2): tmp.append([seg[i],seg[i+1]]) if image_map[d["image_id"]] not in annos: annos[image_map[d["image_id"]]]=[{"class_id":cat_map[d["category_id"]],"annotation":tmp}] else: annos[image_map[d["image_id"]]].append({"class_id":cat_map[d["category_id"]],"annotation":tmp}) return annos def load_backbone(filename): with open(filename) as f: back_annotation = json.load(f) return back_annotation def load_json(filename): with open(filename) as f: annotation = json.load(f) return annotation def extract_bboxes(mask): """Compute bounding boxes from masks. mask: [height, width, num_instances]. Mask pixels are either 1 or 0. Returns: bbox array [num_instances, (y1, x1, y2, x2)]. """ #print(np.max(mask)) #print(np.min(mask)) boxes = np.zeros([mask.shape[-1], 4], dtype=np.int32) for i in range(mask.shape[-1]): m = mask[:, :, i] # Bounding box. horizontal_indicies = np.where(np.any(m, axis=0))[0] vertical_indicies = np.where(np.any(m, axis=1))[0] if horizontal_indicies.shape[0]: x1, x2 = horizontal_indicies[[0, -1]] y1, y2 = vertical_indicies[[0, -1]] # x2 and y2 should not be part of the box. Increment by 1. x2 += 1 y2 += 1 else: # No mask for this instance. Might happen due to # resizing or cropping. Set bbox to zeros x1, x2, y1, y2 = 0, 0, 0, 0 boxes[i] = np.array([x1,y1,x2,y2]) return boxes.astype(np.int32) def resize( image, output_shape, order=1, mode="constant", cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None, ): """A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the right parameters. The right parameters depend on the version of skimage. This solves the problem by using different parameters per version. And it provides a central place to control resizing defaults. """ if LooseVersion(skimage.__version__) >= LooseVersion("0.14"): # New in 0.14: anti_aliasing. Default it to False for backward # compatibility with skimage 0.13. return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, anti_aliasing=anti_aliasing, anti_aliasing_sigma=anti_aliasing_sigma, ) else: return skimage.transform.resize( image, output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range, ) def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"): """Resizes an image keeping the aspect ratio unchanged. min_dim: if provided, resizes the image such that it's smaller dimension == min_dim max_dim: if provided, ensures that the image longest side doesn't exceed this value. min_scale: if provided, ensure that the image is scaled up by at least this percent even if min_dim doesn't require it. mode: Resizing mode. none: No resizing. Return the image unchanged. square: Resize and pad with zeros to get a square image of size [max_dim, max_dim]. pad64: Pads width and height with zeros to make them multiples of 64. If min_dim or min_scale are provided, it scales the image up before padding. max_dim is ignored in this mode. The multiple of 64 is needed to ensure smooth scaling of feature maps up and down the 6 levels of the FPN pyramid (2**6=64). crop: Picks random crops from the image. First, scales the image based on min_dim and min_scale, then picks a random crop of size min_dim x min_dim. Can be used in training only. max_dim is not used in this mode. Returns: image: the resized image window: (y1, x1, y2, x2). If max_dim is provided, padding might be inserted in the returned image. If so, this window is the coordinates of the image part of the full image (excluding the padding). The x2, y2 pixels are not included. scale: The scale factor used to resize the image padding: Padding added to the image [(top, bottom), (left, right), (0, 0)] """ # Keep track of image dtype and return results in the same dtype image_dtype = image.dtype # Default window (y1, x1, y2, x2) and default scale == 1. h, w = image.shape[:2] window = (0, 0, h, w) scale = 1 padding = [(0, 0), (0, 0), (0, 0)] crop = None if mode == "none": return image, window, scale, padding, crop # Scale? if min_dim: # Scale up but not down scale = max(1, min_dim / min(h, w)) if min_scale and scale < min_scale: scale = min_scale # Does it exceed max dim? if max_dim and mode == "square": image_max = max(h, w) if round(image_max * scale) > max_dim: scale = max_dim / image_max # Resize image using bilinear interpolation if scale != 1: image = resize(image, (round(h * scale), round(w * scale)), preserve_range=True) # Need padding or cropping? if mode == "square": # Get new height and width h, w = image.shape[:2] top_pad = (max_dim - h) // 2 bottom_pad = max_dim - h - top_pad left_pad = (max_dim - w) // 2 right_pad = max_dim - w - left_pad padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode="constant", constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "pad64": h, w = image.shape[:2] # Both sides must be divisible by 64 assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64" # Height if h % 64 > 0: max_h = h - (h % 64) + 64 top_pad = (max_h - h) // 2 bottom_pad = max_h - h - top_pad else: top_pad = bottom_pad = 0 # Width if w % 64 > 0: max_w = w - (w % 64) + 64 left_pad = (max_w - w) // 2 right_pad = max_w - w - left_pad else: left_pad = right_pad = 0 padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)] image = np.pad(image, padding, mode="constant", constant_values=0) window = (top_pad, left_pad, h + top_pad, w + left_pad) elif mode == "crop": # Pick a random crop h, w = image.shape[:2] y = random.randint(0, (h - min_dim)) x = random.randint(0, (w - min_dim)) crop = (y, x, min_dim, min_dim) image = image[y : y + min_dim, x : x + min_dim] window = (0, 0, min_dim, min_dim) else: raise Exception("Mode {} not supported".format(mode)) return image.astype(image_dtype), window, scale, padding, crop def resize_mask(mask, scale, padding, crop=None): """Resizes a mask using the given scale and padding. Typically, you get the scale and padding from resize_image() to ensure both, the image and the mask, are resized consistently. scale: mask scaling factor padding: Padding to add to the mask in the form [(top, bottom), (left, right), (0, 0)] """ # Suppress warning from scipy 0.13.0, the output shape of zoom() is # calculated with round() instead of int() with warnings.catch_warnings(): warnings.simplefilter("ignore") mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0) if crop is not None: y, x, h, w = crop mask = mask[y : y + h, x : x + w] else: mask = np.pad(mask, padding, mode="constant", constant_values=0) return mask def vis_mask(vis_img,indicies,color=(255,120,0)): for j in range(len(indicies[0])): x = indicies[1][j] y = indicies[0][j] # viusalize masks cv2.circle(vis_img, (x, y), 1, color, 1) def resize_images_cv(img): scale_percent = 40 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) # resize image resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) return resized def write_text(image,text,point=(0,0),color=(255,0,0)): # font font = cv2.FONT_HERSHEY_SIMPLEX # fontScale fontScale = 1 # Line thickness of 2 px thickness = 3 # Using cv2.putText() method image = cv2.putText(image, text, point, font, fontScale, color, thickness, cv2.LINE_AA) return image def vis_data(image, masks, bboxs,classes,keypoints=None,**kwargs): vis_img = (image.detach().numpy()*255).astype(np.uint8) vis_img=np.moveaxis(vis_img, 0, -1) vis_img=vis_img.copy() class_color={i:[random.uniform(0,255) for _ in range(3)] for i in np.unique(classes)} # offset for drawing text off_x=20 off_y=50 for i in range(masks.shape[0]): mask = masks[i][...,None].detach().numpy() bbox = np.int0(bboxs[i].detach().numpy().copy()) indicies = np.where(mask >= 0.5) vis_mask(vis_img,indicies=indicies,color=class_color[classes[i]]) # Visualize bounding box cv2.rectangle(vis_img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), class_color[classes[i]], 2) # write class name write_text(vis_img,classes[i],((bbox[0], bbox[1]))) # Visualize segm classes if "other_masks" in kwargs and "seg_labels" in kwargs: for j,k in enumerate(kwargs["other_masks"].keys(),start=1): if classes[i] in kwargs["seg_labels"][j]: m=kwargs["other_masks"][k][i][...,None].detach().numpy() indicies = np.where(m >= 0.1) vis_mask(vis_img,indicies=indicies,color=(0,0,255)) #other_mask_id+=1 ## Visualize keypoints if "kp_labels" in kwargs and keypoints is not None: if classes[i] in kwargs["kp_labels"]: keypoint = np.int0(keypoints[i].detach().numpy()) # Visualize Keypoints cv2.circle(vis_img, (keypoint[0][0], keypoint[0][1]), 1, (0, 255, 255), 20) write_text(vis_img,"Head",(keypoint[0][0]+off_x, keypoint[0][1]+off_y)) cv2.circle(vis_img, (keypoint[1][0], keypoint[1][1]), 1, (0, 255, 255), 20) write_text(vis_img,"Tail",(keypoint[1][0]+off_x, keypoint[1][1]+off_y)) # visualize classification if "clas" in kwargs and "clas_labels" in kwargs: for j,k in enumerate(kwargs["clas"].keys(),start=0): if classes[i] in kwargs["clas_labels"][j]: cl=kwargs["clas"][k][i].cpu().item() point=(bbox[0]+(bbox[2]-bbox[0])//2+j*off_x,bbox[1]+(bbox[3]-bbox[1])//2+j*off_y) write_text(vis_img,f"{k}: {cl}",point=point,color=(0,0,255)) vis_img=resize_images_cv(vis_img) #if"" kwargs["DEBUG"]: if "epoch" in kwargs: cv2.imwrite("/home/ec2-user/SageMaker/SMN/res_images/"+f"{kwargs['epoch']}"+".png",vis_img) #cv2.imshow("Input and labels", vis_img) #cv2.waitKey(0) def resize_points(points, scale, window): # window: (y1, x1, y2, x2) scaled_points = [] for i in range(len(points)): two_point = np.array(points[i]) two_point = scale * two_point two_point[0][0] = two_point[0][0] + window[1] two_point[0][1] = two_point[0][1] + window[0] two_point[1][0] = two_point[1][0] + window[1] two_point[1][1] = two_point[1][1] + window[0] scaled_points.append(two_point) return np.int0(scaled_points) def generate_anchors_tensor(scales, ratios, shape, feature_stride, anchor_stride,device="cpu"): """ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_stride: Stride of anchors on the feature map. For example, if the value is 2 then generate anchors for every other feature map pixel. """ # Get all combinations of scales and ratios scales, ratios = np.meshgrid(np.array(scales), np.array(ratios)) scales = scales.flatten() ratios = ratios.flatten() # Enumerate heights and widths from scales and ratios heights = scales / np.sqrt(ratios) widths = scales * np.sqrt(ratios) # Enumerate shifts in feature space shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y) # Enumerate combinations of shifts, widths, and heights box_widths, box_centers_x = np.meshgrid(widths, shifts_x) box_heights, box_centers_y = np.meshgrid(heights, shifts_y) # Reshape to get a list of (y, x) and a list of (h, w) box_centers = np.stack([box_centers_y, box_centers_x], axis=2).reshape([-1, 2]) box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2]) # Convert to corner coordinates (y1, x1, y2, x2) boxes = np.concatenate( [box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], axis=1 ) boxes=torch.tensor(boxes,dtype=torch.float32) return boxes def visualize_anchors( img, anchors, backbone_shapes, RPN_ANCHOR_RATIOS, RPN_ANCHOR_STRIDE, RPN_ANCHOR_SCALES, ): vis_img = img.copy() num_levels = len(backbone_shapes) anchors_per_cell = len(RPN_ANCHOR_RATIOS) print("Anchors Count: ", anchors.shape[0]) print("Scales: ", RPN_ANCHOR_SCALES) print("ratios: ", RPN_ANCHOR_RATIOS) print("Anchors per Cell: ", anchors_per_cell) print("Levels: ", num_levels) anchors_per_level = [] for l in range(num_levels): num_cells = backbone_shapes[l][0] * backbone_shapes[l][1] anchors_per_level.append(anchors_per_cell * num_cells // RPN_ANCHOR_STRIDE ** 2) print("Anchors in Level {}: {}".format(l, anchors_per_level[l])) for level in range(num_levels): colors = [[0, 255, 0]] # Compute the index of the anchors at the center of the image level_start = sum( anchors_per_level[:level] ) # sum of anchors of previous levels level_anchors = anchors[level_start : level_start + anchors_per_level[level]] print( "Level {}. Anchors: {:6} Feature map Shape: {}".format( level, level_anchors.shape[0], backbone_shapes[level] ) ) center_cell = np.array(backbone_shapes[level]) // 2 center_cell_index = center_cell[0] * backbone_shapes[level][1] + center_cell[1] level_center = center_cell_index * anchors_per_cell center_anchor = anchors_per_cell * ( (center_cell[0] * backbone_shapes[level][1] / RPN_ANCHOR_STRIDE ** 2) + center_cell[1] / RPN_ANCHOR_STRIDE ) level_center = int(center_anchor) # Draw anchors. Brightness show the order in the array, dark to bright. for i, rect in enumerate( level_anchors[level_center : level_center + anchors_per_cell] ): y1, x1, y2, x2 = rect cv2.rectangle( vis_img, (int(x1), int(y1)), (int(x2), int(y2)), colors[level], 2 ) cv2.imshow("Center Anchor Boxes", vis_img) cv2.waitKey(0) def generate_pyramid_anchors_tensor(scales, ratios, feature_shapes, feature_strides, anchor_stride,device="cpu"): """Generate anchors at different levels of a feature pyramid. Each scale is associated with a level of the pyramid, but each ratio is used in all levels of the pyramid. Returns: anchors: [N, (y1, x1, y2, x2)]. All generated anchors in one array. Sorted with the same order of the given scales. So, anchors of scale[0] come first, then anchors of scale[1], and so on. """ # Anchors # [anchor_count, (y1, x1, y2, x2)] anchors = [] for i in range(len(scales)): anchors.append(generate_anchors_tensor(scales[i], ratios, feature_shapes[i], feature_strides[i], anchor_stride,device=device)) return torch.cat(anchors, axis=0).to(device=device) def compute_iou_tensor(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficiency. Calculate once in the caller to avoid duplicate work. """ # Calculate intersection areas y1 = torch.maximum(box[0], boxes[:, 0]) y2 = torch.minimum(box[2], boxes[:, 2]) x1 = torch.maximum(box[1], boxes[:, 1]) x2 = torch.minimum(box[3], boxes[:, 3]) intersection = torch.maximum(x2 - x1, torch.tensor(0)) * torch.maximum(y2 - y1, torch.tensor(0)) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_overlaps_tesnor(boxes1, boxes2,device="cpu"): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. For better performance, pass the largest set first and the smaller second. """ # Areas of anchors and GT boxes area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) # Compute overlaps to generate matrix [boxes1 count, boxes2 count] # Each cell contains the IoU value. overlaps = torch.zeros((boxes1.shape[0], boxes2.shape[0])).to(device=device) for i in range(overlaps.shape[1]): box2 = boxes2[i] overlaps[:, i] = compute_iou_tensor(box2, boxes1, area2[i], area1) return overlaps def apply_box_deltas_tesnor(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, (y1, x1, y2, x2)]. Note that (y2, x2) is outside the box. deltas: [N, (dy, dx, log(dh), log(dw))] """ # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] center_y = boxes[:, 0] + 0.5 * height center_x = boxes[:, 1] + 0.5 * width # Apply deltas center_y += deltas[:, 0] * height center_x += deltas[:, 1] * width height *= torch.exp(deltas[:, 2]) width *= torch.exp(deltas[:, 3]) # Convert back to y1, x1, y2, x2 y1 = center_y - 0.5 * height x1 = center_x - 0.5 * width y2 = y1 + height x2 = x1 + width return torch.stack([y1, x1, y2, x2], axis=1) def vis_anchors_refined_anchors_(img, anchors, refined_anchors): vis_img = img.copy() for i, rect in enumerate(anchors): y1, x1, y2, x2 = rect cv2.rectangle(vis_img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2) y1, x1, y2, x2 = refined_anchors[i] cv2.rectangle(vis_img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2) break cv2.imshow("Matched Anchor Boxes", vis_img) cv2.waitKey(0) def build_rpn_targets_tensor(anchors, gt_boxes, config): """Given the anchors and GT boxes, compute overlaps and identify positive anchors and deltas to refine them to match their corresponding GT boxes. anchors: [num_anchors, (y1, x1, y2, x2)] gt_class_ids: [num_gt_boxes] Integer class IDs. gt_boxes: [num_gt_boxes, (y1, x1, y2, x2)] Returns: rpn_match: [N] (int32) matches between anchors and GT boxes. 1 = positive anchor, -1 = negative anchor, 0 = neutral rpn_bbox: [N, (dy, dx, log(dh), log(dw))] Anchor bbox deltas. """ # RPN Match: 1 = positive anchor, -1 = negative anchor, 0 = neutral rpn_match = torch.zeros([anchors.shape[0]], dtype=torch.int32).to(device=config.DEVICE) # RPN bounding boxes: [max anchors per image, (dy, dx, log(dh), log(dw))] rpn_bbox = torch.zeros((config.RPN_TRAIN_ANCHORS_PER_IMAGE, 4)).to(device=config.DEVICE) no_crowd_bool = torch.ones([anchors.shape[0]], dtype=torch.bool).to(device=config.DEVICE) # Compute overlaps [num_anchors, num_gt_boxes] overlaps = compute_overlaps_tesnor(anchors, gt_boxes,config.DEVICE) # Match anchors to GT Boxes # If an anchor overlaps a GT box with IoU >= 0.7 then it's positive. # If an anchor overlaps a GT box with IoU < 0.3 then it's negative. # Neutral anchors are those that don't match the conditions above, # and they don't influence the loss function. # However, don't keep any GT box unmatched (rare, but happens). Instead, # match it to the closest anchor (even if its max IoU is < 0.3). # # 1. Set negative anchors first. They get overwritten below if a GT box is # matched to them. Skip boxes in crowd areas. anchor_iou_argmax = torch.argmax(overlaps, axis=1) anchor_iou_max = overlaps[torch.arange(overlaps.shape[0]), anchor_iou_argmax] rpn_match[(anchor_iou_max < 0.3) & (no_crowd_bool)] = -1 # 2. Set an anchor for each GT box (regardless of IoU value). # If multiple anchors have the same IoU match all of them # original was argwhere # gt_iou_argmax = torch.where(torch.tensor(overlaps == torch.max(overlaps, axis=0)))[:, 0] a = torch.max(overlaps, axis=0)[0] gt_iou_argmax = torch.where(overlaps == a)[0] rpn_match[gt_iou_argmax] = 1 # 3. Set anchors with high overlap as positive. rpn_match[anchor_iou_max >= 0.7] = 1 # Subsample to balance positive and negative anchors # Don't let positives be more than half the anchors ids = torch.where(rpn_match == 1)[0] extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE // 2) if extra > 0: # Reset the extra ones to neutral unif = torch.ones(ids.shape[0]).to(device=config.DEVICE) idx = unif.multinomial(extra, replacement=False) ids = ids[idx] # ids = np.random.choice(ids, extra, replace=False) rpn_match[ids] = 0 # Same for negative proposals ids = torch.where(rpn_match == -1)[0] extra = len(ids) - (config.RPN_TRAIN_ANCHORS_PER_IMAGE - torch.sum(rpn_match == 1)) if extra > 0: # Rest the extra ones to neutral # ids = np.random.choice(ids, extra, replace=False) unif = torch.ones(ids.shape[0]).to(device=config.DEVICE) idx = unif.multinomial(extra, replacement=False) ids = ids[idx] rpn_match[ids] = 0 # For positive anchors, compute shift and scale needed to transform them # to match the corresponding GT boxes. ids = torch.where(rpn_match == 1)[0] ix = 0 # index into rpn_bbox for i, a in zip(ids, anchors[ids]): # Closest gt box (it might have IoU < 0.7) gt = gt_boxes[anchor_iou_argmax[i]] # Convert coordinates to center plus width/height. # GT Box gt_h = gt[2] - gt[0] gt_w = gt[3] - gt[1] gt_center_y = gt[0] + 0.5 * gt_h gt_center_x = gt[1] + 0.5 * gt_w # Anchor a_h = a[2] - a[0] a_w = a[3] - a[1] a_center_y = a[0] + 0.5 * a_h a_center_x = a[1] + 0.5 * a_w # Compute the bbox refinement that the RPN should predict. rpn_bbox[ix] = torch.tensor( [ (gt_center_y - a_center_y) / a_h, (gt_center_x - a_center_x) / a_w, torch.log(gt_h / a_h), torch.log(gt_w / a_w), ] ) # Normalize #rpn_bbox[ix] /= torch.tensor(config.RPN_BBOX_STD_DEV, dtype=torch.float32).to(device=config.DEVICE) ix += 1 return rpn_match, rpn_bbox def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is assumed to be outside the box. """ box = box.type(torch.float32) gt_box = gt_box.type(torch.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = torch.log(gt_height / height) dw = torch.log(gt_width / width) return torch.stack([dy, dx, dh, dw], axis=1) def process_box(box, score, image_shape, min_size): """ Clip boxes in the image size and remove boxes which are too small. """ box[:, [0, 2]] = box[:, [0, 2]].clamp(0, image_shape[0]) box[:, [1, 3]] = box[:, [1, 3]].clamp(0, image_shape[1]) w, h = box[:, 2] - box[:, 0], box[:, 3] - box[:, 1] keep = torch.where((w >= min_size) & (h >= min_size))[0] box, score = box[keep], score[keep] return box, score def roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio ): if torch.__version__ >= "1.5.0": return torch.ops.torchvision.roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, False, ) else: return torch.ops.torchvision.roi_align( features, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio ) class RoIAlign: """ Performs Region of Interest (RoI) Align operator described in Mask R-CNN """ def __init__(self, output_size, sampling_ratio): """ Arguments: output_size (Tuple[int, int]): the size of the output after the cropping is performed, as (height, width) sampling_ratio (int): number of sampling points in the interpolation grid used to compute the output value of each pooled output bin. If > 0, then exactly sampling_ratio x sampling_ratio grid points are used. If <= 0, then an adaptive number of grid points are used (computed as ceil(roi_width / pooled_w), and likewise for height). Default: -1 """ self.output_size = output_size self.sampling_ratio = sampling_ratio self.spatial_scale = None def setup_scale(self, feature_shape, image_shape): if self.spatial_scale is not None: return possible_scales = [] for s1, s2 in zip(feature_shape, image_shape): scale = 2 ** int(math.log2(s1 / s2)) possible_scales.append(scale) assert possible_scales[0] == possible_scales[1] self.spatial_scale = possible_scales[0] def __call__(self, feature, proposal, image_shape): """ Arguments: feature (Tensor[N, C, H, W]) proposal (Tensor[K, 4]) image_shape (Torch.Size([H, W])) Returns: output (Tensor[K, C, self.output_size[0], self.output_size[1]]) """ idx = proposal.new_full((proposal.shape[0], 1), 0) roi = torch.cat((idx, proposal), dim=1) self.setup_scale(feature.shape[-2:], image_shape) return roi_align( feature.to(roi), roi, self.spatial_scale, self.output_size[0], self.output_size[1], self.sampling_ratio, ) class Matcher: def __init__(self, high_threshold, low_threshold, allow_low_quality_matches=False): self.high_threshold = high_threshold self.low_threshold = low_threshold self.allow_low_quality_matches = allow_low_quality_matches def __call__(self, iou): """ Arguments: iou (Tensor[M, N]): containing the pairwise quality between M ground-truth boxes and N predicted boxes. Returns: label (Tensor[N]): positive (1) or negative (0) label for each predicted box, -1 means ignoring this box. matched_idx (Tensor[N]): indices of gt box matched by each predicted box. """ value, matched_idx = iou.max(dim=0) label = torch.full((iou.shape[1],), -1, dtype=torch.float, device=iou.device) label[value >= self.high_threshold] = 1 label[value < self.low_threshold] = 0 if self.allow_low_quality_matches: highest_quality = iou.max(dim=1)[0] gt_pred_pairs = torch.where(iou == highest_quality[:, None])[1] label[gt_pred_pairs] = 1 return label, matched_idx class BalancedPositiveNegativeSampler: def __init__(self, num_samples, positive_fraction): self.num_samples = num_samples self.positive_fraction = positive_fraction def __call__(self, label): positive = torch.where(label == 1)[0] negative = torch.where(label == 0)[0] num_pos = int(self.num_samples * self.positive_fraction) num_pos = min(positive.numel(), num_pos) num_neg = self.num_samples - num_pos num_neg = min(negative.numel(), num_neg) pos_perm = torch.randperm(positive.numel(), device=positive.device)[:num_pos] neg_perm = torch.randperm(negative.numel(), device=negative.device)[:num_neg] pos_idx = positive[pos_perm] neg_idx = negative[neg_perm] return pos_idx, neg_idx def visualize_inference(in_img, inv_normalize,results): vis_img = in_img.clone() vis_img = (inv_normalize(vis_img).data.numpy() * 255).astype(np.uint8) vis_img = np.ascontiguousarray(np.moveaxis(vis_img, 0, -1)) boxes=np.int0(results["boxes"]) labels=results["labels"] scores=results["scores"] print(f"Labels max {labels.max()}") print(f"label min {labels.min()}") print(f"scores max {scores.max()}") print(f"scores min {scores.min()}") for i in range(boxes.shape[0]): bbox=boxes[i] cv2.rectangle(vis_img, (bbox[1], bbox[0]), (bbox[3], bbox[2]), (255, 255, 0), 2) cv2.imshow("Results",vis_img) cv2.waitKey(0)
from celescope.mut.__init__ import __ASSAY__ from celescope.tools.multi import Multi class Multi_mut(Multi): def mapping_mut(self, sample): step = 'mapping_mut' fq = f'{self.outdir_dic[sample]['cutadapt']}/{sample}_clean_2.fq{self.fq_suffix}' cmd = ( f'{self.__APP__} ' f'{self.__ASSAY__} ' f'{step } ' f'--outdir {self.outdir_dic[sample][step]} ' f'--sample {sample} ' f'--assay {self.__ASSAY__} ' f'--fq {fq} ' f'--thread {self.thread} ' f'--indel_genomeDir {self.indel_genomeDir} ' ) self.process_cmd(cmd, step, sample, m=self.args.starMem, x=self.args.thread) def count_mut(self, sample): step = 'count_mut' bam = f'{self.outdir_dic[sample]['mapping_mut']}/{sample}_Aligned.sortedByCoord.out.bam' cmd = ( f'{self.__APP__} ' f'{self.__ASSAY__} ' f'{step } ' f'--outdir {self.outdir_dic[sample][step]} ' f'--sample {sample} ' f'--assay {self.__ASSAY__} ' f'--bam {bam} ' f'--mut_file {self.mut_file} ' f'--match_dir {self.col4_dict[sample]} ' f'--shift_base {self.shift_base} ' ) self.process_cmd(cmd, step, sample, m=8, x=1) def main(): multi = Multi_mut(__ASSAY__) multi.run() if __name__ == '__main__': main()
from celescope.mut.__init__ import __ASSAY__ from celescope.tools.multi import Multi class Multi_mut(Multi): def mapping_mut(self, sample): step = 'mapping_mut' fq = f'{self.outdir_dic[sample]["cutadapt"]}/{sample}_clean_2.fq{self.fq_suffix}' cmd = ( f'{self.__APP__} ' f'{self.__ASSAY__} ' f'{step } ' f'--outdir {self.outdir_dic[sample][step]} ' f'--sample {sample} ' f'--assay {self.__ASSAY__} ' f'--fq {fq} ' f'--thread {self.thread} ' f'--indel_genomeDir {self.indel_genomeDir} ' ) self.process_cmd(cmd, step, sample, m=self.args.starMem, x=self.args.thread) def count_mut(self, sample): step = 'count_mut' bam = f'{self.outdir_dic[sample]["mapping_mut"]}/{sample}_Aligned.sortedByCoord.out.bam' cmd = ( f'{self.__APP__} ' f'{self.__ASSAY__} ' f'{step } ' f'--outdir {self.outdir_dic[sample][step]} ' f'--sample {sample} ' f'--assay {self.__ASSAY__} ' f'--bam {bam} ' f'--mut_file {self.mut_file} ' f'--match_dir {self.col4_dict[sample]} ' f'--shift_base {self.shift_base} ' ) self.process_cmd(cmd, step, sample, m=8, x=1) def main(): multi = Multi_mut(__ASSAY__) multi.run() if __name__ == '__main__': main()
from flask import Flask, jsonify, request, render_template, Response, send_file # from prefix_and_wsgi_proxy_fix import ReverseProxied from base64 import urlsafe_b64encode import gpxpy.gpx import geojson import werkzeug.exceptions import os from werkzeug.datastructures import Headers from db_functions import get_waypoints_by_trip, set_db_path, create_new_trip, get_nakarte_url_by_trip from time_functions import str_ts_to_UTC_ts from datetime import timedelta, timezone app = Flask(__name__) APP_PATH = os.path.dirname(os.path.realpath(__file__)) sqlite_db_path = os.path.join(APP_PATH, 'db', 'tracks_prod.db') set_db_path(sqlite_db_path) # This is just a test route. It is autotested after deploy @app.route('/test_app_is_working_kQK74RxmgPPm69') def test_app_is_working(): return "Yup! The app is working!\n" @app.errorhandler(werkzeug.exceptions.BadRequest) def bad_request_error_handler(e=None): message = { 'status': 400, 'message': 'Bad request or API method not found: ' + request.url, 'return': {'debug': str(e)} } response = jsonify(message) response.status_code = 400 return response @app.errorhandler(werkzeug.exceptions.InternalServerError) def internal_error_handler(e=None): message = { 'status': 500, 'message': 'Internal server error: ' + request.url, 'return': {'debug': str(e)} } response = jsonify(message) response.status_code = 500 return response @app.route('/get_waypoints') def get_waypoints(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = args['trip_name'] waypoints = get_waypoints_by_trip(trip_name) features = [] for i in range(len(waypoints)): id, fms_key_id, id_fms, lat, long, alt, ts, bs, msg = waypoints[i] ts = str_ts_to_UTC_ts(ts) cur_point = geojson.Point((lat, long, alt)) features.append(geojson.Feature(geometry=cur_point, properties={'BatteryState': bs, 'Message': msg, 'TimeStamp': ts})) message = { 'status': 200, 'message': 'OK', 'cnt': len(waypoints), 'return': geojson.FeatureCollection(features) } response = jsonify(message) response.status_code = 200 return response @app.route('/u') def generate_iframe_html(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args and 't' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = ''.join((args.get('trip_name', None) or args['t'])) nakarte_url = get_nakarte_url_by_trip(trip_name) or 'https://nakarte.me/#l=Otm' print('nakarte_url: ', nakarte_url) urlbase64 = f'[{{'n':'{trip_name}","c":3,"m":true,"u":"https://pyfindmespot.proj179.ru/gw?t={trip_name}"}}]' urlbase64 = urlsafe_b64encode(urlbase64.encode('utf-8')).decode('utf-8') nakarte_url += f'&nktj={urlbase64}' return render_template('nakarte.html', nakarte_url=nakarte_url) @app.route('/gw') @app.route('/get_gpx_waypoints') def generate_gpx(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args and 't' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = ''.join((args.get('trip_name', None) or args['t'])) waypoints = get_waypoints_by_trip(trip_name) gpx = gpxpy.gpx.GPX() gpx_track = gpxpy.gpx.GPXTrack() gpx.tracks.append(gpx_track) gpx_segment = gpxpy.gpx.GPXTrackSegment() gpx_track.segments.append(gpx_segment) for i in range(len(waypoints)): id, fms_key_id, id_fms, lat, long, alt, ts, bs, msg = waypoints[i] ts = str_ts_to_UTC_ts(ts) if msg: ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime(" (%m-%d %H:%M)") gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=msg + ts_msg, time=ts, name=msg + ts_msg)) cur_pnt = gpxpy.gpx.GPXTrackPoint(latitude=lat, longitude=long, elevation=alt, comment=msg, time=ts) cur_pnt.description = f"Время: {ts} Заряд батареи {bs}" gpx_segment.points.append(cur_pnt) # Добавляем точку с временем последнего сообщения if waypoints: ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime("%Y-%m-%d %H:%M:%S") gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=ts_msg, time=ts, name=ts_msg)) hdrs = Headers() hdrs.add('Content-Type', 'application/gpx+xml') hdrs.add('Content-Disposition', 'attachment', filename='track.gpx') return Response(gpx.to_xml(), headers=hdrs) @app.route('/create_track') def create_track(*args, **kwargs): args = dict(request.args) for parm in ['trip_name', 'fms_key', 'date_s', 'date_e']: if parm not in args: return bad_request_error_handler(NameError(f'Key {parm} not found')) trip_name = args['trip_name'] fms_key = args['fms_key'] print(args) date_s = str_ts_to_UTC_ts(args['date_s']) date_e = str_ts_to_UTC_ts(args['date_e']) create_new_trip(trip_name, fms_key, date_s, date_e) message = { 'status': 200, 'message': 'OK' } response = jsonify(message) response.status_code = 200 return response @app.route('/') def just_index(): return render_template('index.html') # app.wsgi_app = ReverseProxied(app.wsgi_app) if __name__ == "__main__": app.run(host="0.0.0.0")
from flask import Flask, jsonify, request, render_template, Response, send_file # from prefix_and_wsgi_proxy_fix import ReverseProxied from base64 import urlsafe_b64encode import gpxpy.gpx import geojson import werkzeug.exceptions import os from werkzeug.datastructures import Headers from db_functions import get_waypoints_by_trip, set_db_path, create_new_trip, get_nakarte_url_by_trip from time_functions import str_ts_to_UTC_ts from datetime import timedelta, timezone app = Flask(__name__) APP_PATH = os.path.dirname(os.path.realpath(__file__)) sqlite_db_path = os.path.join(APP_PATH, 'db', 'tracks_prod.db') set_db_path(sqlite_db_path) # This is just a test route. It is autotested after deploy @app.route('/test_app_is_working_kQK74RxmgPPm69') def test_app_is_working(): return "Yup! The app is working!\n" @app.errorhandler(werkzeug.exceptions.BadRequest) def bad_request_error_handler(e=None): message = { 'status': 400, 'message': 'Bad request or API method not found: ' + request.url, 'return': {'debug': str(e)} } response = jsonify(message) response.status_code = 400 return response @app.errorhandler(werkzeug.exceptions.InternalServerError) def internal_error_handler(e=None): message = { 'status': 500, 'message': 'Internal server error: ' + request.url, 'return': {'debug': str(e)} } response = jsonify(message) response.status_code = 500 return response @app.route('/get_waypoints') def get_waypoints(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = args['trip_name'] waypoints = get_waypoints_by_trip(trip_name) features = [] for i in range(len(waypoints)): id, fms_key_id, id_fms, lat, long, alt, ts, bs, msg = waypoints[i] ts = str_ts_to_UTC_ts(ts) cur_point = geojson.Point((lat, long, alt)) features.append(geojson.Feature(geometry=cur_point, properties={'BatteryState': bs, 'Message': msg, 'TimeStamp': ts})) message = { 'status': 200, 'message': 'OK', 'cnt': len(waypoints), 'return': geojson.FeatureCollection(features) } response = jsonify(message) response.status_code = 200 return response @app.route('/u') def generate_iframe_html(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args and 't' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = ''.join((args.get('trip_name', None) or args['t'])) nakarte_url = get_nakarte_url_by_trip(trip_name) or 'https://nakarte.me/#l=Otm' print('nakarte_url: ', nakarte_url) urlbase64 = f'[{{"n":"{trip_name}","c":3,"m":true,"u":"https://pyfindmespot.proj179.ru/gw?t={trip_name}"}}]' urlbase64 = urlsafe_b64encode(urlbase64.encode('utf-8')).decode('utf-8') nakarte_url += f'&nktj={urlbase64}' return render_template('nakarte.html', nakarte_url=nakarte_url) @app.route('/gw') @app.route('/get_gpx_waypoints') def generate_gpx(*args, **kwargs): args = dict(request.args) if 'trip_name' not in args and 't' not in args: return bad_request_error_handler(NameError(f'Key trip_name not found')) trip_name = ''.join((args.get('trip_name', None) or args['t'])) waypoints = get_waypoints_by_trip(trip_name) gpx = gpxpy.gpx.GPX() gpx_track = gpxpy.gpx.GPXTrack() gpx.tracks.append(gpx_track) gpx_segment = gpxpy.gpx.GPXTrackSegment() gpx_track.segments.append(gpx_segment) for i in range(len(waypoints)): id, fms_key_id, id_fms, lat, long, alt, ts, bs, msg = waypoints[i] ts = str_ts_to_UTC_ts(ts) if msg: ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime(" (%m-%d %H:%M)") gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=msg + ts_msg, time=ts, name=msg + ts_msg)) cur_pnt = gpxpy.gpx.GPXTrackPoint(latitude=lat, longitude=long, elevation=alt, comment=msg, time=ts) cur_pnt.description = f"Время: {ts} Заряд батареи {bs}" gpx_segment.points.append(cur_pnt) # Добавляем точку с временем последнего сообщения if waypoints: ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime("%Y-%m-%d %H:%M:%S") gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=ts_msg, time=ts, name=ts_msg)) hdrs = Headers() hdrs.add('Content-Type', 'application/gpx+xml') hdrs.add('Content-Disposition', 'attachment', filename='track.gpx') return Response(gpx.to_xml(), headers=hdrs) @app.route('/create_track') def create_track(*args, **kwargs): args = dict(request.args) for parm in ['trip_name', 'fms_key', 'date_s', 'date_e']: if parm not in args: return bad_request_error_handler(NameError(f'Key {parm} not found')) trip_name = args['trip_name'] fms_key = args['fms_key'] print(args) date_s = str_ts_to_UTC_ts(args['date_s']) date_e = str_ts_to_UTC_ts(args['date_e']) create_new_trip(trip_name, fms_key, date_s, date_e) message = { 'status': 200, 'message': 'OK' } response = jsonify(message) response.status_code = 200 return response @app.route('/') def just_index(): return render_template('index.html') # app.wsgi_app = ReverseProxied(app.wsgi_app) if __name__ == "__main__": app.run(host="0.0.0.0")
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Weight_Editor: @staticmethod def weights_entrypoint(): weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_weapon_type(change_all=False, weights=True) while weapon_data is not None: weapon_data['skins'][skin_choice]["weight"] = Weight_Editor.set_weight(weapon_skin_data) Skin_Manager.modify_skin_data(skin_data) weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_skin(skin_data, weapon_choice, change_all=False, weights=True) def set_weight(skin_data): current_weight = str(skin_data["weight"]) new_weight = inquirer.text( message=f"[{skin_data["display_name"]}] Selecione o peso para a aleatorização (peso atual {current_weight})", default=current_weight, validate=lambda result: result.isdigit(), filter=lambda result: int(result) ).execute() return new_weight
from InquirerPy import prompt, inquirer from InquirerPy.separator import Separator from ...flair_management.skin_manager.skin_manager import Skin_Manager from .weapon_config_prompts import Prompts class Weight_Editor: @staticmethod def weights_entrypoint(): weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_weapon_type(change_all=False, weights=True) while weapon_data is not None: weapon_data['skins'][skin_choice]["weight"] = Weight_Editor.set_weight(weapon_skin_data) Skin_Manager.modify_skin_data(skin_data) weapon_data, skin_data, skin_choice, weapon_choice, weapon_skin_data = Prompts.select_skin(skin_data, weapon_choice, change_all=False, weights=True) def set_weight(skin_data): current_weight = str(skin_data["weight"]) new_weight = inquirer.text( message=f"[{skin_data['display_name']}] Selecione o peso para a aleatorização (peso atual {current_weight})", default=current_weight, validate=lambda result: result.isdigit(), filter=lambda result: int(result) ).execute() return new_weight
# -*- coding: UTF-8 -*- # # copyright: 2020-2021, Frederico Martins # author: Frederico Martins <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Discogs data handler. This module handles Discogs data. The following is a simple usage example:: from .discogs import Discogs d = Discogs('my_discogs_secret_token') r = discogs.get_ratings() print(r) The module contains the following public classes: - Discogs -- The main entry point. As the example above shows, the Discogs() class can be used to load data from Discogs. All other classes in this module are considered implementation details. """ import json import re from time import time, sleep from progress.bar import Bar from requests import sessions class Discogs: """Data handler. This class loads data from Discogs. Args: key (str): Discogs API key. logger (logger.Logger, optional): Logger to use. Defaults to None. """ API_BASEURL = 'https://api.discogs.com' API_FORMAT = 'application/vnd.discogs.v2.plaintext+json' API_LIMIT = 100 API_RATELIMIT_STATUS = 429 API_RATELIMIT_TIME = 61 def __init__(self, key, logger=None): self.__api_last_block_time = time() self.__headers = { 'Accept': f'{self.API_FORMAT}', 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', 'User-Agent': f'{__package__}'} self.__key = key self.__logger = logger self.__params = { 'token': f'{self.__key}', 'per_page': self.API_LIMIT} self.__session = sessions.Session() self.__identity = self.__request(f'{self.API_BASEURL}/oauth/identity') def __request(self, url, params=None): """Private method to perform a request to the Discogs API. Args: url (str): Request URL. params (dict[str, Any], optional): Extra requests params. Defaults to None. Returns: dict[str, Any]: Discogs API data. """ response = self.__session.get( url, params={**self.__params, **params} if params else self.__params, headers=self.__headers) headers = response.headers status_code = response.status_code remaining_queries = int(headers.get('X-Discogs-Ratelimit-Remaining', 60)) if (remaining_queries < 2) or (status_code == self.API_RATELIMIT_STATUS): if self.__logger: self.__logger.warning('API rate limit reacehd.') now = time() sleep(max( 2, self.API_RATELIMIT_TIME - (now - self.__api_last_block_time))) self.__api_last_block_time = now return self.__request(url=url, params=params) return json.loads(response.content) def get_ratings(self, ratings=None): """Fetch Discogs ratings from the user's collection. Args: ratings (dict[str, Any], optional): Ratings. If provided this ratings will be updated. Defaults to None. Returns: dict[str, Any]: Ratings. """ if self.__logger: self.__logger.info('Fetching ratings from Discogs.') last_updated = int(time()) collection_info = self.__request( url=f'{self.__identity['resource_url']}/collection/folders/0', params={'page': 1}) total_albums = int(collection_info.get('count', 0)) total_pages = -(-total_albums // self.API_LIMIT) if ratings: ratings = ratings.get('ratings', {}) else: ratings = {} show_progress = True if self.__logger and self.__logger.level < self.__logger.Level.INFO: show_progress = False for step in Bar('Processing').iter( range(total_pages)) if show_progress else range(total_pages): page = step + 1 if self.__logger: self.__logger.debug(f'Fetching page {page}') content = self.__request( f'{self.__identity['resource_url']}/collection/folders/0/releases', params={'page': page}) releases = content['releases'] for release in releases: release_album_rating = int(release['rating']) release_album = release['basic_information']['title'].title() release_artist = ' - '.join(map( lambda x: re.sub(r'\(\d+\)', '', x['name']).strip(), release['basic_information']['artists'])).title() if self.__logger: self.__logger.debug( f'{release_artist} - [{release_album_rating}] {release_album} ') ratings.setdefault(release_artist, {}) ratings[release_artist].setdefault(release_album, {}) ratings[release_artist][release_album].setdefault( 'rating', release_album_rating) return {'last_updated': last_updated, 'ratings': ratings}
# -*- coding: UTF-8 -*- # # copyright: 2020-2021, Frederico Martins # author: Frederico Martins <http://github.com/fscm> # license: SPDX-License-Identifier: MIT """Discogs data handler. This module handles Discogs data. The following is a simple usage example:: from .discogs import Discogs d = Discogs('my_discogs_secret_token') r = discogs.get_ratings() print(r) The module contains the following public classes: - Discogs -- The main entry point. As the example above shows, the Discogs() class can be used to load data from Discogs. All other classes in this module are considered implementation details. """ import json import re from time import time, sleep from progress.bar import Bar from requests import sessions class Discogs: """Data handler. This class loads data from Discogs. Args: key (str): Discogs API key. logger (logger.Logger, optional): Logger to use. Defaults to None. """ API_BASEURL = 'https://api.discogs.com' API_FORMAT = 'application/vnd.discogs.v2.plaintext+json' API_LIMIT = 100 API_RATELIMIT_STATUS = 429 API_RATELIMIT_TIME = 61 def __init__(self, key, logger=None): self.__api_last_block_time = time() self.__headers = { 'Accept': f'{self.API_FORMAT}', 'Accept-Encoding': 'gzip', 'Content-Type': 'application/json', 'User-Agent': f'{__package__}'} self.__key = key self.__logger = logger self.__params = { 'token': f'{self.__key}', 'per_page': self.API_LIMIT} self.__session = sessions.Session() self.__identity = self.__request(f'{self.API_BASEURL}/oauth/identity') def __request(self, url, params=None): """Private method to perform a request to the Discogs API. Args: url (str): Request URL. params (dict[str, Any], optional): Extra requests params. Defaults to None. Returns: dict[str, Any]: Discogs API data. """ response = self.__session.get( url, params={**self.__params, **params} if params else self.__params, headers=self.__headers) headers = response.headers status_code = response.status_code remaining_queries = int(headers.get('X-Discogs-Ratelimit-Remaining', 60)) if (remaining_queries < 2) or (status_code == self.API_RATELIMIT_STATUS): if self.__logger: self.__logger.warning('API rate limit reacehd.') now = time() sleep(max( 2, self.API_RATELIMIT_TIME - (now - self.__api_last_block_time))) self.__api_last_block_time = now return self.__request(url=url, params=params) return json.loads(response.content) def get_ratings(self, ratings=None): """Fetch Discogs ratings from the user's collection. Args: ratings (dict[str, Any], optional): Ratings. If provided this ratings will be updated. Defaults to None. Returns: dict[str, Any]: Ratings. """ if self.__logger: self.__logger.info('Fetching ratings from Discogs.') last_updated = int(time()) collection_info = self.__request( url=f'{self.__identity["resource_url"]}/collection/folders/0', params={'page': 1}) total_albums = int(collection_info.get('count', 0)) total_pages = -(-total_albums // self.API_LIMIT) if ratings: ratings = ratings.get('ratings', {}) else: ratings = {} show_progress = True if self.__logger and self.__logger.level < self.__logger.Level.INFO: show_progress = False for step in Bar('Processing').iter( range(total_pages)) if show_progress else range(total_pages): page = step + 1 if self.__logger: self.__logger.debug(f'Fetching page {page}') content = self.__request( f'{self.__identity["resource_url"]}/collection/folders/0/releases', params={'page': page}) releases = content['releases'] for release in releases: release_album_rating = int(release['rating']) release_album = release['basic_information']['title'].title() release_artist = ' - '.join(map( lambda x: re.sub(r'\(\d+\)', '', x['name']).strip(), release['basic_information']['artists'])).title() if self.__logger: self.__logger.debug( f'{release_artist} - [{release_album_rating}] {release_album} ') ratings.setdefault(release_artist, {}) ratings[release_artist].setdefault(release_album, {}) ratings[release_artist][release_album].setdefault( 'rating', release_album_rating) return {'last_updated': last_updated, 'ratings': ratings}
""" Define typing templates """ from abc import ABC, abstractmethod import functools import sys import inspect import os.path from collections import namedtuple from collections.abc import Sequence from types import MethodType, FunctionType import numba from numba.core import types, utils from numba.core.errors import TypingError, InternalError from numba.core.cpu_options import InlineOptions # info store for inliner callback functions e.g. cost model _inline_info = namedtuple('inline_info', 'func_ir typemap calltypes signature') class Signature(object): """ The signature of a function call or operation, i.e. its argument types and return type. """ # XXX Perhaps the signature should be a BoundArguments, instead # of separate args and pysig... __slots__ = '_return_type', '_args', '_recvr', '_pysig' def __init__(self, return_type, args, recvr, pysig=None): if isinstance(args, list): args = tuple(args) self._return_type = return_type self._args = args self._recvr = recvr self._pysig = pysig @property def return_type(self): return self._return_type @property def args(self): return self._args @property def recvr(self): return self._recvr @property def pysig(self): return self._pysig def replace(self, **kwargs): """Copy and replace the given attributes provided as keyword arguments. Returns an updated copy. """ curstate = dict(return_type=self.return_type, args=self.args, recvr=self.recvr, pysig=self.pysig) curstate.update(kwargs) return Signature(**curstate) def __getstate__(self): """ Needed because of __slots__. """ return self._return_type, self._args, self._recvr, self._pysig def __setstate__(self, state): """ Needed because of __slots__. """ self._return_type, self._args, self._recvr, self._pysig = state def __hash__(self): return hash((self.args, self.return_type)) def __eq__(self, other): if isinstance(other, Signature): return (self.args == other.args and self.return_type == other.return_type and self.recvr == other.recvr and self.pysig == other.pysig) def __ne__(self, other): return not (self == other) def __repr__(self): return "%s -> %s" % (self.args, self.return_type) @property def is_method(self): """ Whether this signature represents a bound method or a regular function. """ return self.recvr is not None def as_method(self): """ Convert this signature to a bound method signature. """ if self.recvr is not None: return self sig = signature(self.return_type, *self.args[1:], recvr=self.args[0]) # Adjust the python signature params = list(self.pysig.parameters.values())[1:] sig = sig.replace( pysig=utils.pySignature( parameters=params, return_annotation=self.pysig.return_annotation, ), ) return sig def as_function(self): """ Convert this signature to a regular function signature. """ if self.recvr is None: return self sig = signature(self.return_type, *((self.recvr,) + self.args)) return sig def as_type(self): """ Convert this signature to a first-class function type. """ return types.FunctionType(self) def __unliteral__(self): return signature(types.unliteral(self.return_type), *map(types.unliteral, self.args)) def dump(self, tab=''): c = self.as_type()._code print(f'{tab}DUMP {type(self).__name__} [type code: {c}]') print(f'{tab} Argument types:') for a in self.args: a.dump(tab=tab + ' | ') print(f'{tab} Return type:') self.return_type.dump(tab=tab + ' | ') print(f'{tab}END DUMP') def is_precise(self): for atype in self.args: if not atype.is_precise(): return False return self.return_type.is_precise() def make_concrete_template(name, key, signatures): baseclasses = (ConcreteTemplate,) gvars = dict(key=key, cases=list(signatures)) return type(name, baseclasses, gvars) def make_callable_template(key, typer, recvr=None): """ Create a callable template with the given key and typer function. """ def generic(self): return typer name = "%s_CallableTemplate" % (key,) bases = (CallableTemplate,) class_dict = dict(key=key, generic=generic, recvr=recvr) return type(name, bases, class_dict) def signature(return_type, *args, **kws): recvr = kws.pop('recvr', None) assert not kws return Signature(return_type, args, recvr=recvr) def fold_arguments(pysig, args, kws, normal_handler, default_handler, stararg_handler): """ Given the signature *pysig*, explicit *args* and *kws*, resolve omitted arguments and keyword arguments. A tuple of positional arguments is returned. Various handlers allow to process arguments: - normal_handler(index, param, value) is called for normal arguments - default_handler(index, param, default) is called for omitted arguments - stararg_handler(index, param, values) is called for a "*args" argument """ if isinstance(kws, Sequence): # Normalize dict kws kws = dict(kws) # deal with kwonly args params = pysig.parameters kwonly = [] for name, p in params.items(): if p.kind == p.KEYWORD_ONLY: kwonly.append(name) if kwonly: bind_args = args[:-len(kwonly)] else: bind_args = args bind_kws = kws.copy() if kwonly: for idx, n in enumerate(kwonly): bind_kws[n] = args[len(kwonly) + idx] # now bind ba = pysig.bind(*bind_args, **bind_kws) for i, param in enumerate(pysig.parameters.values()): name = param.name default = param.default if param.kind == param.VAR_POSITIONAL: # stararg may be omitted, in which case its "default" value # is simply the empty tuple if name in ba.arguments: argval = ba.arguments[name] # NOTE: avoid wrapping the tuple type for stararg in another # tuple. if (len(argval) == 1 and isinstance(argval[0], (types.StarArgTuple, types.StarArgUniTuple))): argval = tuple(argval[0]) else: argval = () out = stararg_handler(i, param, argval) ba.arguments[name] = out elif name in ba.arguments: # Non-stararg, present ba.arguments[name] = normal_handler(i, param, ba.arguments[name]) else: # Non-stararg, omitted assert default is not param.empty ba.arguments[name] = default_handler(i, param, default) # Collect args in the right order args = tuple(ba.arguments[param.name] for param in pysig.parameters.values()) return args class FunctionTemplate(ABC): # Set to true to disable unsafe cast. # subclass overide-able unsafe_casting = True # Set to true to require exact match without casting. # subclass overide-able exact_match_required = False # Set to true to prefer literal arguments. # Useful for definitions that specialize on literal but also support # non-literals. # subclass overide-able prefer_literal = False def __init__(self, context): self.context = context def _select(self, cases, args, kws): options = { 'unsafe_casting': self.unsafe_casting, 'exact_match_required': self.exact_match_required, } selected = self.context.resolve_overload(self.key, cases, args, kws, **options) return selected def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ # Lookup the key on the class, to avoid binding it with `self`. key = type(self).key # On Python 2, we must also take care about unbound methods if isinstance(key, MethodType): assert key.im_self is None key = key.im_func return key @classmethod def get_source_code_info(cls, impl): """ Gets the source information about function impl. Returns: code - str: source code as a string firstlineno - int: the first line number of the function impl path - str: the path to file containing impl if any of the above are not available something generic is returned """ try: code, firstlineno = inspect.getsourcelines(impl) except OSError: # missing source, probably a string code = "None available (built from string?)" firstlineno = 0 path = inspect.getsourcefile(impl) if path is None: path = "<unknown> (built from string?)" return code, firstlineno, path @abstractmethod def get_template_info(self): """ Returns a dictionary with information specific to the template that will govern how error messages are displayed to users. The dictionary must be of the form: info = { 'kind': "unknown", # str: The kind of template, e.g. "Overload" 'name': "unknown", # str: The name of the source function 'sig': "unknown", # str: The signature(s) of the source function 'filename': "unknown", # str: The filename of the source function 'lines': ("start", "end"), # tuple(int, int): The start and end line of the source function. 'docstring': "unknown" # str: The docstring of the source function } """ pass def __str__(self): info = self.get_template_info() srcinfo = f"{info["filename"]}:{info["lines"][0]}" return f"<{self.__class__.__name__} {srcinfo}>" __repr__ = __str__ class AbstractTemplate(FunctionTemplate): """ Defines method ``generic(self, args, kws)`` which compute a possible signature base on input types. The signature does not have to match the input types. It is compared against the input types afterwards. """ def apply(self, args, kws): generic = getattr(self, "generic") sig = generic(args, kws) # Enforce that *generic()* must return None or Signature if sig is not None: if not isinstance(sig, Signature): raise AssertionError( "generic() must return a Signature or None. " "{} returned {}".format(generic, type(sig)), ) # Unpack optional type if no matching signature if not sig and any(isinstance(x, types.Optional) for x in args): def unpack_opt(x): if isinstance(x, types.Optional): return x.type else: return x args = list(map(unpack_opt, args)) assert not kws # Not supported yet sig = generic(args, kws) return sig def get_template_info(self): impl = getattr(self, "generic") basepath = os.path.dirname(os.path.dirname(numba.__file__)) code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info class CallableTemplate(FunctionTemplate): """ Base class for a template defining a ``generic(self)`` method returning a callable to be called with the actual ``*args`` and ``**kwargs`` representing the call signature. The callable has to return a return type, a full signature, or None. The signature does not have to match the input types. It is compared against the input types afterwards. """ recvr = None def apply(self, args, kws): generic = getattr(self, "generic") typer = generic() sig = typer(*args, **kws) # Unpack optional type if no matching signature if sig is None: if any(isinstance(x, types.Optional) for x in args): def unpack_opt(x): if isinstance(x, types.Optional): return x.type else: return x args = list(map(unpack_opt, args)) sig = typer(*args, **kws) if sig is None: return # Get the pysig try: pysig = typer.pysig except AttributeError: pysig = utils.pysignature(typer) # Fold any keyword arguments bound = pysig.bind(*args, **kws) if bound.kwargs: raise TypingError("unsupported call signature") if not isinstance(sig, Signature): # If not a signature, `sig` is assumed to be the return type if not isinstance(sig, types.Type): raise TypeError("invalid return type for callable template: " "got %r" % (sig,)) sig = signature(sig, *bound.args) if self.recvr is not None: sig = sig.replace(recvr=self.recvr) # Hack any omitted parameters out of the typer's pysig, # as lowering expects an exact match between formal signature # and actual args. if len(bound.args) < len(pysig.parameters): parameters = list(pysig.parameters.values())[:len(bound.args)] pysig = pysig.replace(parameters=parameters) sig = sig.replace(pysig=pysig) cases = [sig] return self._select(cases, bound.args, bound.kwargs) def get_template_info(self): impl = getattr(self, "generic") basepath = os.path.dirname(os.path.dirname(numba.__file__)) code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(self.key, '__name__', getattr(impl, '__qualname__', impl.__name__),), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info class ConcreteTemplate(FunctionTemplate): """ Defines attributes "cases" as a list of signature to match against the given input types. """ def apply(self, args, kws): cases = getattr(self, 'cases') return self._select(cases, args, kws) def get_template_info(self): import operator name = getattr(self.key, '__name__', "unknown") op_func = getattr(operator, name, None) kind = "Type restricted function" if op_func is not None: if self.key is op_func: kind = "operator overload" info = { 'kind': kind, 'name': name, 'sig': "unknown", 'filename': "unknown", 'lines': ("unknown", "unknown"), 'docstring': "unknown" } return info class _EmptyImplementationEntry(InternalError): def __init__(self, reason): super(_EmptyImplementationEntry, self).__init__( "_EmptyImplementationEntry({!r})".format(reason), ) class _OverloadFunctionTemplate(AbstractTemplate): """ A base class of templates for overload functions. """ def _validate_sigs(self, typing_func, impl_func): # check that the impl func and the typing func have the same signature! typing_sig = utils.pysignature(typing_func) impl_sig = utils.pysignature(impl_func) # the typing signature is considered golden and must be adhered to by # the implementation... # Things that are valid: # 1. args match exactly # 2. kwargs match exactly in name and default value # 3. Use of *args in the same location by the same name in both typing # and implementation signature # 4. Use of *args in the implementation signature to consume any number # of arguments in the typing signature. # Things that are invalid: # 5. Use of *args in the typing signature that is not replicated # in the implementing signature # 6. Use of **kwargs def get_args_kwargs(sig): kws = [] args = [] pos_arg = None for x in sig.parameters.values(): if x.default == utils.pyParameter.empty: args.append(x) if x.kind == utils.pyParameter.VAR_POSITIONAL: pos_arg = x elif x.kind == utils.pyParameter.VAR_KEYWORD: msg = ("The use of VAR_KEYWORD (e.g. **kwargs) is " "unsupported. (offending argument name is '%s')") raise InternalError(msg % x) else: kws.append(x) return args, kws, pos_arg ty_args, ty_kws, ty_pos = get_args_kwargs(typing_sig) im_args, im_kws, im_pos = get_args_kwargs(impl_sig) sig_fmt = ("Typing signature: %s\n" "Implementation signature: %s") sig_str = sig_fmt % (typing_sig, impl_sig) err_prefix = "Typing and implementation arguments differ in " a = ty_args b = im_args if ty_pos: if not im_pos: # case 5. described above msg = ("VAR_POSITIONAL (e.g. *args) argument kind (offending " "argument name is '%s') found in the typing function " "signature, but is not in the implementing function " "signature.\n%s") % (ty_pos, sig_str) raise InternalError(msg) else: if im_pos: # no *args in typing but there's a *args in the implementation # this is case 4. described above b = im_args[:im_args.index(im_pos)] try: a = ty_args[:ty_args.index(b[-1]) + 1] except ValueError: # there's no b[-1] arg name in the ty_args, something is # very wrong, we can't work out a diff (*args consumes # unknown quantity of args) so just report first error specialized = "argument names.\n%s\nFirst difference: '%s'" msg = err_prefix + specialized % (sig_str, b[-1]) raise InternalError(msg) def gen_diff(typing, implementing): diff = set(typing) ^ set(implementing) return "Difference: %s" % diff if a != b: specialized = "argument names.\n%s\n%s" % (sig_str, gen_diff(a, b)) raise InternalError(err_prefix + specialized) # ensure kwargs are the same ty = [x.name for x in ty_kws] im = [x.name for x in im_kws] if ty != im: specialized = "keyword argument names.\n%s\n%s" msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws)) raise InternalError(msg) same = [x.default for x in ty_kws] == [x.default for x in im_kws] if not same: specialized = "keyword argument default values.\n%s\n%s" msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws)) raise InternalError(msg) def generic(self, args, kws): """ Type the overloaded function by compiling the appropriate implementation for the given args. """ disp, new_args = self._get_impl(args, kws) if disp is None: return # Compile and type it for the given types disp_type = types.Dispatcher(disp) # Store the compiled overload for use in the lowering phase if there's # no inlining required (else functions are being compiled which will # never be used as they are inlined) if not self._inline.is_never_inline: # need to run the compiler front end up to type inference to compute # a signature from numba.core import typed_passes, compiler from numba.core.inline_closurecall import InlineWorker fcomp = disp._compiler flags = compiler.Flags() # Updating these causes problems?! #fcomp.targetdescr.options.parse_as_flags(flags, # fcomp.targetoptions) #flags = fcomp._customize_flags(flags) # spoof a compiler pipline like the one that will be in use tyctx = fcomp.targetdescr.typing_context tgctx = fcomp.targetdescr.target_context compiler_inst = fcomp.pipeline_class(tyctx, tgctx, None, None, None, flags, None, ) inline_worker = InlineWorker(tyctx, tgctx, fcomp.locals, compiler_inst, flags, None,) # If the inlinee contains something to trigger literal arg dispatch # then the pipeline call will unconditionally fail due to a raised # ForceLiteralArg exception. Therefore `resolve` is run first, as # type resolution must occur at some point, this will hit any # `literally` calls and because it's going via the dispatcher will # handle them correctly i.e. ForceLiteralArg propagates. This having # the desired effect of ensuring the pipeline call is only made in # situations that will succeed. For context see #5887. resolve = disp_type.dispatcher.get_call_template template, pysig, folded_args, kws = resolve(new_args, kws) ir = inline_worker.run_untyped_passes(disp_type.dispatcher.py_func) typemap, return_type, calltypes = typed_passes.type_inference_stage( self.context, ir, folded_args, None) sig = Signature(return_type, folded_args, None) # this stores a load of info for the cost model function if supplied # it by default is None self._inline_overloads[sig.args] = {'folded_args': folded_args} # this stores the compiled overloads, if there's no compiled # overload available i.e. function is always inlined, the key still # needs to exist for type resolution # NOTE: If lowering is failing on a `_EmptyImplementationEntry`, # the inliner has failed to inline this entry corretly. impl_init = _EmptyImplementationEntry('always inlined') self._compiled_overloads[sig.args] = impl_init if not self._inline.is_always_inline: # this branch is here because a user has supplied a function to # determine whether to inline or not. As a result both compiled # function and inliner info needed, delaying the computation of # this leads to an internal state mess at present. TODO: Fix! sig = disp_type.get_call_type(self.context, new_args, kws) self._compiled_overloads[sig.args] = disp_type.get_overload(sig) # store the inliner information, it's used later in the cost # model function call iinfo = _inline_info(ir, typemap, calltypes, sig) self._inline_overloads[sig.args] = {'folded_args': folded_args, 'iinfo': iinfo} else: sig = disp_type.get_call_type(self.context, new_args, kws) self._compiled_overloads[sig.args] = disp_type.get_overload(sig) return sig def _get_impl(self, args, kws): """Get implementation given the argument types. Returning a Dispatcher object. The Dispatcher object is cached internally in `self._impl_cache`. """ cache_key = self.context, tuple(args), tuple(kws.items()) try: impl, args = self._impl_cache[cache_key] except KeyError: impl, args = self._build_impl(cache_key, args, kws) return impl, args def _build_impl(self, cache_key, args, kws): """Build and cache the implementation. Given the positional (`args`) and keyword arguments (`kws`), obtains the `overload` implementation and wrap it in a Dispatcher object. The expected argument types are returned for use by type-inference. The expected argument types are only different from the given argument types if there is an imprecise type in the given argument types. Parameters ---------- cache_key : hashable The key used for caching the implementation. args : Tuple[Type] Types of positional argument. kws : Dict[Type] Types of keyword argument. Returns ------- disp, args : On success, returns `(Dispatcher, Tuple[Type])`. On failure, returns `(None, None)`. """ from numba import jit # Get the overload implementation for the given types ovf_result = self._overload_func(*args, **kws) if ovf_result is None: # No implementation => fail typing self._impl_cache[cache_key] = None, None return None, None elif isinstance(ovf_result, tuple): # The implementation returned a signature that the type-inferencer # should be using. sig, pyfunc = ovf_result args = sig.args kws = {} cache_key = None # don't cache else: # Regular case pyfunc = ovf_result # Check type of pyfunc if not isinstance(pyfunc, FunctionType): msg = ("Implementator function returned by `@overload` " "has an unexpected type. Got {}") raise AssertionError(msg.format(pyfunc)) # check that the typing and impl sigs match up if self._strict: self._validate_sigs(self._overload_func, pyfunc) # Make dispatcher jitdecor = jit(nopython=True, **self._jit_options) disp = jitdecor(pyfunc) # Make sure that the implementation can be fully compiled disp_type = types.Dispatcher(disp) disp_type.get_call_type(self.context, args, kws) if cache_key is not None: self._impl_cache[cache_key] = disp, args return disp, args def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ return self._compiled_overloads[sig.args] @classmethod def get_source_info(cls): """Return a dictionary with information about the source code of the implementation. Returns ------- info : dict - "kind" : str The implementation kind. - "name" : str The name of the function that provided the definition. - "sig" : str The formatted signature of the function. - "filename" : str The name of the source file. - "lines": tuple (int, int) First and list line number. - "docstring": str The docstring of the definition. """ basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = cls._overload_func code, firstlineno, path = cls.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def get_template_info(self): basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = self._overload_func code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def make_overload_template(func, overload_func, jit_options, strict, inline, prefer_literal=False): """ Make a template class for function *func* overloaded by *overload_func*. Compiler options are passed as a dictionary to *jit_options*. """ func_name = getattr(func, '__name__', str(func)) name = "OverloadTemplate_%s" % (func_name,) base = _OverloadFunctionTemplate dct = dict(key=func, _overload_func=staticmethod(overload_func), _impl_cache={}, _compiled_overloads={}, _jit_options=jit_options, _strict=strict, _inline=staticmethod(InlineOptions(inline)), _inline_overloads={}, prefer_literal=prefer_literal) return type(base)(name, (base,), dct) class _IntrinsicTemplate(AbstractTemplate): """ A base class of templates for intrinsic definition """ def generic(self, args, kws): """ Type the intrinsic by the arguments. """ from numba.core.imputils import lower_builtin cache_key = self.context, args, tuple(kws.items()) try: return self._impl_cache[cache_key] except KeyError: result = self._definition_func(self.context, *args, **kws) if result is None: return [sig, imp] = result pysig = utils.pysignature(self._definition_func) # omit context argument from user function parameters = list(pysig.parameters.values())[1:] sig = sig.replace(pysig=pysig.replace(parameters=parameters)) self._impl_cache[cache_key] = sig self._overload_cache[sig.args] = imp # register the lowering lower_builtin(imp, *sig.args)(imp) return sig def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ return self._overload_cache[sig.args] def get_template_info(self): basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = self._definition_func code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "intrinsic", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def make_intrinsic_template(handle, defn, name): """ Make a template class for a intrinsic handle *handle* defined by the function *defn*. The *name* is used for naming the new template class. """ base = _IntrinsicTemplate name = "_IntrinsicTemplate_%s" % (name) dct = dict(key=handle, _definition_func=staticmethod(defn), _impl_cache={}, _overload_cache={}) return type(base)(name, (base,), dct) class AttributeTemplate(object): _initialized = False def __init__(self, context): self._lazy_class_init() self.context = context def resolve(self, value, attr): return self._resolve(value, attr) @classmethod def _lazy_class_init(cls): if not cls._initialized: cls.do_class_init() cls._initialized = True @classmethod def do_class_init(cls): """ Class-wide initialization. Can be overridden by subclasses to register permanent typing or target hooks. """ def _resolve(self, value, attr): fn = getattr(self, "resolve_%s" % attr, None) if fn is None: fn = self.generic_resolve if fn is NotImplemented: if isinstance(value, types.Module): return self.context.resolve_module_constants(value, attr) else: return None else: return fn(value, attr) else: return fn(value) generic_resolve = NotImplemented class _OverloadAttributeTemplate(AttributeTemplate): """ A base class of templates for @overload_attribute functions. """ is_method = False def __init__(self, context): super(_OverloadAttributeTemplate, self).__init__(context) self.context = context @classmethod def do_class_init(cls): """ Register attribute implementation. """ from numba.core.imputils import lower_getattr attr = cls._attr @lower_getattr(cls.key, attr) def getattr_impl(context, builder, typ, value): typingctx = context.typing_context fnty = cls._get_function_type(typingctx, typ) sig = cls._get_signature(typingctx, fnty, (typ,), {}) call = context.get_function(fnty, sig) return call(builder, (value,)) def _resolve(self, typ, attr): if self._attr != attr: return None fnty = self._get_function_type(self.context, typ) sig = self._get_signature(self.context, fnty, (typ,), {}) # There should only be one template for template in fnty.templates: self._inline_overloads.update(template._inline_overloads) return sig.return_type @classmethod def _get_signature(cls, typingctx, fnty, args, kws): sig = fnty.get_call_type(typingctx, args, kws) sig = sig.replace(pysig=utils.pysignature(cls._overload_func)) return sig @classmethod def _get_function_type(cls, typingctx, typ): return typingctx.resolve_value_type(cls._overload_func) class _OverloadMethodTemplate(_OverloadAttributeTemplate): """ A base class of templates for @overload_method functions. """ is_method = True @classmethod def do_class_init(cls): """ Register generic method implementation. """ from numba.core.imputils import lower_builtin attr = cls._attr @lower_builtin((cls.key, attr), cls.key, types.VarArg(types.Any)) def method_impl(context, builder, sig, args): typ = sig.args[0] typing_context = context.typing_context fnty = cls._get_function_type(typing_context, typ) sig = cls._get_signature(typing_context, fnty, sig.args, {}) call = context.get_function(fnty, sig) # Link dependent library context.add_linking_libs(getattr(call, 'libs', ())) return call(builder, args) def _resolve(self, typ, attr): if self._attr != attr: return None assert isinstance(typ, self.key) class MethodTemplate(AbstractTemplate): key = (self.key, attr) _inline = self._inline _overload_func = staticmethod(self._overload_func) _inline_overloads = self._inline_overloads prefer_literal = self.prefer_literal def generic(_, args, kws): args = (typ,) + tuple(args) fnty = self._get_function_type(self.context, typ) sig = self._get_signature(self.context, fnty, args, kws) sig = sig.replace(pysig=utils.pysignature(self._overload_func)) for template in fnty.templates: self._inline_overloads.update(template._inline_overloads) if sig is not None: return sig.as_method() return types.BoundFunction(MethodTemplate, typ) def make_overload_attribute_template(typ, attr, overload_func, inline, prefer_literal=False, base=_OverloadAttributeTemplate): """ Make a template class for attribute *attr* of *typ* overloaded by *overload_func*. """ assert isinstance(typ, types.Type) or issubclass(typ, types.Type) name = "OverloadAttributeTemplate_%s_%s" % (typ, attr) # Note the implementation cache is subclass-specific dct = dict(key=typ, _attr=attr, _impl_cache={}, _inline=staticmethod(InlineOptions(inline)), _inline_overloads={}, _overload_func=staticmethod(overload_func), prefer_literal=prefer_literal, ) obj = type(base)(name, (base,), dct) return obj def make_overload_method_template(typ, attr, overload_func, inline, prefer_literal=False): """ Make a template class for method *attr* of *typ* overloaded by *overload_func*. """ return make_overload_attribute_template( typ, attr, overload_func, inline=inline, base=_OverloadMethodTemplate, prefer_literal=prefer_literal, ) def bound_function(template_key): """ Wrap an AttributeTemplate resolve_* method to allow it to resolve an instance method's signature rather than a instance attribute. The wrapped method must return the resolved method's signature according to the given self type, args, and keywords. It is used thusly: class ComplexAttributes(AttributeTemplate): @bound_function("complex.conjugate") def resolve_conjugate(self, ty, args, kwds): return ty *template_key* (e.g. "complex.conjugate" above) will be used by the target to look up the method's implementation, as a regular function. """ def wrapper(method_resolver): @functools.wraps(method_resolver) def attribute_resolver(self, ty): class MethodTemplate(AbstractTemplate): key = template_key def generic(_, args, kws): sig = method_resolver(self, ty, args, kws) if sig is not None and sig.recvr is None: sig = sig.replace(recvr=ty) return sig return types.BoundFunction(MethodTemplate, ty) return attribute_resolver return wrapper class MacroTemplate(object): pass # ----------------------------- class Registry(object): """ A registry of typing declarations. The registry stores such declarations for functions, attributes and globals. """ def __init__(self): self.functions = [] self.attributes = [] self.globals = [] def register(self, item): assert issubclass(item, FunctionTemplate) self.functions.append(item) return item def register_attr(self, item): assert issubclass(item, AttributeTemplate) self.attributes.append(item) return item def register_global(self, val=None, typ=None, **kwargs): """ Register the typing of a global value. Functional usage with a Numba type:: register_global(value, typ) Decorator usage with a template class:: @register_global(value, typing_key=None) class Template: ... """ if typ is not None: # register_global(val, typ) assert val is not None assert not kwargs self.globals.append((val, typ)) else: def decorate(cls, typing_key): class Template(cls): key = typing_key if callable(val): typ = types.Function(Template) else: raise TypeError("cannot infer type for global value %r") self.globals.append((val, typ)) return cls # register_global(val, typing_key=None)(<template class>) assert val is not None typing_key = kwargs.pop('typing_key', val) assert not kwargs if typing_key is val: # Check the value is globally reachable, as it is going # to be used as the key. mod = sys.modules[val.__module__] if getattr(mod, val.__name__) is not val: raise ValueError("%r is not globally reachable as '%s.%s'" % (mod, val.__module__, val.__name__)) def decorator(cls): return decorate(cls, typing_key) return decorator class BaseRegistryLoader(object): """ An incremental loader for a registry. Each new call to new_registrations() will iterate over the not yet seen registrations. The reason for this object is multiple: - there can be several contexts - each context wants to install all registrations - registrations can be added after the first installation, so contexts must be able to get the "new" installations Therefore each context maintains its own loaders for each existing registry, without duplicating the registries themselves. """ def __init__(self, registry): self._registrations = dict( (name, utils.stream_list(getattr(registry, name))) for name in self.registry_items) def new_registrations(self, name): for item in next(self._registrations[name]): yield item class RegistryLoader(BaseRegistryLoader): """ An incremental loader for a typing registry. """ registry_items = ('functions', 'attributes', 'globals') builtin_registry = Registry() infer = builtin_registry.register infer_getattr = builtin_registry.register_attr infer_global = builtin_registry.register_global
""" Define typing templates """ from abc import ABC, abstractmethod import functools import sys import inspect import os.path from collections import namedtuple from collections.abc import Sequence from types import MethodType, FunctionType import numba from numba.core import types, utils from numba.core.errors import TypingError, InternalError from numba.core.cpu_options import InlineOptions # info store for inliner callback functions e.g. cost model _inline_info = namedtuple('inline_info', 'func_ir typemap calltypes signature') class Signature(object): """ The signature of a function call or operation, i.e. its argument types and return type. """ # XXX Perhaps the signature should be a BoundArguments, instead # of separate args and pysig... __slots__ = '_return_type', '_args', '_recvr', '_pysig' def __init__(self, return_type, args, recvr, pysig=None): if isinstance(args, list): args = tuple(args) self._return_type = return_type self._args = args self._recvr = recvr self._pysig = pysig @property def return_type(self): return self._return_type @property def args(self): return self._args @property def recvr(self): return self._recvr @property def pysig(self): return self._pysig def replace(self, **kwargs): """Copy and replace the given attributes provided as keyword arguments. Returns an updated copy. """ curstate = dict(return_type=self.return_type, args=self.args, recvr=self.recvr, pysig=self.pysig) curstate.update(kwargs) return Signature(**curstate) def __getstate__(self): """ Needed because of __slots__. """ return self._return_type, self._args, self._recvr, self._pysig def __setstate__(self, state): """ Needed because of __slots__. """ self._return_type, self._args, self._recvr, self._pysig = state def __hash__(self): return hash((self.args, self.return_type)) def __eq__(self, other): if isinstance(other, Signature): return (self.args == other.args and self.return_type == other.return_type and self.recvr == other.recvr and self.pysig == other.pysig) def __ne__(self, other): return not (self == other) def __repr__(self): return "%s -> %s" % (self.args, self.return_type) @property def is_method(self): """ Whether this signature represents a bound method or a regular function. """ return self.recvr is not None def as_method(self): """ Convert this signature to a bound method signature. """ if self.recvr is not None: return self sig = signature(self.return_type, *self.args[1:], recvr=self.args[0]) # Adjust the python signature params = list(self.pysig.parameters.values())[1:] sig = sig.replace( pysig=utils.pySignature( parameters=params, return_annotation=self.pysig.return_annotation, ), ) return sig def as_function(self): """ Convert this signature to a regular function signature. """ if self.recvr is None: return self sig = signature(self.return_type, *((self.recvr,) + self.args)) return sig def as_type(self): """ Convert this signature to a first-class function type. """ return types.FunctionType(self) def __unliteral__(self): return signature(types.unliteral(self.return_type), *map(types.unliteral, self.args)) def dump(self, tab=''): c = self.as_type()._code print(f'{tab}DUMP {type(self).__name__} [type code: {c}]') print(f'{tab} Argument types:') for a in self.args: a.dump(tab=tab + ' | ') print(f'{tab} Return type:') self.return_type.dump(tab=tab + ' | ') print(f'{tab}END DUMP') def is_precise(self): for atype in self.args: if not atype.is_precise(): return False return self.return_type.is_precise() def make_concrete_template(name, key, signatures): baseclasses = (ConcreteTemplate,) gvars = dict(key=key, cases=list(signatures)) return type(name, baseclasses, gvars) def make_callable_template(key, typer, recvr=None): """ Create a callable template with the given key and typer function. """ def generic(self): return typer name = "%s_CallableTemplate" % (key,) bases = (CallableTemplate,) class_dict = dict(key=key, generic=generic, recvr=recvr) return type(name, bases, class_dict) def signature(return_type, *args, **kws): recvr = kws.pop('recvr', None) assert not kws return Signature(return_type, args, recvr=recvr) def fold_arguments(pysig, args, kws, normal_handler, default_handler, stararg_handler): """ Given the signature *pysig*, explicit *args* and *kws*, resolve omitted arguments and keyword arguments. A tuple of positional arguments is returned. Various handlers allow to process arguments: - normal_handler(index, param, value) is called for normal arguments - default_handler(index, param, default) is called for omitted arguments - stararg_handler(index, param, values) is called for a "*args" argument """ if isinstance(kws, Sequence): # Normalize dict kws kws = dict(kws) # deal with kwonly args params = pysig.parameters kwonly = [] for name, p in params.items(): if p.kind == p.KEYWORD_ONLY: kwonly.append(name) if kwonly: bind_args = args[:-len(kwonly)] else: bind_args = args bind_kws = kws.copy() if kwonly: for idx, n in enumerate(kwonly): bind_kws[n] = args[len(kwonly) + idx] # now bind ba = pysig.bind(*bind_args, **bind_kws) for i, param in enumerate(pysig.parameters.values()): name = param.name default = param.default if param.kind == param.VAR_POSITIONAL: # stararg may be omitted, in which case its "default" value # is simply the empty tuple if name in ba.arguments: argval = ba.arguments[name] # NOTE: avoid wrapping the tuple type for stararg in another # tuple. if (len(argval) == 1 and isinstance(argval[0], (types.StarArgTuple, types.StarArgUniTuple))): argval = tuple(argval[0]) else: argval = () out = stararg_handler(i, param, argval) ba.arguments[name] = out elif name in ba.arguments: # Non-stararg, present ba.arguments[name] = normal_handler(i, param, ba.arguments[name]) else: # Non-stararg, omitted assert default is not param.empty ba.arguments[name] = default_handler(i, param, default) # Collect args in the right order args = tuple(ba.arguments[param.name] for param in pysig.parameters.values()) return args class FunctionTemplate(ABC): # Set to true to disable unsafe cast. # subclass overide-able unsafe_casting = True # Set to true to require exact match without casting. # subclass overide-able exact_match_required = False # Set to true to prefer literal arguments. # Useful for definitions that specialize on literal but also support # non-literals. # subclass overide-able prefer_literal = False def __init__(self, context): self.context = context def _select(self, cases, args, kws): options = { 'unsafe_casting': self.unsafe_casting, 'exact_match_required': self.exact_match_required, } selected = self.context.resolve_overload(self.key, cases, args, kws, **options) return selected def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ # Lookup the key on the class, to avoid binding it with `self`. key = type(self).key # On Python 2, we must also take care about unbound methods if isinstance(key, MethodType): assert key.im_self is None key = key.im_func return key @classmethod def get_source_code_info(cls, impl): """ Gets the source information about function impl. Returns: code - str: source code as a string firstlineno - int: the first line number of the function impl path - str: the path to file containing impl if any of the above are not available something generic is returned """ try: code, firstlineno = inspect.getsourcelines(impl) except OSError: # missing source, probably a string code = "None available (built from string?)" firstlineno = 0 path = inspect.getsourcefile(impl) if path is None: path = "<unknown> (built from string?)" return code, firstlineno, path @abstractmethod def get_template_info(self): """ Returns a dictionary with information specific to the template that will govern how error messages are displayed to users. The dictionary must be of the form: info = { 'kind': "unknown", # str: The kind of template, e.g. "Overload" 'name': "unknown", # str: The name of the source function 'sig': "unknown", # str: The signature(s) of the source function 'filename': "unknown", # str: The filename of the source function 'lines': ("start", "end"), # tuple(int, int): The start and end line of the source function. 'docstring': "unknown" # str: The docstring of the source function } """ pass def __str__(self): info = self.get_template_info() srcinfo = f"{info['filename']}:{info['lines'][0]}" return f"<{self.__class__.__name__} {srcinfo}>" __repr__ = __str__ class AbstractTemplate(FunctionTemplate): """ Defines method ``generic(self, args, kws)`` which compute a possible signature base on input types. The signature does not have to match the input types. It is compared against the input types afterwards. """ def apply(self, args, kws): generic = getattr(self, "generic") sig = generic(args, kws) # Enforce that *generic()* must return None or Signature if sig is not None: if not isinstance(sig, Signature): raise AssertionError( "generic() must return a Signature or None. " "{} returned {}".format(generic, type(sig)), ) # Unpack optional type if no matching signature if not sig and any(isinstance(x, types.Optional) for x in args): def unpack_opt(x): if isinstance(x, types.Optional): return x.type else: return x args = list(map(unpack_opt, args)) assert not kws # Not supported yet sig = generic(args, kws) return sig def get_template_info(self): impl = getattr(self, "generic") basepath = os.path.dirname(os.path.dirname(numba.__file__)) code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info class CallableTemplate(FunctionTemplate): """ Base class for a template defining a ``generic(self)`` method returning a callable to be called with the actual ``*args`` and ``**kwargs`` representing the call signature. The callable has to return a return type, a full signature, or None. The signature does not have to match the input types. It is compared against the input types afterwards. """ recvr = None def apply(self, args, kws): generic = getattr(self, "generic") typer = generic() sig = typer(*args, **kws) # Unpack optional type if no matching signature if sig is None: if any(isinstance(x, types.Optional) for x in args): def unpack_opt(x): if isinstance(x, types.Optional): return x.type else: return x args = list(map(unpack_opt, args)) sig = typer(*args, **kws) if sig is None: return # Get the pysig try: pysig = typer.pysig except AttributeError: pysig = utils.pysignature(typer) # Fold any keyword arguments bound = pysig.bind(*args, **kws) if bound.kwargs: raise TypingError("unsupported call signature") if not isinstance(sig, Signature): # If not a signature, `sig` is assumed to be the return type if not isinstance(sig, types.Type): raise TypeError("invalid return type for callable template: " "got %r" % (sig,)) sig = signature(sig, *bound.args) if self.recvr is not None: sig = sig.replace(recvr=self.recvr) # Hack any omitted parameters out of the typer's pysig, # as lowering expects an exact match between formal signature # and actual args. if len(bound.args) < len(pysig.parameters): parameters = list(pysig.parameters.values())[:len(bound.args)] pysig = pysig.replace(parameters=parameters) sig = sig.replace(pysig=pysig) cases = [sig] return self._select(cases, bound.args, bound.kwargs) def get_template_info(self): impl = getattr(self, "generic") basepath = os.path.dirname(os.path.dirname(numba.__file__)) code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(self.key, '__name__', getattr(impl, '__qualname__', impl.__name__),), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info class ConcreteTemplate(FunctionTemplate): """ Defines attributes "cases" as a list of signature to match against the given input types. """ def apply(self, args, kws): cases = getattr(self, 'cases') return self._select(cases, args, kws) def get_template_info(self): import operator name = getattr(self.key, '__name__', "unknown") op_func = getattr(operator, name, None) kind = "Type restricted function" if op_func is not None: if self.key is op_func: kind = "operator overload" info = { 'kind': kind, 'name': name, 'sig': "unknown", 'filename': "unknown", 'lines': ("unknown", "unknown"), 'docstring': "unknown" } return info class _EmptyImplementationEntry(InternalError): def __init__(self, reason): super(_EmptyImplementationEntry, self).__init__( "_EmptyImplementationEntry({!r})".format(reason), ) class _OverloadFunctionTemplate(AbstractTemplate): """ A base class of templates for overload functions. """ def _validate_sigs(self, typing_func, impl_func): # check that the impl func and the typing func have the same signature! typing_sig = utils.pysignature(typing_func) impl_sig = utils.pysignature(impl_func) # the typing signature is considered golden and must be adhered to by # the implementation... # Things that are valid: # 1. args match exactly # 2. kwargs match exactly in name and default value # 3. Use of *args in the same location by the same name in both typing # and implementation signature # 4. Use of *args in the implementation signature to consume any number # of arguments in the typing signature. # Things that are invalid: # 5. Use of *args in the typing signature that is not replicated # in the implementing signature # 6. Use of **kwargs def get_args_kwargs(sig): kws = [] args = [] pos_arg = None for x in sig.parameters.values(): if x.default == utils.pyParameter.empty: args.append(x) if x.kind == utils.pyParameter.VAR_POSITIONAL: pos_arg = x elif x.kind == utils.pyParameter.VAR_KEYWORD: msg = ("The use of VAR_KEYWORD (e.g. **kwargs) is " "unsupported. (offending argument name is '%s')") raise InternalError(msg % x) else: kws.append(x) return args, kws, pos_arg ty_args, ty_kws, ty_pos = get_args_kwargs(typing_sig) im_args, im_kws, im_pos = get_args_kwargs(impl_sig) sig_fmt = ("Typing signature: %s\n" "Implementation signature: %s") sig_str = sig_fmt % (typing_sig, impl_sig) err_prefix = "Typing and implementation arguments differ in " a = ty_args b = im_args if ty_pos: if not im_pos: # case 5. described above msg = ("VAR_POSITIONAL (e.g. *args) argument kind (offending " "argument name is '%s') found in the typing function " "signature, but is not in the implementing function " "signature.\n%s") % (ty_pos, sig_str) raise InternalError(msg) else: if im_pos: # no *args in typing but there's a *args in the implementation # this is case 4. described above b = im_args[:im_args.index(im_pos)] try: a = ty_args[:ty_args.index(b[-1]) + 1] except ValueError: # there's no b[-1] arg name in the ty_args, something is # very wrong, we can't work out a diff (*args consumes # unknown quantity of args) so just report first error specialized = "argument names.\n%s\nFirst difference: '%s'" msg = err_prefix + specialized % (sig_str, b[-1]) raise InternalError(msg) def gen_diff(typing, implementing): diff = set(typing) ^ set(implementing) return "Difference: %s" % diff if a != b: specialized = "argument names.\n%s\n%s" % (sig_str, gen_diff(a, b)) raise InternalError(err_prefix + specialized) # ensure kwargs are the same ty = [x.name for x in ty_kws] im = [x.name for x in im_kws] if ty != im: specialized = "keyword argument names.\n%s\n%s" msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws)) raise InternalError(msg) same = [x.default for x in ty_kws] == [x.default for x in im_kws] if not same: specialized = "keyword argument default values.\n%s\n%s" msg = err_prefix + specialized % (sig_str, gen_diff(ty_kws, im_kws)) raise InternalError(msg) def generic(self, args, kws): """ Type the overloaded function by compiling the appropriate implementation for the given args. """ disp, new_args = self._get_impl(args, kws) if disp is None: return # Compile and type it for the given types disp_type = types.Dispatcher(disp) # Store the compiled overload for use in the lowering phase if there's # no inlining required (else functions are being compiled which will # never be used as they are inlined) if not self._inline.is_never_inline: # need to run the compiler front end up to type inference to compute # a signature from numba.core import typed_passes, compiler from numba.core.inline_closurecall import InlineWorker fcomp = disp._compiler flags = compiler.Flags() # Updating these causes problems?! #fcomp.targetdescr.options.parse_as_flags(flags, # fcomp.targetoptions) #flags = fcomp._customize_flags(flags) # spoof a compiler pipline like the one that will be in use tyctx = fcomp.targetdescr.typing_context tgctx = fcomp.targetdescr.target_context compiler_inst = fcomp.pipeline_class(tyctx, tgctx, None, None, None, flags, None, ) inline_worker = InlineWorker(tyctx, tgctx, fcomp.locals, compiler_inst, flags, None,) # If the inlinee contains something to trigger literal arg dispatch # then the pipeline call will unconditionally fail due to a raised # ForceLiteralArg exception. Therefore `resolve` is run first, as # type resolution must occur at some point, this will hit any # `literally` calls and because it's going via the dispatcher will # handle them correctly i.e. ForceLiteralArg propagates. This having # the desired effect of ensuring the pipeline call is only made in # situations that will succeed. For context see #5887. resolve = disp_type.dispatcher.get_call_template template, pysig, folded_args, kws = resolve(new_args, kws) ir = inline_worker.run_untyped_passes(disp_type.dispatcher.py_func) typemap, return_type, calltypes = typed_passes.type_inference_stage( self.context, ir, folded_args, None) sig = Signature(return_type, folded_args, None) # this stores a load of info for the cost model function if supplied # it by default is None self._inline_overloads[sig.args] = {'folded_args': folded_args} # this stores the compiled overloads, if there's no compiled # overload available i.e. function is always inlined, the key still # needs to exist for type resolution # NOTE: If lowering is failing on a `_EmptyImplementationEntry`, # the inliner has failed to inline this entry corretly. impl_init = _EmptyImplementationEntry('always inlined') self._compiled_overloads[sig.args] = impl_init if not self._inline.is_always_inline: # this branch is here because a user has supplied a function to # determine whether to inline or not. As a result both compiled # function and inliner info needed, delaying the computation of # this leads to an internal state mess at present. TODO: Fix! sig = disp_type.get_call_type(self.context, new_args, kws) self._compiled_overloads[sig.args] = disp_type.get_overload(sig) # store the inliner information, it's used later in the cost # model function call iinfo = _inline_info(ir, typemap, calltypes, sig) self._inline_overloads[sig.args] = {'folded_args': folded_args, 'iinfo': iinfo} else: sig = disp_type.get_call_type(self.context, new_args, kws) self._compiled_overloads[sig.args] = disp_type.get_overload(sig) return sig def _get_impl(self, args, kws): """Get implementation given the argument types. Returning a Dispatcher object. The Dispatcher object is cached internally in `self._impl_cache`. """ cache_key = self.context, tuple(args), tuple(kws.items()) try: impl, args = self._impl_cache[cache_key] except KeyError: impl, args = self._build_impl(cache_key, args, kws) return impl, args def _build_impl(self, cache_key, args, kws): """Build and cache the implementation. Given the positional (`args`) and keyword arguments (`kws`), obtains the `overload` implementation and wrap it in a Dispatcher object. The expected argument types are returned for use by type-inference. The expected argument types are only different from the given argument types if there is an imprecise type in the given argument types. Parameters ---------- cache_key : hashable The key used for caching the implementation. args : Tuple[Type] Types of positional argument. kws : Dict[Type] Types of keyword argument. Returns ------- disp, args : On success, returns `(Dispatcher, Tuple[Type])`. On failure, returns `(None, None)`. """ from numba import jit # Get the overload implementation for the given types ovf_result = self._overload_func(*args, **kws) if ovf_result is None: # No implementation => fail typing self._impl_cache[cache_key] = None, None return None, None elif isinstance(ovf_result, tuple): # The implementation returned a signature that the type-inferencer # should be using. sig, pyfunc = ovf_result args = sig.args kws = {} cache_key = None # don't cache else: # Regular case pyfunc = ovf_result # Check type of pyfunc if not isinstance(pyfunc, FunctionType): msg = ("Implementator function returned by `@overload` " "has an unexpected type. Got {}") raise AssertionError(msg.format(pyfunc)) # check that the typing and impl sigs match up if self._strict: self._validate_sigs(self._overload_func, pyfunc) # Make dispatcher jitdecor = jit(nopython=True, **self._jit_options) disp = jitdecor(pyfunc) # Make sure that the implementation can be fully compiled disp_type = types.Dispatcher(disp) disp_type.get_call_type(self.context, args, kws) if cache_key is not None: self._impl_cache[cache_key] = disp, args return disp, args def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ return self._compiled_overloads[sig.args] @classmethod def get_source_info(cls): """Return a dictionary with information about the source code of the implementation. Returns ------- info : dict - "kind" : str The implementation kind. - "name" : str The name of the function that provided the definition. - "sig" : str The formatted signature of the function. - "filename" : str The name of the source file. - "lines": tuple (int, int) First and list line number. - "docstring": str The docstring of the definition. """ basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = cls._overload_func code, firstlineno, path = cls.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def get_template_info(self): basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = self._overload_func code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "overload", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def make_overload_template(func, overload_func, jit_options, strict, inline, prefer_literal=False): """ Make a template class for function *func* overloaded by *overload_func*. Compiler options are passed as a dictionary to *jit_options*. """ func_name = getattr(func, '__name__', str(func)) name = "OverloadTemplate_%s" % (func_name,) base = _OverloadFunctionTemplate dct = dict(key=func, _overload_func=staticmethod(overload_func), _impl_cache={}, _compiled_overloads={}, _jit_options=jit_options, _strict=strict, _inline=staticmethod(InlineOptions(inline)), _inline_overloads={}, prefer_literal=prefer_literal) return type(base)(name, (base,), dct) class _IntrinsicTemplate(AbstractTemplate): """ A base class of templates for intrinsic definition """ def generic(self, args, kws): """ Type the intrinsic by the arguments. """ from numba.core.imputils import lower_builtin cache_key = self.context, args, tuple(kws.items()) try: return self._impl_cache[cache_key] except KeyError: result = self._definition_func(self.context, *args, **kws) if result is None: return [sig, imp] = result pysig = utils.pysignature(self._definition_func) # omit context argument from user function parameters = list(pysig.parameters.values())[1:] sig = sig.replace(pysig=pysig.replace(parameters=parameters)) self._impl_cache[cache_key] = sig self._overload_cache[sig.args] = imp # register the lowering lower_builtin(imp, *sig.args)(imp) return sig def get_impl_key(self, sig): """ Return the key for looking up the implementation for the given signature on the target context. """ return self._overload_cache[sig.args] def get_template_info(self): basepath = os.path.dirname(os.path.dirname(numba.__file__)) impl = self._definition_func code, firstlineno, path = self.get_source_code_info(impl) sig = str(utils.pysignature(impl)) info = { 'kind': "intrinsic", 'name': getattr(impl, '__qualname__', impl.__name__), 'sig': sig, 'filename': utils.safe_relpath(path, start=basepath), 'lines': (firstlineno, firstlineno + len(code) - 1), 'docstring': impl.__doc__ } return info def make_intrinsic_template(handle, defn, name): """ Make a template class for a intrinsic handle *handle* defined by the function *defn*. The *name* is used for naming the new template class. """ base = _IntrinsicTemplate name = "_IntrinsicTemplate_%s" % (name) dct = dict(key=handle, _definition_func=staticmethod(defn), _impl_cache={}, _overload_cache={}) return type(base)(name, (base,), dct) class AttributeTemplate(object): _initialized = False def __init__(self, context): self._lazy_class_init() self.context = context def resolve(self, value, attr): return self._resolve(value, attr) @classmethod def _lazy_class_init(cls): if not cls._initialized: cls.do_class_init() cls._initialized = True @classmethod def do_class_init(cls): """ Class-wide initialization. Can be overridden by subclasses to register permanent typing or target hooks. """ def _resolve(self, value, attr): fn = getattr(self, "resolve_%s" % attr, None) if fn is None: fn = self.generic_resolve if fn is NotImplemented: if isinstance(value, types.Module): return self.context.resolve_module_constants(value, attr) else: return None else: return fn(value, attr) else: return fn(value) generic_resolve = NotImplemented class _OverloadAttributeTemplate(AttributeTemplate): """ A base class of templates for @overload_attribute functions. """ is_method = False def __init__(self, context): super(_OverloadAttributeTemplate, self).__init__(context) self.context = context @classmethod def do_class_init(cls): """ Register attribute implementation. """ from numba.core.imputils import lower_getattr attr = cls._attr @lower_getattr(cls.key, attr) def getattr_impl(context, builder, typ, value): typingctx = context.typing_context fnty = cls._get_function_type(typingctx, typ) sig = cls._get_signature(typingctx, fnty, (typ,), {}) call = context.get_function(fnty, sig) return call(builder, (value,)) def _resolve(self, typ, attr): if self._attr != attr: return None fnty = self._get_function_type(self.context, typ) sig = self._get_signature(self.context, fnty, (typ,), {}) # There should only be one template for template in fnty.templates: self._inline_overloads.update(template._inline_overloads) return sig.return_type @classmethod def _get_signature(cls, typingctx, fnty, args, kws): sig = fnty.get_call_type(typingctx, args, kws) sig = sig.replace(pysig=utils.pysignature(cls._overload_func)) return sig @classmethod def _get_function_type(cls, typingctx, typ): return typingctx.resolve_value_type(cls._overload_func) class _OverloadMethodTemplate(_OverloadAttributeTemplate): """ A base class of templates for @overload_method functions. """ is_method = True @classmethod def do_class_init(cls): """ Register generic method implementation. """ from numba.core.imputils import lower_builtin attr = cls._attr @lower_builtin((cls.key, attr), cls.key, types.VarArg(types.Any)) def method_impl(context, builder, sig, args): typ = sig.args[0] typing_context = context.typing_context fnty = cls._get_function_type(typing_context, typ) sig = cls._get_signature(typing_context, fnty, sig.args, {}) call = context.get_function(fnty, sig) # Link dependent library context.add_linking_libs(getattr(call, 'libs', ())) return call(builder, args) def _resolve(self, typ, attr): if self._attr != attr: return None assert isinstance(typ, self.key) class MethodTemplate(AbstractTemplate): key = (self.key, attr) _inline = self._inline _overload_func = staticmethod(self._overload_func) _inline_overloads = self._inline_overloads prefer_literal = self.prefer_literal def generic(_, args, kws): args = (typ,) + tuple(args) fnty = self._get_function_type(self.context, typ) sig = self._get_signature(self.context, fnty, args, kws) sig = sig.replace(pysig=utils.pysignature(self._overload_func)) for template in fnty.templates: self._inline_overloads.update(template._inline_overloads) if sig is not None: return sig.as_method() return types.BoundFunction(MethodTemplate, typ) def make_overload_attribute_template(typ, attr, overload_func, inline, prefer_literal=False, base=_OverloadAttributeTemplate): """ Make a template class for attribute *attr* of *typ* overloaded by *overload_func*. """ assert isinstance(typ, types.Type) or issubclass(typ, types.Type) name = "OverloadAttributeTemplate_%s_%s" % (typ, attr) # Note the implementation cache is subclass-specific dct = dict(key=typ, _attr=attr, _impl_cache={}, _inline=staticmethod(InlineOptions(inline)), _inline_overloads={}, _overload_func=staticmethod(overload_func), prefer_literal=prefer_literal, ) obj = type(base)(name, (base,), dct) return obj def make_overload_method_template(typ, attr, overload_func, inline, prefer_literal=False): """ Make a template class for method *attr* of *typ* overloaded by *overload_func*. """ return make_overload_attribute_template( typ, attr, overload_func, inline=inline, base=_OverloadMethodTemplate, prefer_literal=prefer_literal, ) def bound_function(template_key): """ Wrap an AttributeTemplate resolve_* method to allow it to resolve an instance method's signature rather than a instance attribute. The wrapped method must return the resolved method's signature according to the given self type, args, and keywords. It is used thusly: class ComplexAttributes(AttributeTemplate): @bound_function("complex.conjugate") def resolve_conjugate(self, ty, args, kwds): return ty *template_key* (e.g. "complex.conjugate" above) will be used by the target to look up the method's implementation, as a regular function. """ def wrapper(method_resolver): @functools.wraps(method_resolver) def attribute_resolver(self, ty): class MethodTemplate(AbstractTemplate): key = template_key def generic(_, args, kws): sig = method_resolver(self, ty, args, kws) if sig is not None and sig.recvr is None: sig = sig.replace(recvr=ty) return sig return types.BoundFunction(MethodTemplate, ty) return attribute_resolver return wrapper class MacroTemplate(object): pass # ----------------------------- class Registry(object): """ A registry of typing declarations. The registry stores such declarations for functions, attributes and globals. """ def __init__(self): self.functions = [] self.attributes = [] self.globals = [] def register(self, item): assert issubclass(item, FunctionTemplate) self.functions.append(item) return item def register_attr(self, item): assert issubclass(item, AttributeTemplate) self.attributes.append(item) return item def register_global(self, val=None, typ=None, **kwargs): """ Register the typing of a global value. Functional usage with a Numba type:: register_global(value, typ) Decorator usage with a template class:: @register_global(value, typing_key=None) class Template: ... """ if typ is not None: # register_global(val, typ) assert val is not None assert not kwargs self.globals.append((val, typ)) else: def decorate(cls, typing_key): class Template(cls): key = typing_key if callable(val): typ = types.Function(Template) else: raise TypeError("cannot infer type for global value %r") self.globals.append((val, typ)) return cls # register_global(val, typing_key=None)(<template class>) assert val is not None typing_key = kwargs.pop('typing_key', val) assert not kwargs if typing_key is val: # Check the value is globally reachable, as it is going # to be used as the key. mod = sys.modules[val.__module__] if getattr(mod, val.__name__) is not val: raise ValueError("%r is not globally reachable as '%s.%s'" % (mod, val.__module__, val.__name__)) def decorator(cls): return decorate(cls, typing_key) return decorator class BaseRegistryLoader(object): """ An incremental loader for a registry. Each new call to new_registrations() will iterate over the not yet seen registrations. The reason for this object is multiple: - there can be several contexts - each context wants to install all registrations - registrations can be added after the first installation, so contexts must be able to get the "new" installations Therefore each context maintains its own loaders for each existing registry, without duplicating the registries themselves. """ def __init__(self, registry): self._registrations = dict( (name, utils.stream_list(getattr(registry, name))) for name in self.registry_items) def new_registrations(self, name): for item in next(self._registrations[name]): yield item class RegistryLoader(BaseRegistryLoader): """ An incremental loader for a typing registry. """ registry_items = ('functions', 'attributes', 'globals') builtin_registry = Registry() infer = builtin_registry.register infer_getattr = builtin_registry.register_attr infer_global = builtin_registry.register_global
import os import re import sys import importlib from aq.cli.commands import AQCommand class Command(AQCommand): description = "Displays this help message" def run(self): print("\nAzure Query CLI\n") print("This tool provides an easy to use CLI implementation of the Microsoft Graph API REST interface") print(f"Usage: {os.path.basename(sys.argv[0])} [subcommand] [options]\n") print("List of Sub Commands:") sub_command_path = os.path.dirname(__file__) max_length = 0 sub_commands = [] for sub_command in os.listdir(sub_command_path): if re.match("^__.*", sub_command) or not re.match('.*\.py$', sub_command): continue else: sub_commands.append(sub_command[:-3]) if len(sub_command) > max_length: max_length = len(sub_command) for sub_command in sub_commands: command_module = importlib.import_module(f"aq.cli.commands.{sub_command}") description = command_module.Command.description print(f"{sub_command.rjust(max_length + 3, " ")} : {description}")
import os import re import sys import importlib from aq.cli.commands import AQCommand class Command(AQCommand): description = "Displays this help message" def run(self): print("\nAzure Query CLI\n") print("This tool provides an easy to use CLI implementation of the Microsoft Graph API REST interface") print(f"Usage: {os.path.basename(sys.argv[0])} [subcommand] [options]\n") print("List of Sub Commands:") sub_command_path = os.path.dirname(__file__) max_length = 0 sub_commands = [] for sub_command in os.listdir(sub_command_path): if re.match("^__.*", sub_command) or not re.match('.*\.py$', sub_command): continue else: sub_commands.append(sub_command[:-3]) if len(sub_command) > max_length: max_length = len(sub_command) for sub_command in sub_commands: command_module = importlib.import_module(f"aq.cli.commands.{sub_command}") description = command_module.Command.description print(f"{sub_command.rjust(max_length + 3, ' ')} : {description}")
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid from dataclasses import dataclass from dataclasses import field from typing import List, Iterable import requests from metadata.generated.schema.entity.data.chart import Chart from metadata.generated.schema.type.entityReference import EntityReference from metadata.ingestion.api.common import ConfigModel, Record, WorkflowContext from metadata.ingestion.api.source import Source from metadata.ingestion.api.source import SourceStatus from metadata.ingestion.models.table_metadata import Dashboard from metadata.ingestion.ometa.openmetadata_rest import MetadataServerConfig from redash_toolbelt import Redash from metadata.utils.helpers import get_dashboard_service_or_create from metadata.generated.schema.entity.services.dashboardService import DashboardServiceType class RedashSourceConfig(ConfigModel): uri: str = "http://localhost:5000" username: str = "" api_key: str service_name: str service_type: str = "Redash" @dataclass class RedashSourceStatus(SourceStatus): items_scanned: int = 0 filtered: List[str] = field(default_factory=list) def item_scanned_status(self) -> None: self.items_scanned += 1 def item_dropped_status(self, item: str) -> None: self.filtered.append(item) class RedashSource(Source): config: RedashSourceConfig metadata_config: MetadataServerConfig status: RedashSourceStatus platform = "redash" def __init__(self, config: RedashSourceConfig, metadata_config: MetadataServerConfig, ctx: WorkflowContext): super().__init__(ctx) self.config = config self.metadata_config = metadata_config self.status = RedashSourceStatus() self.client = Redash(self.config.uri, self.config.api_key) self.service = get_dashboard_service_or_create(config.service_name, DashboardServiceType.Redash.name, config.username, config.api_key, config.uri, metadata_config) @classmethod def create(cls, config_dict: dict, metadata_config_dict: dict, ctx: WorkflowContext): config = RedashSourceConfig.parse_obj(config_dict) metadata_config = MetadataServerConfig.parse_obj(metadata_config_dict) return cls(config, metadata_config, ctx) def prepare(self): pass def next_record(self) -> Iterable[Record]: yield from self.get_redash_charts() yield from self.get_redash_dashboard() def get_redash_charts(self) -> Chart: query_info = self.client.queries() for query_info in query_info["results"]: query_id = query_info["id"] query_name = query_info["name"] query_data = requests.get(f"{self.config.uri}/api/queries/{query_id}").json() for visualization in query_data.get("Visualizations", []): chart_type = visualization.get("type", "") chart_description = visualization.get("description", "") if visualization.get("description", "") else "" yield Chart( id=uuid.uuid4(), name=query_id, displayName=query_name, chartType=chart_type, service=EntityReference(id=self.service.id, type="dashboardService"), description=chart_description, ) def get_redash_dashboard(self) -> Dashboard: charts: List[Chart] = [] dashboard_info = self.client.dashboards() for dashboard_info in dashboard_info["results"]: dashboard_id = dashboard_info["id"] if dashboard_info["id"] is not None: self.status.item_scanned_status() dashboard_data = self.client.dashboard(dashboard_id) dashboard_url = f"{self.config.uri}/dashboard/{dashboard_data.get("slug", "")}" for widgets in dashboard_data.get("widgets", []): dashboard_description = widgets.get("text") yield Dashboard( id=uuid.uuid4(), name=dashboard_info["id"], displayName=dashboard_info["name"], description=dashboard_description if dashboard_info else "", charts=charts, usageSummary=None, service=EntityReference(id=self.service.id, type="dashboardService"), url=dashboard_url ) def get_status(self) -> SourceStatus: return self.status
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import uuid from dataclasses import dataclass from dataclasses import field from typing import List, Iterable import requests from metadata.generated.schema.entity.data.chart import Chart from metadata.generated.schema.type.entityReference import EntityReference from metadata.ingestion.api.common import ConfigModel, Record, WorkflowContext from metadata.ingestion.api.source import Source from metadata.ingestion.api.source import SourceStatus from metadata.ingestion.models.table_metadata import Dashboard from metadata.ingestion.ometa.openmetadata_rest import MetadataServerConfig from redash_toolbelt import Redash from metadata.utils.helpers import get_dashboard_service_or_create from metadata.generated.schema.entity.services.dashboardService import DashboardServiceType class RedashSourceConfig(ConfigModel): uri: str = "http://localhost:5000" username: str = "" api_key: str service_name: str service_type: str = "Redash" @dataclass class RedashSourceStatus(SourceStatus): items_scanned: int = 0 filtered: List[str] = field(default_factory=list) def item_scanned_status(self) -> None: self.items_scanned += 1 def item_dropped_status(self, item: str) -> None: self.filtered.append(item) class RedashSource(Source): config: RedashSourceConfig metadata_config: MetadataServerConfig status: RedashSourceStatus platform = "redash" def __init__(self, config: RedashSourceConfig, metadata_config: MetadataServerConfig, ctx: WorkflowContext): super().__init__(ctx) self.config = config self.metadata_config = metadata_config self.status = RedashSourceStatus() self.client = Redash(self.config.uri, self.config.api_key) self.service = get_dashboard_service_or_create(config.service_name, DashboardServiceType.Redash.name, config.username, config.api_key, config.uri, metadata_config) @classmethod def create(cls, config_dict: dict, metadata_config_dict: dict, ctx: WorkflowContext): config = RedashSourceConfig.parse_obj(config_dict) metadata_config = MetadataServerConfig.parse_obj(metadata_config_dict) return cls(config, metadata_config, ctx) def prepare(self): pass def next_record(self) -> Iterable[Record]: yield from self.get_redash_charts() yield from self.get_redash_dashboard() def get_redash_charts(self) -> Chart: query_info = self.client.queries() for query_info in query_info["results"]: query_id = query_info["id"] query_name = query_info["name"] query_data = requests.get(f"{self.config.uri}/api/queries/{query_id}").json() for visualization in query_data.get("Visualizations", []): chart_type = visualization.get("type", "") chart_description = visualization.get("description", "") if visualization.get("description", "") else "" yield Chart( id=uuid.uuid4(), name=query_id, displayName=query_name, chartType=chart_type, service=EntityReference(id=self.service.id, type="dashboardService"), description=chart_description, ) def get_redash_dashboard(self) -> Dashboard: charts: List[Chart] = [] dashboard_info = self.client.dashboards() for dashboard_info in dashboard_info["results"]: dashboard_id = dashboard_info["id"] if dashboard_info["id"] is not None: self.status.item_scanned_status() dashboard_data = self.client.dashboard(dashboard_id) dashboard_url = f"{self.config.uri}/dashboard/{dashboard_data.get('slug', '')}" for widgets in dashboard_data.get("widgets", []): dashboard_description = widgets.get("text") yield Dashboard( id=uuid.uuid4(), name=dashboard_info["id"], displayName=dashboard_info["name"], description=dashboard_description if dashboard_info else "", charts=charts, usageSummary=None, service=EntityReference(id=self.service.id, type="dashboardService"), url=dashboard_url ) def get_status(self) -> SourceStatus: return self.status
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module for kanging stickers or making new ones. Thanks @rupansh""" import io import math import random import urllib.request from os import remove from PIL import Image from telethon.tl.functions.messages import GetStickerSetRequest from telethon.tl.types import ( DocumentAttributeFilename, DocumentAttributeSticker, InputStickerSetID, MessageMediaPhoto, ) from userbot import CMD_HELP, bot from userbot.events import register KANGING_STR = [ "Eh... Koq bagus... aku curry ahhh :3", "Aku curry ya kakak :)", "Curry Sticker dulu yee kan", "ehh, mantep nih.....aku ambil ya kaka", "Bagus eaaaa....\nAmbil ahh....", "Ini Sticker aku ambil yaa\nDUARR!", "leh ugha ni Sticker\nCurry ahh~", "Pim Pim Pom!!!\nni Sticker punya aing sekarang hehe", "Bentar boss, ane curry dulu", "Ihh, bagus nih\nCurry ahh~", "Curry lagi yee kan.....", "CURRY TROSS!!!", "Curry Sticker ahh.....", "Curry dolo boss", "Swiper jangan mencurry", ] @register(outgoing=True, pattern=r"^\.curry") async def kang(args): """For .kang command, kangs stickers or creates new ones.""" user = await bot.get_me() if not user.username: user.username = user.first_name message = await args.get_reply_message() photo = None emojibypass = False is_anim = False emoji = None if not message or not message.media: return await args.edit("`I can't kang that...`") if isinstance(message.media, MessageMediaPhoto): await args.edit(f"`{random.choice(KANGING_STR)}`") photo = io.BytesIO() photo = await bot.download_media(message.photo, photo) elif "image" in message.media.document.mime_type.split("/"): await args.edit(f"`{random.choice(KANGING_STR)}`") photo = io.BytesIO() await bot.download_file(message.media.document, photo) if ( DocumentAttributeFilename(file_name="sticker.webp") in message.media.document.attributes ): emoji = message.media.document.attributes[1].alt if emoji != "": emojibypass = True elif "tgsticker" in message.media.document.mime_type: await args.edit(f"`{random.choice(KANGING_STR)}`") await bot.download_file(message.media.document, "AnimatedSticker.tgs") attributes = message.media.document.attributes for attribute in attributes: if isinstance(attribute, DocumentAttributeSticker): emoji = attribute.alt emojibypass = True is_anim = True photo = 1 else: return await args.edit("`Unsupported File!`") if photo: splat = args.text.split() if not emojibypass: emoji = "🤔" pack = 1 if len(splat) == 3: pack = splat[2] # User sent both emoji = splat[1] elif len(splat) == 2: if splat[1].isnumeric(): # User wants to push into different pack, but is okay with # thonk as emote. pack = int(splat[1]) else: # User sent just custom emote, wants to push to default # pack emoji = splat[1] packname = f"a{user.id}_by_{user.username}_{pack}" packnick = f"@{user.username}'s kang pack Vol.{pack}" cmd = "/newpack" file = io.BytesIO() if not is_anim: image = await resize_photo(photo) file.name = "sticker.png" image.save(file, "PNG") else: packname += "_anim" packnick += " (Animated)" cmd = "/newanimated" response = urllib.request.urlopen( urllib.request.Request(f"http://t.me/addstickers/{packname}") ) htmlstr = response.read().decode("utf8").split("\n") if ( " A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in htmlstr ): async with bot.conversation("Stickers") as conv: await conv.send_message("/addsticker") await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packname) x = await conv.get_response() while "120" in x.text: pack += 1 packname = f"a{user.id}_by_{user.username}_{pack}" packnick = f"@{user.username}'s kang pack Vol.{pack}" await args.edit( "`Switching to Pack " + str(pack) + " due to insufficient space`" ) await conv.send_message(packname) x = await conv.get_response() if x.text == "Invalid pack selected.": await conv.send_message(cmd) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packnick) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) await conv.get_response() await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/publish") if is_anim: await conv.get_response() await conv.send_message(f"<{packnick}>") # Ensure user doesn't get spamming notifications await conv.get_response() await bot.send_read_acknowledge(conv.chat_id) await conv.send_message("/skip") # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message(packname) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) return await args.edit( "`Sticker added in a Different Pack !" "\nThis Pack is Newly created!" f"\nYour pack can be found [here](t.me/addstickers/{packname})", parse_mode="md", ) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) rsp = await conv.get_response() if "Sorry, the file type is invalid." in rsp.text: return await args.edit( "`Failed to add sticker, use` @Stickers `bot to add the sticker manually.`" ) await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/done") await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) else: await args.edit("`Brewing a new Pack...`") async with bot.conversation("Stickers") as conv: await conv.send_message(cmd) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packnick) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) rsp = await conv.get_response() if "Sorry, the file type is invalid." in rsp.text: return await args.edit( "`Failed to add sticker, use` @Stickers `bot to add the sticker manually.`" ) await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/publish") if is_anim: await conv.get_response() await conv.send_message(f"<{packnick}>") # Ensure user doesn't get spamming notifications await conv.get_response() await bot.send_read_acknowledge(conv.chat_id) await conv.send_message("/skip") # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message(packname) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await args.edit( "Curry Success!" f"\n[Klik Disini](t.me/addstickers/{packname})", parse_mode="md", ) async def resize_photo(photo): """Resize the given photo to 512x512""" image = Image.open(photo) if (image.width and image.height) < 512: size1 = image.width size2 = image.height if image.width > image.height: scale = 512 / size1 size1new = 512 size2new = size2 * scale else: scale = 512 / size2 size1new = size1 * scale size2new = 512 size1new = math.floor(size1new) size2new = math.floor(size2new) sizenew = (size1new, size2new) image = image.resize(sizenew) else: maxsize = (512, 512) image.thumbnail(maxsize) return image @register(outgoing=True, pattern=r"^\.stkrinfo$") async def get_pack_info(event): if not event.is_reply: return await event.edit("`I can't fetch info from nothing, can I ?!`") rep_msg = await event.get_reply_message() if not rep_msg.document: return await event.edit("`Reply to a sticker to get the pack details`") try: stickerset_attr = rep_msg.document.attributes[1] await event.edit("`Fetching details of the sticker pack, please wait..`") except BaseException: return await event.edit("`This is not a sticker. Reply to a sticker.`") if not isinstance(stickerset_attr, DocumentAttributeSticker): return await event.edit("`This is not a sticker. Reply to a sticker.`") get_stickerset = await bot( GetStickerSetRequest( InputStickerSetID( id=stickerset_attr.stickerset.id, access_hash=stickerset_attr.stickerset.access_hash, ) ) ) pack_emojis = [] for document_sticker in get_stickerset.packs: if document_sticker.emoticon not in pack_emojis: pack_emojis.append(document_sticker.emoticon) OUTPUT = ( f"**Sticker Title:** `{get_stickerset.set.title}\n`" f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" f"**Official:** `{get_stickerset.set.official}`\n" f"**Archived:** `{get_stickerset.set.archived}`\n" f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" f"**Emojis In Pack:**\n{" ".join(pack_emojis)}" ) await event.edit(OUTPUT) @register(outgoing=True, pattern=r"^\.getsticker$") async def sticker_to_png(sticker): if not sticker.is_reply: await sticker.edit("`NULL information to fetch...`") return False img = await sticker.get_reply_message() if not img.document: await sticker.edit("`Reply to a sticker...`") return False try: img.document.attributes[1] except Exception: await sticker.edit("`This is not a sticker...`") return with io.BytesIO() as image: await sticker.client.download_media(img, image) image.name = "sticker.png" image.seek(0) try: await img.reply(file=image, force_document=True) except Exception: await sticker.edit("`Err, can't send file...`") else: await sticker.delete() return CMD_HELP.update( { "stickers": ">`.curry`" "\nUsage: Reply .curry to a sticker or an image to put it to your sticker pack." "\n\n>`.curry (emoji['s]]?` [number]?" "\nUsage: Curry the sticker/image to the specified pack. You can specify the emoji too. " "(Default: 🤔)" "\n\n>`.stkrinfo`" "\nUsage: Gets info about the sticker pack." "\n\n>`.getsticker`" "\nUsage: Reply to a sticker to get 'PNG' file of sticker." } )
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module for kanging stickers or making new ones. Thanks @rupansh""" import io import math import random import urllib.request from os import remove from PIL import Image from telethon.tl.functions.messages import GetStickerSetRequest from telethon.tl.types import ( DocumentAttributeFilename, DocumentAttributeSticker, InputStickerSetID, MessageMediaPhoto, ) from userbot import CMD_HELP, bot from userbot.events import register KANGING_STR = [ "Eh... Koq bagus... aku curry ahhh :3", "Aku curry ya kakak :)", "Curry Sticker dulu yee kan", "ehh, mantep nih.....aku ambil ya kaka", "Bagus eaaaa....\nAmbil ahh....", "Ini Sticker aku ambil yaa\nDUARR!", "leh ugha ni Sticker\nCurry ahh~", "Pim Pim Pom!!!\nni Sticker punya aing sekarang hehe", "Bentar boss, ane curry dulu", "Ihh, bagus nih\nCurry ahh~", "Curry lagi yee kan.....", "CURRY TROSS!!!", "Curry Sticker ahh.....", "Curry dolo boss", "Swiper jangan mencurry", ] @register(outgoing=True, pattern=r"^\.curry") async def kang(args): """For .kang command, kangs stickers or creates new ones.""" user = await bot.get_me() if not user.username: user.username = user.first_name message = await args.get_reply_message() photo = None emojibypass = False is_anim = False emoji = None if not message or not message.media: return await args.edit("`I can't kang that...`") if isinstance(message.media, MessageMediaPhoto): await args.edit(f"`{random.choice(KANGING_STR)}`") photo = io.BytesIO() photo = await bot.download_media(message.photo, photo) elif "image" in message.media.document.mime_type.split("/"): await args.edit(f"`{random.choice(KANGING_STR)}`") photo = io.BytesIO() await bot.download_file(message.media.document, photo) if ( DocumentAttributeFilename(file_name="sticker.webp") in message.media.document.attributes ): emoji = message.media.document.attributes[1].alt if emoji != "": emojibypass = True elif "tgsticker" in message.media.document.mime_type: await args.edit(f"`{random.choice(KANGING_STR)}`") await bot.download_file(message.media.document, "AnimatedSticker.tgs") attributes = message.media.document.attributes for attribute in attributes: if isinstance(attribute, DocumentAttributeSticker): emoji = attribute.alt emojibypass = True is_anim = True photo = 1 else: return await args.edit("`Unsupported File!`") if photo: splat = args.text.split() if not emojibypass: emoji = "🤔" pack = 1 if len(splat) == 3: pack = splat[2] # User sent both emoji = splat[1] elif len(splat) == 2: if splat[1].isnumeric(): # User wants to push into different pack, but is okay with # thonk as emote. pack = int(splat[1]) else: # User sent just custom emote, wants to push to default # pack emoji = splat[1] packname = f"a{user.id}_by_{user.username}_{pack}" packnick = f"@{user.username}'s kang pack Vol.{pack}" cmd = "/newpack" file = io.BytesIO() if not is_anim: image = await resize_photo(photo) file.name = "sticker.png" image.save(file, "PNG") else: packname += "_anim" packnick += " (Animated)" cmd = "/newanimated" response = urllib.request.urlopen( urllib.request.Request(f"http://t.me/addstickers/{packname}") ) htmlstr = response.read().decode("utf8").split("\n") if ( " A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in htmlstr ): async with bot.conversation("Stickers") as conv: await conv.send_message("/addsticker") await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packname) x = await conv.get_response() while "120" in x.text: pack += 1 packname = f"a{user.id}_by_{user.username}_{pack}" packnick = f"@{user.username}'s kang pack Vol.{pack}" await args.edit( "`Switching to Pack " + str(pack) + " due to insufficient space`" ) await conv.send_message(packname) x = await conv.get_response() if x.text == "Invalid pack selected.": await conv.send_message(cmd) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packnick) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) await conv.get_response() await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/publish") if is_anim: await conv.get_response() await conv.send_message(f"<{packnick}>") # Ensure user doesn't get spamming notifications await conv.get_response() await bot.send_read_acknowledge(conv.chat_id) await conv.send_message("/skip") # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message(packname) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) return await args.edit( "`Sticker added in a Different Pack !" "\nThis Pack is Newly created!" f"\nYour pack can be found [here](t.me/addstickers/{packname})", parse_mode="md", ) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) rsp = await conv.get_response() if "Sorry, the file type is invalid." in rsp.text: return await args.edit( "`Failed to add sticker, use` @Stickers `bot to add the sticker manually.`" ) await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/done") await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) else: await args.edit("`Brewing a new Pack...`") async with bot.conversation("Stickers") as conv: await conv.send_message(cmd) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.send_message(packnick) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) if is_anim: await conv.send_file("AnimatedSticker.tgs") remove("AnimatedSticker.tgs") else: file.seek(0) await conv.send_file(file, force_document=True) rsp = await conv.get_response() if "Sorry, the file type is invalid." in rsp.text: return await args.edit( "`Failed to add sticker, use` @Stickers `bot to add the sticker manually.`" ) await conv.send_message(emoji) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message("/publish") if is_anim: await conv.get_response() await conv.send_message(f"<{packnick}>") # Ensure user doesn't get spamming notifications await conv.get_response() await bot.send_read_acknowledge(conv.chat_id) await conv.send_message("/skip") # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() await conv.send_message(packname) # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await conv.get_response() # Ensure user doesn't get spamming notifications await bot.send_read_acknowledge(conv.chat_id) await args.edit( "Curry Success!" f"\n[Klik Disini](t.me/addstickers/{packname})", parse_mode="md", ) async def resize_photo(photo): """Resize the given photo to 512x512""" image = Image.open(photo) if (image.width and image.height) < 512: size1 = image.width size2 = image.height if image.width > image.height: scale = 512 / size1 size1new = 512 size2new = size2 * scale else: scale = 512 / size2 size1new = size1 * scale size2new = 512 size1new = math.floor(size1new) size2new = math.floor(size2new) sizenew = (size1new, size2new) image = image.resize(sizenew) else: maxsize = (512, 512) image.thumbnail(maxsize) return image @register(outgoing=True, pattern=r"^\.stkrinfo$") async def get_pack_info(event): if not event.is_reply: return await event.edit("`I can't fetch info from nothing, can I ?!`") rep_msg = await event.get_reply_message() if not rep_msg.document: return await event.edit("`Reply to a sticker to get the pack details`") try: stickerset_attr = rep_msg.document.attributes[1] await event.edit("`Fetching details of the sticker pack, please wait..`") except BaseException: return await event.edit("`This is not a sticker. Reply to a sticker.`") if not isinstance(stickerset_attr, DocumentAttributeSticker): return await event.edit("`This is not a sticker. Reply to a sticker.`") get_stickerset = await bot( GetStickerSetRequest( InputStickerSetID( id=stickerset_attr.stickerset.id, access_hash=stickerset_attr.stickerset.access_hash, ) ) ) pack_emojis = [] for document_sticker in get_stickerset.packs: if document_sticker.emoticon not in pack_emojis: pack_emojis.append(document_sticker.emoticon) OUTPUT = ( f"**Sticker Title:** `{get_stickerset.set.title}\n`" f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" f"**Official:** `{get_stickerset.set.official}`\n" f"**Archived:** `{get_stickerset.set.archived}`\n" f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" f"**Emojis In Pack:**\n{' '.join(pack_emojis)}" ) await event.edit(OUTPUT) @register(outgoing=True, pattern=r"^\.getsticker$") async def sticker_to_png(sticker): if not sticker.is_reply: await sticker.edit("`NULL information to fetch...`") return False img = await sticker.get_reply_message() if not img.document: await sticker.edit("`Reply to a sticker...`") return False try: img.document.attributes[1] except Exception: await sticker.edit("`This is not a sticker...`") return with io.BytesIO() as image: await sticker.client.download_media(img, image) image.name = "sticker.png" image.seek(0) try: await img.reply(file=image, force_document=True) except Exception: await sticker.edit("`Err, can't send file...`") else: await sticker.delete() return CMD_HELP.update( { "stickers": ">`.curry`" "\nUsage: Reply .curry to a sticker or an image to put it to your sticker pack." "\n\n>`.curry (emoji['s]]?` [number]?" "\nUsage: Curry the sticker/image to the specified pack. You can specify the emoji too. " "(Default: 🤔)" "\n\n>`.stkrinfo`" "\nUsage: Gets info about the sticker pack." "\n\n>`.getsticker`" "\nUsage: Reply to a sticker to get 'PNG' file of sticker." } )
from __future__ import unicode_literals import datetime import logging from inspect import isclass from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist from django.db.models import Q, ForeignKey from .fields import SlickReportField from .helpers import get_field_from_query_text from .registry import field_registry logger = logging.getLogger(__name__) class ReportGenerator(object): """ The main class responsible generating the report and managing the flow """ field_registry_class = field_registry """You can have a custom computation field locator! It only needs a `get_field_by_name(string)` and returns a ReportField`""" report_model = None """The main model where data is """ """ Class to generate a Json Object containing report data. """ date_field = None """Main date field to use whenever date filter is needed""" print_flag = None list_display_links = [] group_by = None """The field to use for grouping, if not set then the report is expected to be a sub version of the report model""" columns = None """A list of column names. Columns names can be 1. A Computation Field 2. If group_by is set, then any field on teh group_by model 3. If group_by is not set, then any field name on the report_model / queryset 4. A callable on the generator 5. Special __time_series__, and __crosstab__ Those can be use to control the position of the time series inside the columns, defaults it's appended at the end Example: columns = ['product_id', '__time_series__', 'col_b'] Same is true with __crosstab__ """ time_series_pattern = '' """ If set the Report will compute a time series. Possible options are: daily, weekly, semimonthly, monthly, quarterly, semiannually, annually and custom. if `custom` is set, you'd need to override `get_custom_time_series_dates` """ time_series_columns = None """ a list of Calculation Field names which will be included in the series calculation. Example: ['__total__', '__total_quantity__'] with compute those 2 fields for all the series """ time_series_custom_dates = None """ Used with `time_series_pattern` set to 'custom' It's a list of tuple, each tuple represent start date & end date Example: [ (start_date_1, end_date_1), (start_date_2, end_date_2), ....] """ crosstab_model = None """ If set, a cross tab over this model selected ids (via `crosstab_ids`) """ crosstab_columns = None """The computation fields which will be computed for each crosstab-ed ids """ crosstab_ids = None """A list is the ids to create a crosstab report on""" crosstab_compute_reminder = True """Include an an extra crosstab_columns for the outer group ( ie: all expects those `crosstab_ids`) """ show_empty_records = True """ If group_by is set, this option control if the report result will include all objects regardless of appearing in the report_model/qs. If set False, only those objects which are found in the report_model/qs Example: Say you group by client show_empty_records = True will get the computation fields for all clients in the Client model (including those who didnt make a transaction. show_empty_records = False will get the computation fields for all clients in the Client model (including those who didnt make a transaction. """ limit_records = None """Serves are a main limit to the returned data of teh report_model. Can be beneficial if the results may be huge. """ swap_sign = False def __init__(self, report_model=None, main_queryset=None, start_date=None, end_date=None, date_field=None, q_filters=None, kwargs_filters=None, group_by=None, columns=None, time_series_pattern=None, time_series_columns=None, time_series_custom_dates=None, crosstab_model=None, crosstab_columns=None, crosstab_ids=None, crosstab_compute_reminder=None, swap_sign=False, show_empty_records=None, print_flag=False, doc_type_plus_list=None, doc_type_minus_list=None, limit_records=False, format_row_func=None): """ :param report_model: Main model containing the data :param main_queryset: Default to report_model.objects :param start_date: :param end_date: :param date_field: :param q_filters: :param kwargs_filters: :param group_by: :param columns: :param time_series_pattern: :param time_series_columns: :param crosstab_model: :param crosstab_columns: :param crosstab_ids: :param crosstab_compute_reminder: :param swap_sign: :param show_empty_records: :param base_model: :param print_flag: :param doc_type_plus_list: :param doc_type_minus_list: :param limit_records: """ from .app_settings import SLICK_REPORTING_DEFAULT_START_DATE, SLICK_REPORTING_DEFAULT_END_DATE super(ReportGenerator, self).__init__() self.report_model = self.report_model or report_model if not self.report_model: raise ImproperlyConfigured('report_model must be set on a class level or via init') self.start_date = start_date or datetime.datetime.combine(SLICK_REPORTING_DEFAULT_START_DATE.date(), SLICK_REPORTING_DEFAULT_START_DATE.time()) self.end_date = end_date or datetime.datetime.combine(SLICK_REPORTING_DEFAULT_END_DATE.date(), SLICK_REPORTING_DEFAULT_END_DATE.time()) self.date_field = self.date_field or date_field if not self.date_field: raise ImproperlyConfigured('date_field must be set on a class level or via init') self.q_filters = q_filters or [] self.kwargs_filters = kwargs_filters or {} self.crosstab_model = self.crosstab_model or crosstab_model self.crosstab_columns = crosstab_columns or self.crosstab_columns or [] self.crosstab_ids = self.crosstab_ids or crosstab_ids or [] self.crosstab_compute_reminder = self.crosstab_compute_reminder if crosstab_compute_reminder is None else crosstab_compute_reminder self.format_row = format_row_func or self._default_format_row main_queryset = main_queryset or self.report_model.objects main_queryset = main_queryset.order_by() self.columns = self.columns or columns or [] self.group_by = self.group_by or group_by self.time_series_pattern = self.time_series_pattern or time_series_pattern self.time_series_columns = self.time_series_columns or time_series_columns self.time_series_custom_dates = self.time_series_custom_dates or time_series_custom_dates self._prepared_results = {} self.report_fields_classes = {} self._report_fields_dependencies = {'time_series': {}, 'crosstab': {}, 'normal': {}} self.existing_dependencies = {'series': [], 'matrix': [], 'normal': []} self.print_flag = print_flag or self.print_flag # todo validate columns is not empty (if no time series / cross tab) if self.group_by: group_by_split = self.group_by.split('__') search_field = group_by_split[0] try: self.group_by_field = [x for x in self.report_model._meta.get_fields() if x.name == search_field][0] except IndexError: raise ImproperlyConfigured( f'Can not find group_by field:{self.group_by} in report_model {self.report_model} ') self.focus_field_as_key = self.group_by_field if '__' not in self.group_by: self.group_by_field_attname = self.group_by_field.attname else: self.group_by_field_attname = self.group_by else: self.focus_field_as_key = None self.group_by_field_attname = None # doc_types = form.get_doc_type_plus_minus_lists() doc_types = [], [] self.doc_type_plus_list = list(doc_type_plus_list) if doc_type_plus_list else doc_types[0] self.doc_type_minus_list = list(doc_type_minus_list) if doc_type_minus_list else doc_types[1] self.swap_sign = self.swap_sign or swap_sign self.limit_records = self.limit_records or limit_records # passed to the report fields # self.date_field = date_field or self.date_field # in case of a group by, do we show a grouped by model data regardless of their appearance in the results # a client who didnt make a transaction during the date period. self.show_empty_records = False # show_empty_records if show_empty_records else self.show_empty_records # Looks like this options is harder then what i thought as it interfere with the usual filtering of the report # Preparing actions self._parse() if self.group_by: if self.show_empty_records: pass # group_by_filter = self.kwargs_filters.get(self.group_by, '') # qs = self.group_by_field.related_model.objects # if group_by_filter: # lookup = 'pk__in' if isinstance(group_by_filter, Iterable) else 'pk' # qs = qs.filter(**{lookup: group_by_filter}) # self.main_queryset = qs.values() else: self.main_queryset = self._apply_queryset_options(main_queryset) if type(self.group_by_field) is ForeignKey and '__' not in self.group_by: ids = self.main_queryset.values_list(self.group_by_field_attname).distinct() self.main_queryset = self.group_by_field.related_model.objects.filter(pk__in=ids).values() else: self.main_queryset = self.main_queryset.distinct().values(self.group_by_field_attname) else: if self.time_series_pattern: self.main_queryset = [{}] else: self.main_queryset = self._apply_queryset_options(main_queryset, self.get_database_columns()) self._prepare_report_dependencies() def _apply_queryset_options(self, query, fields=None): """ Apply the filters to the main queryset which will computed results be mapped to :param query: :param fields: :return: """ filters = { f'{self.date_field}__gt': self.start_date, f'{self.date_field}__lte': self.end_date, } filters.update(self.kwargs_filters) if filters: query = query.filter(**filters) if fields: return query.values(*fields) return query.values() def _construct_crosstab_filter(self, col_data): """ In charge of adding the needed crosstab filter, specific to the case of is_reminder or not :param col_data: :return: """ if col_data['is_reminder']: filters = [~Q(**{f"{col_data["model"]}_id__in": self.crosstab_ids})] else: filters = [Q(**{f"{col_data["model"]}_id": col_data['id']})] return filters def _prepare_report_dependencies(self): from .fields import SlickReportField all_columns = ( ('normal', self._parsed_columns), ('time_series', self._time_series_parsed_columns), ('crosstab', self._crosstab_parsed_columns), ) for window, window_cols in all_columns: for col_data in window_cols: klass = col_data['ref'] if isclass(klass) and issubclass(klass, SlickReportField): dependencies_names = klass.get_full_dependency_list() # check if any of this dependencies is on the report fields_on_report = [x for x in window_cols if x['ref'] in dependencies_names] for field in fields_on_report: self._report_fields_dependencies[window][field['name']] = col_data['name'] for col_data in window_cols: klass = col_data['ref'] name = col_data['name'] # if column has a dependency then skip it if not (isclass(klass) and issubclass(klass, SlickReportField)): continue if self._report_fields_dependencies[window].get(name, False): continue report_class = klass(self.doc_type_plus_list, self.doc_type_minus_list, group_by=self.group_by, report_model=self.report_model, date_field=self.date_field) q_filters = None date_filter = { f'{self.date_field}__gt': col_data.get('start_date', self.start_date), f'{self.date_field}__lte': col_data.get('end_date', self.end_date), } date_filter.update(self.kwargs_filters) if window == 'crosstab': q_filters = self._construct_crosstab_filter(col_data) report_class.init_preparation(q_filters, date_filter) self.report_fields_classes[name] = report_class def _get_record_data(self, obj, columns): """ the function is run for every obj in the main_queryset :param obj: current row :param: columns: The columns we iterate on :return: a dict object containing all needed data """ # todo , if columns are empty for whatever reason this will throw an error display_link = self.list_display_links or columns[0] data = {} group_by_val = None if self.group_by: column_data = obj.get(self.group_by_field_attname, obj.get('id')) group_by_val = str(column_data) for window, window_cols in columns: for col_data in window_cols: name = col_data['name'] if (col_data.get('source', '') == 'magic_field' and self.group_by) or ( self.time_series_pattern and not self.group_by): source = self._report_fields_dependencies[window].get(name, False) if source: computation_class = self.report_fields_classes[source] value = computation_class.get_dependency_value(group_by_val, col_data['ref'].name) else: try: computation_class = self.report_fields_classes[name] except KeyError: continue value = computation_class.resolve(group_by_val, data) if self.swap_sign: value = -value data[name] = value else: data[name] = obj.get(name, '') # if self.group_by and name in display_link: # data[name] = make_linkable_field(self.group_by_field.related_model, group_by_val, data[name]) return data def get_report_data(self): main_queryset = self.main_queryset[:self.limit_records] if self.limit_records else self.main_queryset all_columns = ( ('normal', self._parsed_columns), ('time_series', self._time_series_parsed_columns), ('crosstab', self._crosstab_parsed_columns), ) get_record_data = self._get_record_data format_row = self.format_row data = [format_row(get_record_data(obj, all_columns)) for obj in main_queryset] return data def _default_format_row(self, row_obj): """ Hook where you can format row values like properly format a date :param row_obj: :return: """ return row_obj @classmethod def check_columns(cls, columns, group_by, report_model, ): """ Check and parse the columns, throw errors in case an item in the columns cant not identified :param columns: List of columns :param group_by: group by field if any :param report_model: the report model :return: List of dict, each dict contains relevant data to the respective field in `columns` """ group_by_model = None if group_by: group_by_field = [x for x in report_model._meta.get_fields() if x.name == group_by.split('__')[0]][0] if group_by_field.is_relation: group_by_model = group_by_field.related_model else: group_by_model = report_model parsed_columns = [] for col in columns: if col in ['__time_series__', '__crosstab__']: # These are placeholder not real computation field continue magic_field_class = None attr = None if type(col) is str: attr = getattr(cls, col, None) elif issubclass(col, SlickReportField): magic_field_class = col try: magic_field_class = magic_field_class or field_registry.get_field_by_name(col) except KeyError: magic_field_class = None if attr: # todo Add testing here col_data = {'name': col, 'verbose_name': getattr(attr, 'verbose_name', col), # 'type': 'method', 'ref': attr, 'type': 'text' } elif magic_field_class: # a magic field if col in ['__time_series__', '__crosstab__']: # These are placeholder not real computation field continue col_data = {'name': magic_field_class.name, 'verbose_name': magic_field_class.verbose_name, 'source': 'magic_field', 'ref': magic_field_class, 'type': magic_field_class.type, 'is_summable': magic_field_class.is_summable } else: # A database field model_to_use = group_by_model if group_by and '__' not in group_by else report_model try: if '__' in col: # A traversing link order__client__email field = get_field_from_query_text(col, model_to_use) else: field = model_to_use._meta.get_field(col) except FieldDoesNotExist: raise FieldDoesNotExist( f'Field "{col}" not found either as an attribute to the generator class {cls}, ' f'or a computation field, or a database column for the model "{model_to_use}"') col_data = {'name': col, 'verbose_name': getattr(field, 'verbose_name', col), 'source': 'database', 'ref': field, 'type': field.get_internal_type() } parsed_columns.append(col_data) return parsed_columns def _parse(self): self.parsed_columns = self.check_columns(self.columns, self.group_by, self.report_model) self._parsed_columns = list(self.parsed_columns) self._time_series_parsed_columns = self.get_time_series_parsed_columns() self._crosstab_parsed_columns = self.get_crosstab_parsed_columns() def get_database_columns(self): return [col['name'] for col in self.parsed_columns if col['source'] == 'database'] def get_method_columns(self): return [col['name'] for col in self.parsed_columns if col['type'] == 'method'] def get_list_display_columns(self): columns = self.parsed_columns if self.time_series_pattern: time_series_columns = self.get_time_series_parsed_columns() try: index = self.columns.index('__time_series__') columns[index:index] = time_series_columns except ValueError: columns += time_series_columns if self.crosstab_model: crosstab_columns = self.get_crosstab_parsed_columns() try: index = self.columns.index('__crosstab__') columns[index:index] = crosstab_columns except ValueError: columns += crosstab_columns return columns def get_time_series_parsed_columns(self): """ Return time series columns with all needed data attached :param plain: if True it returns '__total__' instead of '__total_TS011212' :return: List if columns """ _values = [] cols = self.time_series_columns or [] series = self._get_time_series_dates(self.time_series_pattern) for index, dt in enumerate(series): for col in cols: magic_field_class = None if type(col) is str: magic_field_class = field_registry.get_field_by_name(col) elif issubclass(col, SlickReportField): magic_field_class = col _values.append({ 'name': magic_field_class.name + 'TS' + dt[1].strftime('%Y%m%d'), 'original_name': magic_field_class.name, 'verbose_name': self.get_time_series_field_verbose_name(magic_field_class, dt, index, series), 'ref': magic_field_class, 'start_date': dt[0], 'end_date': dt[1], 'source': 'magic_field' if magic_field_class else '', 'is_summable': magic_field_class.is_summable, }) return _values def get_time_series_field_verbose_name(self, computation_class, date_period, index, series, pattern=None): """ Sent the column data to construct a verbose name. Default implementation is delegated to the ReportField.get_time_series_field_verbose_name (which is name + the end date %Y%m%d) :param computation_class: the computation field_name :param date_period: a tuple of (start_date, end_date) :return: a verbose string """ pattern = pattern or self.time_series_pattern return computation_class.get_time_series_field_verbose_name(date_period, index, series, pattern) def get_custom_time_series_dates(self): """ Hook to get custom , maybe separated date periods :return: [ (date1,date2) , (date3,date4), .... ] """ return self.time_series_custom_dates or [] def _get_time_series_dates(self, series=None, start_date=None, end_date=None): from dateutil.relativedelta import relativedelta series = series or self.time_series_pattern start_date = start_date or self.start_date end_date = end_date or self.end_date _values = [] if series: if series == 'daily': time_delta = datetime.timedelta(days=1) elif series == 'weekly': time_delta = relativedelta(weeks=1) elif series == 'semimonthly': time_delta = relativedelta(weeks=2) elif series == 'monthly': time_delta = relativedelta(months=1) elif series == 'quarterly': time_delta = relativedelta(months=3) elif series == 'semiannually': time_delta = relativedelta(months=6) elif series == 'annually': time_delta = relativedelta(years=1) elif series == 'custom': return self.get_custom_time_series_dates() else: raise NotImplementedError(f'"{series}" is not implemented for time_series_pattern') done = False while not done: to_date = start_date + time_delta _values.append((start_date, to_date)) start_date = to_date if to_date >= end_date: done = True return _values def get_crosstab_parsed_columns(self): """ Return a list of the columns analyzed , with reference to computation field and everything :return: """ report_columns = self.crosstab_columns or [] ids = list(self.crosstab_ids) if self.crosstab_compute_reminder: ids.append('----') output_cols = [] ids_length = len(ids) - 1 for counter, id in enumerate(ids): for col in report_columns: magic_field_class = None if type(col) is str: magic_field_class = field_registry.get_field_by_name(col) elif issubclass(col, SlickReportField): magic_field_class = col output_cols.append({ 'name': f'{magic_field_class.name}CT{id}', 'original_name': magic_field_class.name, 'verbose_name': self.get_crosstab_field_verbose_name(magic_field_class, self.crosstab_model, id), 'ref': magic_field_class, 'id': id, 'model': self.crosstab_model, 'is_reminder': counter == ids_length, 'source': 'magic_field' if magic_field_class else '', 'is_summable': magic_field_class.is_summable, }) return output_cols def get_crosstab_field_verbose_name(self, computation_class, model, id): """ Hook to change the crosstab field verbose name, default it delegate this function to the ReportField :param computation_class: ReportField Class :param model: the model name as string :param id: the current crosstab id :return: a verbose string """ return computation_class.get_crosstab_field_verbose_name(model, id)
from __future__ import unicode_literals import datetime import logging from inspect import isclass from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist from django.db.models import Q, ForeignKey from .fields import SlickReportField from .helpers import get_field_from_query_text from .registry import field_registry logger = logging.getLogger(__name__) class ReportGenerator(object): """ The main class responsible generating the report and managing the flow """ field_registry_class = field_registry """You can have a custom computation field locator! It only needs a `get_field_by_name(string)` and returns a ReportField`""" report_model = None """The main model where data is """ """ Class to generate a Json Object containing report data. """ date_field = None """Main date field to use whenever date filter is needed""" print_flag = None list_display_links = [] group_by = None """The field to use for grouping, if not set then the report is expected to be a sub version of the report model""" columns = None """A list of column names. Columns names can be 1. A Computation Field 2. If group_by is set, then any field on teh group_by model 3. If group_by is not set, then any field name on the report_model / queryset 4. A callable on the generator 5. Special __time_series__, and __crosstab__ Those can be use to control the position of the time series inside the columns, defaults it's appended at the end Example: columns = ['product_id', '__time_series__', 'col_b'] Same is true with __crosstab__ """ time_series_pattern = '' """ If set the Report will compute a time series. Possible options are: daily, weekly, semimonthly, monthly, quarterly, semiannually, annually and custom. if `custom` is set, you'd need to override `get_custom_time_series_dates` """ time_series_columns = None """ a list of Calculation Field names which will be included in the series calculation. Example: ['__total__', '__total_quantity__'] with compute those 2 fields for all the series """ time_series_custom_dates = None """ Used with `time_series_pattern` set to 'custom' It's a list of tuple, each tuple represent start date & end date Example: [ (start_date_1, end_date_1), (start_date_2, end_date_2), ....] """ crosstab_model = None """ If set, a cross tab over this model selected ids (via `crosstab_ids`) """ crosstab_columns = None """The computation fields which will be computed for each crosstab-ed ids """ crosstab_ids = None """A list is the ids to create a crosstab report on""" crosstab_compute_reminder = True """Include an an extra crosstab_columns for the outer group ( ie: all expects those `crosstab_ids`) """ show_empty_records = True """ If group_by is set, this option control if the report result will include all objects regardless of appearing in the report_model/qs. If set False, only those objects which are found in the report_model/qs Example: Say you group by client show_empty_records = True will get the computation fields for all clients in the Client model (including those who didnt make a transaction. show_empty_records = False will get the computation fields for all clients in the Client model (including those who didnt make a transaction. """ limit_records = None """Serves are a main limit to the returned data of teh report_model. Can be beneficial if the results may be huge. """ swap_sign = False def __init__(self, report_model=None, main_queryset=None, start_date=None, end_date=None, date_field=None, q_filters=None, kwargs_filters=None, group_by=None, columns=None, time_series_pattern=None, time_series_columns=None, time_series_custom_dates=None, crosstab_model=None, crosstab_columns=None, crosstab_ids=None, crosstab_compute_reminder=None, swap_sign=False, show_empty_records=None, print_flag=False, doc_type_plus_list=None, doc_type_minus_list=None, limit_records=False, format_row_func=None): """ :param report_model: Main model containing the data :param main_queryset: Default to report_model.objects :param start_date: :param end_date: :param date_field: :param q_filters: :param kwargs_filters: :param group_by: :param columns: :param time_series_pattern: :param time_series_columns: :param crosstab_model: :param crosstab_columns: :param crosstab_ids: :param crosstab_compute_reminder: :param swap_sign: :param show_empty_records: :param base_model: :param print_flag: :param doc_type_plus_list: :param doc_type_minus_list: :param limit_records: """ from .app_settings import SLICK_REPORTING_DEFAULT_START_DATE, SLICK_REPORTING_DEFAULT_END_DATE super(ReportGenerator, self).__init__() self.report_model = self.report_model or report_model if not self.report_model: raise ImproperlyConfigured('report_model must be set on a class level or via init') self.start_date = start_date or datetime.datetime.combine(SLICK_REPORTING_DEFAULT_START_DATE.date(), SLICK_REPORTING_DEFAULT_START_DATE.time()) self.end_date = end_date or datetime.datetime.combine(SLICK_REPORTING_DEFAULT_END_DATE.date(), SLICK_REPORTING_DEFAULT_END_DATE.time()) self.date_field = self.date_field or date_field if not self.date_field: raise ImproperlyConfigured('date_field must be set on a class level or via init') self.q_filters = q_filters or [] self.kwargs_filters = kwargs_filters or {} self.crosstab_model = self.crosstab_model or crosstab_model self.crosstab_columns = crosstab_columns or self.crosstab_columns or [] self.crosstab_ids = self.crosstab_ids or crosstab_ids or [] self.crosstab_compute_reminder = self.crosstab_compute_reminder if crosstab_compute_reminder is None else crosstab_compute_reminder self.format_row = format_row_func or self._default_format_row main_queryset = main_queryset or self.report_model.objects main_queryset = main_queryset.order_by() self.columns = self.columns or columns or [] self.group_by = self.group_by or group_by self.time_series_pattern = self.time_series_pattern or time_series_pattern self.time_series_columns = self.time_series_columns or time_series_columns self.time_series_custom_dates = self.time_series_custom_dates or time_series_custom_dates self._prepared_results = {} self.report_fields_classes = {} self._report_fields_dependencies = {'time_series': {}, 'crosstab': {}, 'normal': {}} self.existing_dependencies = {'series': [], 'matrix': [], 'normal': []} self.print_flag = print_flag or self.print_flag # todo validate columns is not empty (if no time series / cross tab) if self.group_by: group_by_split = self.group_by.split('__') search_field = group_by_split[0] try: self.group_by_field = [x for x in self.report_model._meta.get_fields() if x.name == search_field][0] except IndexError: raise ImproperlyConfigured( f'Can not find group_by field:{self.group_by} in report_model {self.report_model} ') self.focus_field_as_key = self.group_by_field if '__' not in self.group_by: self.group_by_field_attname = self.group_by_field.attname else: self.group_by_field_attname = self.group_by else: self.focus_field_as_key = None self.group_by_field_attname = None # doc_types = form.get_doc_type_plus_minus_lists() doc_types = [], [] self.doc_type_plus_list = list(doc_type_plus_list) if doc_type_plus_list else doc_types[0] self.doc_type_minus_list = list(doc_type_minus_list) if doc_type_minus_list else doc_types[1] self.swap_sign = self.swap_sign or swap_sign self.limit_records = self.limit_records or limit_records # passed to the report fields # self.date_field = date_field or self.date_field # in case of a group by, do we show a grouped by model data regardless of their appearance in the results # a client who didnt make a transaction during the date period. self.show_empty_records = False # show_empty_records if show_empty_records else self.show_empty_records # Looks like this options is harder then what i thought as it interfere with the usual filtering of the report # Preparing actions self._parse() if self.group_by: if self.show_empty_records: pass # group_by_filter = self.kwargs_filters.get(self.group_by, '') # qs = self.group_by_field.related_model.objects # if group_by_filter: # lookup = 'pk__in' if isinstance(group_by_filter, Iterable) else 'pk' # qs = qs.filter(**{lookup: group_by_filter}) # self.main_queryset = qs.values() else: self.main_queryset = self._apply_queryset_options(main_queryset) if type(self.group_by_field) is ForeignKey and '__' not in self.group_by: ids = self.main_queryset.values_list(self.group_by_field_attname).distinct() self.main_queryset = self.group_by_field.related_model.objects.filter(pk__in=ids).values() else: self.main_queryset = self.main_queryset.distinct().values(self.group_by_field_attname) else: if self.time_series_pattern: self.main_queryset = [{}] else: self.main_queryset = self._apply_queryset_options(main_queryset, self.get_database_columns()) self._prepare_report_dependencies() def _apply_queryset_options(self, query, fields=None): """ Apply the filters to the main queryset which will computed results be mapped to :param query: :param fields: :return: """ filters = { f'{self.date_field}__gt': self.start_date, f'{self.date_field}__lte': self.end_date, } filters.update(self.kwargs_filters) if filters: query = query.filter(**filters) if fields: return query.values(*fields) return query.values() def _construct_crosstab_filter(self, col_data): """ In charge of adding the needed crosstab filter, specific to the case of is_reminder or not :param col_data: :return: """ if col_data['is_reminder']: filters = [~Q(**{f"{col_data['model']}_id__in": self.crosstab_ids})] else: filters = [Q(**{f"{col_data['model']}_id": col_data['id']})] return filters def _prepare_report_dependencies(self): from .fields import SlickReportField all_columns = ( ('normal', self._parsed_columns), ('time_series', self._time_series_parsed_columns), ('crosstab', self._crosstab_parsed_columns), ) for window, window_cols in all_columns: for col_data in window_cols: klass = col_data['ref'] if isclass(klass) and issubclass(klass, SlickReportField): dependencies_names = klass.get_full_dependency_list() # check if any of this dependencies is on the report fields_on_report = [x for x in window_cols if x['ref'] in dependencies_names] for field in fields_on_report: self._report_fields_dependencies[window][field['name']] = col_data['name'] for col_data in window_cols: klass = col_data['ref'] name = col_data['name'] # if column has a dependency then skip it if not (isclass(klass) and issubclass(klass, SlickReportField)): continue if self._report_fields_dependencies[window].get(name, False): continue report_class = klass(self.doc_type_plus_list, self.doc_type_minus_list, group_by=self.group_by, report_model=self.report_model, date_field=self.date_field) q_filters = None date_filter = { f'{self.date_field}__gt': col_data.get('start_date', self.start_date), f'{self.date_field}__lte': col_data.get('end_date', self.end_date), } date_filter.update(self.kwargs_filters) if window == 'crosstab': q_filters = self._construct_crosstab_filter(col_data) report_class.init_preparation(q_filters, date_filter) self.report_fields_classes[name] = report_class def _get_record_data(self, obj, columns): """ the function is run for every obj in the main_queryset :param obj: current row :param: columns: The columns we iterate on :return: a dict object containing all needed data """ # todo , if columns are empty for whatever reason this will throw an error display_link = self.list_display_links or columns[0] data = {} group_by_val = None if self.group_by: column_data = obj.get(self.group_by_field_attname, obj.get('id')) group_by_val = str(column_data) for window, window_cols in columns: for col_data in window_cols: name = col_data['name'] if (col_data.get('source', '') == 'magic_field' and self.group_by) or ( self.time_series_pattern and not self.group_by): source = self._report_fields_dependencies[window].get(name, False) if source: computation_class = self.report_fields_classes[source] value = computation_class.get_dependency_value(group_by_val, col_data['ref'].name) else: try: computation_class = self.report_fields_classes[name] except KeyError: continue value = computation_class.resolve(group_by_val, data) if self.swap_sign: value = -value data[name] = value else: data[name] = obj.get(name, '') # if self.group_by and name in display_link: # data[name] = make_linkable_field(self.group_by_field.related_model, group_by_val, data[name]) return data def get_report_data(self): main_queryset = self.main_queryset[:self.limit_records] if self.limit_records else self.main_queryset all_columns = ( ('normal', self._parsed_columns), ('time_series', self._time_series_parsed_columns), ('crosstab', self._crosstab_parsed_columns), ) get_record_data = self._get_record_data format_row = self.format_row data = [format_row(get_record_data(obj, all_columns)) for obj in main_queryset] return data def _default_format_row(self, row_obj): """ Hook where you can format row values like properly format a date :param row_obj: :return: """ return row_obj @classmethod def check_columns(cls, columns, group_by, report_model, ): """ Check and parse the columns, throw errors in case an item in the columns cant not identified :param columns: List of columns :param group_by: group by field if any :param report_model: the report model :return: List of dict, each dict contains relevant data to the respective field in `columns` """ group_by_model = None if group_by: group_by_field = [x for x in report_model._meta.get_fields() if x.name == group_by.split('__')[0]][0] if group_by_field.is_relation: group_by_model = group_by_field.related_model else: group_by_model = report_model parsed_columns = [] for col in columns: if col in ['__time_series__', '__crosstab__']: # These are placeholder not real computation field continue magic_field_class = None attr = None if type(col) is str: attr = getattr(cls, col, None) elif issubclass(col, SlickReportField): magic_field_class = col try: magic_field_class = magic_field_class or field_registry.get_field_by_name(col) except KeyError: magic_field_class = None if attr: # todo Add testing here col_data = {'name': col, 'verbose_name': getattr(attr, 'verbose_name', col), # 'type': 'method', 'ref': attr, 'type': 'text' } elif magic_field_class: # a magic field if col in ['__time_series__', '__crosstab__']: # These are placeholder not real computation field continue col_data = {'name': magic_field_class.name, 'verbose_name': magic_field_class.verbose_name, 'source': 'magic_field', 'ref': magic_field_class, 'type': magic_field_class.type, 'is_summable': magic_field_class.is_summable } else: # A database field model_to_use = group_by_model if group_by and '__' not in group_by else report_model try: if '__' in col: # A traversing link order__client__email field = get_field_from_query_text(col, model_to_use) else: field = model_to_use._meta.get_field(col) except FieldDoesNotExist: raise FieldDoesNotExist( f'Field "{col}" not found either as an attribute to the generator class {cls}, ' f'or a computation field, or a database column for the model "{model_to_use}"') col_data = {'name': col, 'verbose_name': getattr(field, 'verbose_name', col), 'source': 'database', 'ref': field, 'type': field.get_internal_type() } parsed_columns.append(col_data) return parsed_columns def _parse(self): self.parsed_columns = self.check_columns(self.columns, self.group_by, self.report_model) self._parsed_columns = list(self.parsed_columns) self._time_series_parsed_columns = self.get_time_series_parsed_columns() self._crosstab_parsed_columns = self.get_crosstab_parsed_columns() def get_database_columns(self): return [col['name'] for col in self.parsed_columns if col['source'] == 'database'] def get_method_columns(self): return [col['name'] for col in self.parsed_columns if col['type'] == 'method'] def get_list_display_columns(self): columns = self.parsed_columns if self.time_series_pattern: time_series_columns = self.get_time_series_parsed_columns() try: index = self.columns.index('__time_series__') columns[index:index] = time_series_columns except ValueError: columns += time_series_columns if self.crosstab_model: crosstab_columns = self.get_crosstab_parsed_columns() try: index = self.columns.index('__crosstab__') columns[index:index] = crosstab_columns except ValueError: columns += crosstab_columns return columns def get_time_series_parsed_columns(self): """ Return time series columns with all needed data attached :param plain: if True it returns '__total__' instead of '__total_TS011212' :return: List if columns """ _values = [] cols = self.time_series_columns or [] series = self._get_time_series_dates(self.time_series_pattern) for index, dt in enumerate(series): for col in cols: magic_field_class = None if type(col) is str: magic_field_class = field_registry.get_field_by_name(col) elif issubclass(col, SlickReportField): magic_field_class = col _values.append({ 'name': magic_field_class.name + 'TS' + dt[1].strftime('%Y%m%d'), 'original_name': magic_field_class.name, 'verbose_name': self.get_time_series_field_verbose_name(magic_field_class, dt, index, series), 'ref': magic_field_class, 'start_date': dt[0], 'end_date': dt[1], 'source': 'magic_field' if magic_field_class else '', 'is_summable': magic_field_class.is_summable, }) return _values def get_time_series_field_verbose_name(self, computation_class, date_period, index, series, pattern=None): """ Sent the column data to construct a verbose name. Default implementation is delegated to the ReportField.get_time_series_field_verbose_name (which is name + the end date %Y%m%d) :param computation_class: the computation field_name :param date_period: a tuple of (start_date, end_date) :return: a verbose string """ pattern = pattern or self.time_series_pattern return computation_class.get_time_series_field_verbose_name(date_period, index, series, pattern) def get_custom_time_series_dates(self): """ Hook to get custom , maybe separated date periods :return: [ (date1,date2) , (date3,date4), .... ] """ return self.time_series_custom_dates or [] def _get_time_series_dates(self, series=None, start_date=None, end_date=None): from dateutil.relativedelta import relativedelta series = series or self.time_series_pattern start_date = start_date or self.start_date end_date = end_date or self.end_date _values = [] if series: if series == 'daily': time_delta = datetime.timedelta(days=1) elif series == 'weekly': time_delta = relativedelta(weeks=1) elif series == 'semimonthly': time_delta = relativedelta(weeks=2) elif series == 'monthly': time_delta = relativedelta(months=1) elif series == 'quarterly': time_delta = relativedelta(months=3) elif series == 'semiannually': time_delta = relativedelta(months=6) elif series == 'annually': time_delta = relativedelta(years=1) elif series == 'custom': return self.get_custom_time_series_dates() else: raise NotImplementedError(f'"{series}" is not implemented for time_series_pattern') done = False while not done: to_date = start_date + time_delta _values.append((start_date, to_date)) start_date = to_date if to_date >= end_date: done = True return _values def get_crosstab_parsed_columns(self): """ Return a list of the columns analyzed , with reference to computation field and everything :return: """ report_columns = self.crosstab_columns or [] ids = list(self.crosstab_ids) if self.crosstab_compute_reminder: ids.append('----') output_cols = [] ids_length = len(ids) - 1 for counter, id in enumerate(ids): for col in report_columns: magic_field_class = None if type(col) is str: magic_field_class = field_registry.get_field_by_name(col) elif issubclass(col, SlickReportField): magic_field_class = col output_cols.append({ 'name': f'{magic_field_class.name}CT{id}', 'original_name': magic_field_class.name, 'verbose_name': self.get_crosstab_field_verbose_name(magic_field_class, self.crosstab_model, id), 'ref': magic_field_class, 'id': id, 'model': self.crosstab_model, 'is_reminder': counter == ids_length, 'source': 'magic_field' if magic_field_class else '', 'is_summable': magic_field_class.is_summable, }) return output_cols def get_crosstab_field_verbose_name(self, computation_class, model, id): """ Hook to change the crosstab field verbose name, default it delegate this function to the ReportField :param computation_class: ReportField Class :param model: the model name as string :param id: the current crosstab id :return: a verbose string """ return computation_class.get_crosstab_field_verbose_name(model, id)
# flake8: noqa E501 import json conditional_token_abi = json.loads( '[{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"name":"payoutNumerators","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"ids","type":"uint256[]"},{"name":"values","type":"uint256[]"},{"name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owners","type":"address[]"},{"name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"operator","type":"address"},{"name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"payoutDenominator","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"id","type":"uint256"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":true,"name":"oracle","type":"address"},{"indexed":true,"name":"questionId","type":"bytes32"},{"indexed":false,"name":"outcomeSlotCount","type":"uint256"}],"name":"ConditionPreparation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":true,"name":"oracle","type":"address"},{"indexed":true,"name":"questionId","type":"bytes32"},{"indexed":false,"name":"outcomeSlotCount","type":"uint256"},{"indexed":false,"name":"payoutNumerators","type":"uint256[]"}],"name":"ConditionResolution","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"stakeholder","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"partition","type":"uint256[]"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"PositionSplit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"stakeholder","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"partition","type":"uint256[]"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"PositionsMerge","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"redeemer","type":"address"},{"indexed":true,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":false,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"indexSets","type":"uint256[]"},{"indexed":false,"name":"payout","type":"uint256"}],"name":"PayoutRedemption","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"operator","type":"address"},{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"id","type":"uint256"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"operator","type":"address"},{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"ids","type":"uint256[]"},{"indexed":false,"name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"operator","type":"address"},{"indexed":false,"name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"string"},{"indexed":true,"name":"id","type":"uint256"}],"name":"URI","type":"event"},{"constant":false,"inputs":[{"name":"oracle","type":"address"},{"name":"questionId","type":"bytes32"},{"name":"outcomeSlotCount","type":"uint256"}],"name":"prepareCondition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"questionId","type":"bytes32"},{"name":"payouts","type":"uint256[]"}],"name":"reportPayouts","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"partition","type":"uint256[]"},{"name":"amount","type":"uint256"}],"name":"splitPosition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"partition","type":"uint256[]"},{"name":"amount","type":"uint256"}],"name":"mergePositions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"indexSets","type":"uint256[]"}],"name":"redeemPositions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"conditionId","type":"bytes32"}],"name":"getOutcomeSlotCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"oracle","type":"address"},{"name":"questionId","type":"bytes32"},{"name":"outcomeSlotCount","type":"uint256"}],"name":"getConditionId","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"indexSet","type":"uint256"}],"name":"getCollectionId","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"collateralToken","type":"address"},{"name":"collectionId","type":"bytes32"}],"name":"getPositionId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}]' ) market_maker_abi = json.loads( '[{"constant":true,"inputs":[{"name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"resume","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"pmSystem","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"outcomeTokenAmounts","type":"int256[]"},{"name":"collateralLimit","type":"int256"}],"name":"trade","outputs":[{"name":"netCost","type":"int256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"close","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"withdrawFees","outputs":[{"name":"fees","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"fundingChange","type":"int256"}],"name":"changeFunding","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"whitelist","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"outcomeTokenCost","type":"uint256"}],"name":"calcMarketFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"collateralToken","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_operator","type":"address"},{"name":"","type":"address"},{"name":"","type":"uint256[]"},{"name":"","type":"uint256[]"},{"name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"name":"","type":"bytes4"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"stage","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"funding","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"conditionIds","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"atomicOutcomeSlotCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_fee","type":"uint64"}],"name":"changeFee","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"operator","type":"address"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"name":"","type":"bytes4"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"FEE_RANGE","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initialFunding","type":"uint256"}],"name":"AMMCreated","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMPaused","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMResumed","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fundingChange","type":"int256"}],"name":"AMMFundingChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newFee","type":"uint64"}],"name":"AMMFeeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fees","type":"uint256"}],"name":"AMMFeeWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"transactor","type":"address"},{"indexed":false,"name":"outcomeTokenAmounts","type":"int256[]"},{"indexed":false,"name":"outcomeTokenNetCost","type":"int256"},{"indexed":false,"name":"marketFees","type":"uint256"}],"name":"AMMOutcomeTokenTrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"constant":true,"inputs":[{"name":"outcomeTokenAmounts","type":"int256[]"}],"name":"calcNetCost","outputs":[{"name":"netCost","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"outcomeTokenIndex","type":"uint8"}],"name":"calcMarginalPrice","outputs":[{"name":"price","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' ) market_maker_factory_abi = json.loads( '[{"constant":true,"inputs":[],"name":"implementationMaster","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"creator","type":"address"},{"indexed":false,"name":"lmsrMarketMaker","type":"address"},{"indexed":false,"name":"pmSystem","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":false,"name":"conditionIds","type":"bytes32[]"},{"indexed":false,"name":"fee","type":"uint64"},{"indexed":false,"name":"funding","type":"uint256"}],"name":"LMSRMarketMakerCreation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initialFunding","type":"uint256"}],"name":"AMMCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"target","type":"address"},{"indexed":false,"name":"clone","type":"address"}],"name":"CloneCreated","type":"event"},{"constant":false,"inputs":[{"name":"consData","type":"bytes"}],"name":"cloneConstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pmSystem","type":"address"},{"name":"collateralToken","type":"address"},{"name":"conditionIds","type":"bytes32[]"},{"name":"fee","type":"uint64"},{"name":"whitelist","type":"address"},{"name":"funding","type":"uint256"}],"name":"createLMSRMarketMaker","outputs":[{"name":"lmsrMarketMaker","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]' )
# flake8: noqa E501 import json conditional_token_abi = json.loads( '[{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"id","type":"uint256"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"},{"name":"","type":"uint256"}],"name":"payoutNumerators","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"ids","type":"uint256[]"},{"name":"values","type":"uint256[]"},{"name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"owners","type":"address[]"},{"name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"name":"","type":"uint256[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"operator","type":"address"},{"name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"payoutDenominator","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"owner","type":"address"},{"name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"id","type":"uint256"},{"name":"value","type":"uint256"},{"name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":true,"name":"oracle","type":"address"},{"indexed":true,"name":"questionId","type":"bytes32"},{"indexed":false,"name":"outcomeSlotCount","type":"uint256"}],"name":"ConditionPreparation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":true,"name":"oracle","type":"address"},{"indexed":true,"name":"questionId","type":"bytes32"},{"indexed":false,"name":"outcomeSlotCount","type":"uint256"},{"indexed":false,"name":"payoutNumerators","type":"uint256[]"}],"name":"ConditionResolution","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"stakeholder","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"partition","type":"uint256[]"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"PositionSplit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"stakeholder","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":true,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"partition","type":"uint256[]"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"PositionsMerge","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"redeemer","type":"address"},{"indexed":true,"name":"collateralToken","type":"address"},{"indexed":true,"name":"parentCollectionId","type":"bytes32"},{"indexed":false,"name":"conditionId","type":"bytes32"},{"indexed":false,"name":"indexSets","type":"uint256[]"},{"indexed":false,"name":"payout","type":"uint256"}],"name":"PayoutRedemption","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"operator","type":"address"},{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"id","type":"uint256"},{"indexed":false,"name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"operator","type":"address"},{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"ids","type":"uint256[]"},{"indexed":false,"name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"operator","type":"address"},{"indexed":false,"name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"value","type":"string"},{"indexed":true,"name":"id","type":"uint256"}],"name":"URI","type":"event"},{"constant":false,"inputs":[{"name":"oracle","type":"address"},{"name":"questionId","type":"bytes32"},{"name":"outcomeSlotCount","type":"uint256"}],"name":"prepareCondition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"questionId","type":"bytes32"},{"name":"payouts","type":"uint256[]"}],"name":"reportPayouts","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"partition","type":"uint256[]"},{"name":"amount","type":"uint256"}],"name":"splitPosition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"partition","type":"uint256[]"},{"name":"amount","type":"uint256"}],"name":"mergePositions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"collateralToken","type":"address"},{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"indexSets","type":"uint256[]"}],"name":"redeemPositions","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"conditionId","type":"bytes32"}],"name":"getOutcomeSlotCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"oracle","type":"address"},{"name":"questionId","type":"bytes32"},{"name":"outcomeSlotCount","type":"uint256"}],"name":"getConditionId","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[{"name":"parentCollectionId","type":"bytes32"},{"name":"conditionId","type":"bytes32"},{"name":"indexSet","type":"uint256"}],"name":"getCollectionId","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"collateralToken","type":"address"},{"name":"collectionId","type":"bytes32"}],"name":"getPositionId","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"}]' ) market_maker_abi = json.loads( '[{"constant":true,"inputs":[{"name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"resume","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"pmSystem","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"outcomeTokenAmounts","type":"int256[]"},{"name":"collateralLimit","type":"int256"}],"name":"trade","outputs":[{"name":"netCost","type":"int256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"close","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"withdrawFees","outputs":[{"name":"fees","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"renounceOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"fundingChange","type":"int256"}],"name":"changeFunding","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"isOwner","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"whitelist","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"outcomeTokenCost","type":"uint256"}],"name":"calcMarketFee","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"collateralToken","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_operator","type":"address"},{"name":"","type":"address"},{"name":"","type":"uint256[]"},{"name":"","type":"uint256[]"},{"name":"","type":"bytes"}],"name":"onERC1155BatchReceived","outputs":[{"name":"","type":"bytes4"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"stage","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"funding","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"conditionIds","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"atomicOutcomeSlotCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"fee","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_fee","type":"uint64"}],"name":"changeFee","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"operator","type":"address"},{"name":"","type":"address"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"bytes"}],"name":"onERC1155Received","outputs":[{"name":"","type":"bytes4"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"FEE_RANGE","outputs":[{"name":"","type":"uint64"}],"payable":false,"stateMutability":"view","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initialFunding","type":"uint256"}],"name":"AMMCreated","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMPaused","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMResumed","type":"event"},{"anonymous":false,"inputs":[],"name":"AMMClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fundingChange","type":"int256"}],"name":"AMMFundingChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"newFee","type":"uint64"}],"name":"AMMFeeChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"fees","type":"uint256"}],"name":"AMMFeeWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"transactor","type":"address"},{"indexed":false,"name":"outcomeTokenAmounts","type":"int256[]"},{"indexed":false,"name":"outcomeTokenNetCost","type":"int256"},{"indexed":false,"name":"marketFees","type":"uint256"}],"name":"AMMOutcomeTokenTrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"constant":true,"inputs":[{"name":"outcomeTokenAmounts","type":"int256[]"}],"name":"calcNetCost","outputs":[{"name":"netCost","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"outcomeTokenIndex","type":"uint8"}],"name":"calcMarginalPrice","outputs":[{"name":"price","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' ) market_maker_factory_abi = json.loads( '[{"constant":true,"inputs":[],"name":"implementationMaster","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"creator","type":"address"},{"indexed":false,"name":"lmsrMarketMaker","type":"address"},{"indexed":false,"name":"pmSystem","type":"address"},{"indexed":false,"name":"collateralToken","type":"address"},{"indexed":false,"name":"conditionIds","type":"bytes32[]"},{"indexed":false,"name":"fee","type":"uint64"},{"indexed":false,"name":"funding","type":"uint256"}],"name":"LMSRMarketMakerCreation","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"previousOwner","type":"address"},{"indexed":true,"name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"name":"initialFunding","type":"uint256"}],"name":"AMMCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"target","type":"address"},{"indexed":false,"name":"clone","type":"address"}],"name":"CloneCreated","type":"event"},{"constant":false,"inputs":[{"name":"consData","type":"bytes"}],"name":"cloneConstructor","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"pmSystem","type":"address"},{"name":"collateralToken","type":"address"},{"name":"conditionIds","type":"bytes32[]"},{"name":"fee","type":"uint64"},{"name":"whitelist","type":"address"},{"name":"funding","type":"uint256"}],"name":"createLMSRMarketMaker","outputs":[{"name":"lmsrMarketMaker","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]' )
""" Prepare all X-ray structures for FAH # Projects 13430 : apo Mpro monomer His41(0) Cys145(0) 13431 : apo Mpro monomer His41(+) Cys145(-) 13432 : holo Mpro monomer His41(0) Cys145(0) 13433 : holo Mpro monomer His41(+) Cys145(-) 13434 : apo Mpro dimer His41(0) Cys145(0) 13435 : apo Mpro dimer His41(+) Cys145(-) 13436 : holo Mpro dimer His41(0) Cys145(0) 13437 : holo Mpro dimer His41(+) Cys145(-) Each RUN corresponds to a different fragment structure # Manifest `../structures/metadata.csv` : master index of fragment IDs and RUNs ``` ,crystal_name,RealCrystalName,smiles,new_smiles,alternate_name,site_name,pdb_entry 1,Mpro-1q2w-2020-04-Bonanno_0,Mpro-1q2w-2020-04-Bonanno,C[C@H](O)CC(C)(C)O,NA,NA,Mpro-SARS1,1Q2W 3,Mpro-1wof-2020-04-Yang_0,Mpro-1wof-2020-04-Yang,CCOC(O)CC[C@H](C[C@@H]1CCNC1O)N[C@H](O)[C@H](CC(C)C)NC(O)[C@@H](NC(O)[C@H](C)NC(O)C1CC(C)ON1)C(C)C,NA,NA,Mpro-SARS1,1WOF 4,Mpro-2a5i-2020-04-Lee_0,Mpro-2a5i-2020-04-Lee,CCOC(O)[C@@H](O)C[C@@H](O)N(CCC(N)O)NC(O)[C@H](CC1CCCCC1)N[C@H](O)[C@H](CC(C)C)N[C@H](O)OCC1CCCCC1,NA,NA,Mpro-SARS1,2A5I ... ``` First column is used to identify RUN: * `RUN0` is skipped * `RUN1` is Mpro-1q2w-2020-04-Bonanno_0 * `RUN2` is skipped * `RUN3` is Mpro-1wof-2020-04-Yang_0 ... """ import os import time import argparse import csv from collections import OrderedDict import tempfile import traceback, sys from simtk import unit, openmm from openff.toolkit.topology import Molecule from simtk.openmm import app from openmmforcefields.generators import SystemGenerator import mdtraj as md import bz2 from openmmtools import integrators import numpy as np from rich.progress import track from openeye import oechem import yaml def setup_fah_run(destination_path, protein_pdb_filename, oemol=None, cache=None, restrain_rmsd=False, biounit='monomer'): """ Prepare simulation Parameters ---------- destination_path : str The path to the RUN to be created protein_pdb_filename : str Path to protein PDB file oemol : openeye.oechem.OEMol, optional, default=None The molecule to parameterize, with SDData attached If None, don't include the small molecule restrain_rmsd : bool, optional, default=False If True, restrain RMSD during first equilibration phase biounit : str, optional, default='monomer' 'monomer' or 'dimer' """ # Parameters protein_forcefield = 'amber14/protein.ff14SB.xml' solvent_forcefield = 'amber14/tip3p.xml' small_molecule_forcefield = 'openff-1.3.0' water_model = 'tip3p' solvent_padding = 10.0 * unit.angstrom ionic_strength = 70 * unit.millimolar # assay buffer: 20 mM HEPES pH 7.3, 1 mM TCEP, 50 mM NaCl, 0.01% Tween-20, 10% glycerol pressure = 1.0 * unit.atmospheres collision_rate = 1.0 / unit.picoseconds temperature = 300.0 * unit.kelvin timestep = 4.0 * unit.femtoseconds iterations = 1000 # 1 ns equilibration nsteps_per_iteration = 250 nsteps_per_snapshot = 250000 # 1 ns nsnapshots_per_wu = 20 # number of snapshots per WU # Prepare phases system_xml_filename = os.path.join(destination_path, 'system.xml.bz2') integrator_xml_filename = os.path.join(destination_path, 'integrator.xml.bz2') state_xml_filename = os.path.join(destination_path, 'state.xml.bz2') # Check if we can skip setup openmm_files_exist = os.path.exists(system_xml_filename) and os.path.exists(state_xml_filename) and os.path.exists( integrator_xml_filename) if openmm_files_exist: return # Create barostat barostat = openmm.MonteCarloBarostat(pressure, temperature) # Create RUN directory if it does not yet exist os.makedirs(destination_path, exist_ok=True) # Load any molecule(s) molecule = None molecules = [] if oemol is not None: molecule = Molecule.from_openeye(oemol, allow_undefined_stereo=True) molecule.name = 'MOL' # Ensure residue is MOL print([res for res in molecule.to_topology().to_openmm().residues()]) molecules = [molecule] # Create SystemGenerator forcefield_kwargs = {'removeCMMotion': False, 'hydrogenMass': 3.0 * unit.amu, 'constraints': app.HBonds, 'rigidWater': True} periodic_kwargs = {'nonbondedMethod': app.PME, 'ewaldErrorTolerance': 2.5e-04} forcefields = [protein_forcefield, solvent_forcefield] openmm_system_generator = SystemGenerator( forcefields=forcefields, molecules=molecules, small_molecule_forcefield=small_molecule_forcefield, cache=cache, barostat=barostat, forcefield_kwargs=forcefield_kwargs, periodic_forcefield_kwargs=periodic_kwargs) # Read protein print(f'Reading protein from {protein_pdb_filename}...') pdbfile = app.PDBFile(protein_pdb_filename) modeller = app.Modeller(pdbfile.topology, pdbfile.positions) if oemol is not None: # Add small molecule to the system modeller.add(molecule.to_topology().to_openmm(), molecule.conformers[0]) # Extract protein and molecule chains and indices before adding solvent mdtop = md.Topology.from_openmm(modeller.topology) # excludes solvent and ions protein_atom_indices = mdtop.select('protein and (mass > 1)') molecule_atom_indices = mdtop.select('(not protein) and (not water) and (mass > 1)') protein_chainids = list( set([atom.residue.chain.index for atom in mdtop.atoms if atom.index in protein_atom_indices])) n_protein_chains = len(protein_chainids) protein_chain_atom_indices = dict() for chainid in protein_chainids: protein_chain_atom_indices[chainid] = mdtop.select(f'protein and chainid {chainid}') # Add solvent print('Adding solvent...') kwargs = {'padding': solvent_padding} modeller.addSolvent(openmm_system_generator.forcefield, model='tip3p', ionicStrength=ionic_strength, **kwargs) # Write initial model and select atom subsets and chains with bz2.open(os.path.join(destination_path, 'initial-model.pdb.bz2'), 'wt') as outfile: app.PDBFile.writeFile(modeller.topology, modeller.positions, outfile, keepIds=True) # Create an OpenMM system print('Creating OpenMM system...') system = openmm_system_generator.create_system(modeller.topology) # # Add virtual bonds to ensure protein subunits and ligand are imaged together # virtual_bond_force = openmm.CustomBondForce('0') system.addForce(virtual_bond_force) # Add a virtual bond between protein chains if (n_protein_chains > 1): chainid = protein_chainids[0] iatom = protein_chain_atom_indices[chainid][0] for chainid in protein_chainids[1:]: jatom = protein_chain_atom_indices[chainid][0] print(f'Creating virtual bond between atoms {iatom} and {jatom}') virtual_bond_force.addBond(int(iatom), int(jatom), []) # Add a virtual bond between protein and ligand to make sure they are not imaged separately if oemol is not None: ligand_atom_indices = mdtop.select('((resname MOL) and (mass > 1))') # ligand heavy atoms protein_atom_index = int(protein_atom_indices[0]) ligand_atom_index = int(ligand_atom_indices[0]) print(f'Creating virtual bond between atoms {protein_atom_index} and {ligand_atom_index}') virtual_bond_force.addBond(int(protein_atom_index), int(ligand_atom_index), []) # Add RMSD restraints if requested if restrain_rmsd: print('Adding RMSD restraint...') kB = unit.AVOGADRO_CONSTANT_NA * unit.BOLTZMANN_CONSTANT_kB kT = kB * temperature rmsd_atom_indices = mdtop.select( '(protein and (name CA)) or ((resname MOL) and (mass > 1))') # CA atoms and ligand heavy atoms rmsd_atom_indices = [int(index) for index in rmsd_atom_indices] custom_cv_force = openmm.CustomCVForce('(K_RMSD/2)*RMSD^2') custom_cv_force.addGlobalParameter('K_RMSD', kT / unit.angstrom ** 2) rmsd_force = openmm.RMSDForce(modeller.positions, rmsd_atom_indices) custom_cv_force.addCollectiveVariable('RMSD', rmsd_force) force_index = system.addForce(custom_cv_force) # Create OpenM Context platform = openmm.Platform.getPlatformByName('CPU') # platform = openmm.Platform.findPlatform() # platform.setPropertyDefaultValue('Precision', 'mixed') integrator = integrators.LangevinIntegrator(temperature, collision_rate, timestep) context = openmm.Context(system, integrator, platform) context.setPositions(modeller.positions) # Report initial potential energy state = context.getState(getEnergy=True) print(f'Initial potential energy is {state.getPotentialEnergy() / unit.kilocalories_per_mole:.3f} kcal/mol') # Store snapshots in MDTraj trajectory to examine RMSD mdtop = md.Topology.from_openmm(pdbfile.topology) atom_indices = mdtop.select('all') # all solute atoms protein_atom_indices = mdtop.select('protein and (mass > 1)') # heavy solute atoms if oemol is not None: ligand_atom_indices = mdtop.select('(resname MOL) and (mass > 1)') # ligand heavy atoms trajectory = md.Trajectory(np.zeros([iterations + 1, len(atom_indices), 3], np.float32), mdtop) trajectory.xyz[0, :, :] = context.getState(getPositions=True).getPositions(asNumpy=True)[ atom_indices] / unit.nanometers # Minimize print('Minimizing...') openmm.LocalEnergyMinimizer.minimize(context) # Equilibrate (with RMSD restraint if needed) initial_time = time.time() for iteration in track(range(iterations), 'Equilibrating...'): integrator.step(nsteps_per_iteration) trajectory.xyz[iteration + 1, :, :] = context.getState(getPositions=True).getPositions(asNumpy=True)[ atom_indices] / unit.nanometers elapsed_time = (time.time() - initial_time) * unit.seconds ns_per_day = (context.getState().getTime() / elapsed_time) / (unit.nanoseconds / unit.day) print(f'Performance: {ns_per_day:8.3f} ns/day') if restrain_rmsd: # Disable RMSD restraint context.setParameter('K_RMSD', 0.0) print('Minimizing...') openmm.LocalEnergyMinimizer.minimize(context) for iteration in track(range(iterations), 'Equilibrating without RMSD restraint...'): integrator.step(nsteps_per_iteration) # Retrieve state state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) modeller.topology.setPeriodicBoxVectors(state.getPeriodicBoxVectors()) print(f'Final potential energy is {state.getPotentialEnergy() / unit.kilocalories_per_mole:.3f} kcal/mol') # Equilibrate again if we restrained the RMSD if restrain_rmsd: print('Removing RMSD restraint from system...') system.removeForce(force_index) # if oemol is not None: # # Check final RMSD # print('checking RMSD...') # trajectory.superpose(trajectory, atom_indices=protein_atom_indices) # protein_rmsd = md.rmsd(trajectory, trajectory[-1], atom_indices=protein_atom_indices)[-1] * 10 # Angstroms # oechem.OESetSDData(oemol, 'equil_protein_rmsd', f'{protein_rmsd:.2f} A') # ligand_rmsd = md.rmsd(trajectory, trajectory[-1], atom_indices=ligand_atom_indices)[-1] * 10 # Angstroms # oechem.OESetSDData(oemol, 'equil_ligand_rmsd', f'{ligand_rmsd:.2f} A') # print('RMSD after equilibration: protein {protein_rmsd:8.2f} A | ligand {ligand_rmsd:8.3f} A') # Save as OpenMM print('Exporting for OpenMM FAH simulation...') with bz2.open(integrator_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(integrator)) with bz2.open(state_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(state)) with bz2.open(system_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(system)) with bz2.open(os.path.join(destination_path, 'equilibrated-all.pdb.bz2'), 'wt') as f: app.PDBFile.writeFile(modeller.topology, state.getPositions(), f, keepIds=True) with open(os.path.join(destination_path, 'equilibrated-solute.pdb'), 'wt') as f: mdtraj_topology = mdtraj.Topology.from_openmm(modeller.topology) mdtraj_trajectory = mdtraj.Trajectory([state.getPositions(asNumpy=True) / unit.nanometers], mdtraj_topology) selection = mdtraj_topology.select('not water') mdtraj_trajectory = mdtraj_trajectory.atom_slice(selection) app.PDBFile.writeFile(mdtraj_trajectory.topology.to_openmm(), mdtraj_trajectory.openmm_positions(0), f, keepIds=True) with open(os.path.join(destination_path, 'core.xml'), 'wt') as f: f.write(f'<config>\n') f.write(f' <numSteps>{nsteps_per_snapshot * nsnapshots_per_wu}</numSteps>\n') f.write(f' <xtcFreq>{nsteps_per_snapshot}</xtcFreq>\n') f.write(f' <precision>mixed</precision>\n') f.write(f' <xtcAtoms>{','.join([str(index) for index in selection])}</xtcAtoms>\n') f.write(f'</config>\n') if oemol is not None: # Write molecule as SDF, SMILES, and mol2 for extension in ['sdf', 'mol2', 'smi', 'csv']: filename = os.path.join(destination_path, f'molecule.{extension}') with oechem.oemolostream(filename) as ofs: oechem.OEWriteMolecule(ofs, oemol) # Clean up del context, integrator if __name__ == '__main__': # Parse arguments parser = argparse.ArgumentParser( description='Prepare the specified RUN for FAH by preparing all X-ray structure variants of a specific fragment') parser.add_argument('--receptors', dest='receptors_path', type=str, default='../receptors', help='directory of receptor conformations (default: ../receptors)') parser.add_argument('--metadata', dest='metadata_filename', type=str, default='../fah-xray/fah-metadata.csv', help='metadata (default: ../fah-xray/fah-metadata.csv)') parser.add_argument('--run', dest='run', type=str, required=True, help='RUN index to prepare (zero-indexes first column contents in Mpro.zip metadata.csv)') parser.add_argument('--output', dest='output_path', type=str, default='projects', help='base directory for produced output (default: projects/)') args = parser.parse_args() # Read DiamondMX/XChem structure medatadata metadata = OrderedDict() with open(args.metadata_filename, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: run = row['RUN'] metadata[run] = row # Extract relevant metadata run = f'RUN{args.run}' if run not in metadata: raise Exception(f'{run} not found in metadata.csv') print(f'Preparing {run}') metadata = metadata[run] # Extract crystal_name crystal_name = metadata['crystal_name'] # Read molecule in the appropriate protonation state try: oemol = oechem.OEMol() molecule_filename = os.path.join(args.receptors_path, 'monomer', f'{crystal_name}_bound-ligand.mol2') if not os.path.exists(molecule_filename): msg = f'{molecule_filename} does not exist' print(msg) with oechem.oemolistream(molecule_filename) as ifs: oechem.OEReadMolecule(ifs, oemol) # Rename the molecule title = metadata['alternate_name'] print(f'Setting title to {title}') oemol.SetTitle(title) # Remove dummy atoms for atom in oemol.GetAtoms(): if atom.GetName().startswith('Du'): print('Removing dummy atom.') oemol.DeleteAtom(atom) # Attach all structure metadata to the molecule for key in metadata: oechem.OESetSDData(oemol, key, metadata[key]) except Exception as e: print(e) oemol = None # Set up all variants # TODO: Generalize this to just use just one protonation state # and maybe constant-pH simulations? with tempfile.TemporaryDirectory() as tmpdir: cache = os.path.join(tmpdir, 'cache.json') def prepare_variant(project, run, crystal_name, biounit, dyad_state, oemol): assert biounit in ['monomer', 'dimer'] try: print('') print(f'PROJ{project}') if dyad_state == 'His41(0) Cys145(0)': protein_pdb_filename = os.path.join(args.receptors_path, biounit, f'{crystal_name}_bound-protein.pdb') elif dyad_state == 'His41(+) Cys145(-)': protein_pdb_filename = os.path.join(args.receptors_path, biounit, f'{crystal_name}_bound-protein-thiolate.pdb') else: raise Exception("dyad_state must be one of ['His41(0) Cys145(0)', 'His41(+) Cys145(-)']") destination_path = os.path.join(args.output_path, project, 'RUNS', f'RUN{run}') # Create RUN directory if it does not yet exist os.makedirs(destination_path, exist_ok=True) # Write metadata with open(os.path.join(destination_path, 'metadata.yaml'), 'wt') as outfile: yaml.dump(dict(metadata), outfile) # Set up RUN setup_fah_run(destination_path, protein_pdb_filename, oemol=oemol, cache=cache, biounit=biounit) print('') except Exception as e: traceback.print_exc(file=sys.stdout) print(e) # prepare_variant('13430', args.run, crystal_name, 'monomer', 'His41(0) Cys145(0)', None) prepare_variant('13431', args.run, crystal_name, 'monomer', 'His41(+) Cys145(-)', None) if oemol is not None: # prepare_variant('13432', args.run, crystal_name, 'monomer', 'His41(0) Cys145(0)', oemol) prepare_variant('13433', args.run, crystal_name, 'monomer', 'His41(+) Cys145(-)', oemol) # prepare_variant('13434', args.run, crystal_name, 'dimer', 'His41(0) Cys145(0)', None) prepare_variant('13435', args.run, crystal_name, 'dimer', 'His41(+) Cys145(-)', None) if oemol is not None: # prepare_variant('13436', args.run, crystal_name, 'dimer', 'His41(0) Cys145(0)', oemol) prepare_variant('13437', args.run, crystal_name, 'dimer', 'His41(+) Cys145(-)', oemol)
""" Prepare all X-ray structures for FAH # Projects 13430 : apo Mpro monomer His41(0) Cys145(0) 13431 : apo Mpro monomer His41(+) Cys145(-) 13432 : holo Mpro monomer His41(0) Cys145(0) 13433 : holo Mpro monomer His41(+) Cys145(-) 13434 : apo Mpro dimer His41(0) Cys145(0) 13435 : apo Mpro dimer His41(+) Cys145(-) 13436 : holo Mpro dimer His41(0) Cys145(0) 13437 : holo Mpro dimer His41(+) Cys145(-) Each RUN corresponds to a different fragment structure # Manifest `../structures/metadata.csv` : master index of fragment IDs and RUNs ``` ,crystal_name,RealCrystalName,smiles,new_smiles,alternate_name,site_name,pdb_entry 1,Mpro-1q2w-2020-04-Bonanno_0,Mpro-1q2w-2020-04-Bonanno,C[C@H](O)CC(C)(C)O,NA,NA,Mpro-SARS1,1Q2W 3,Mpro-1wof-2020-04-Yang_0,Mpro-1wof-2020-04-Yang,CCOC(O)CC[C@H](C[C@@H]1CCNC1O)N[C@H](O)[C@H](CC(C)C)NC(O)[C@@H](NC(O)[C@H](C)NC(O)C1CC(C)ON1)C(C)C,NA,NA,Mpro-SARS1,1WOF 4,Mpro-2a5i-2020-04-Lee_0,Mpro-2a5i-2020-04-Lee,CCOC(O)[C@@H](O)C[C@@H](O)N(CCC(N)O)NC(O)[C@H](CC1CCCCC1)N[C@H](O)[C@H](CC(C)C)N[C@H](O)OCC1CCCCC1,NA,NA,Mpro-SARS1,2A5I ... ``` First column is used to identify RUN: * `RUN0` is skipped * `RUN1` is Mpro-1q2w-2020-04-Bonanno_0 * `RUN2` is skipped * `RUN3` is Mpro-1wof-2020-04-Yang_0 ... """ import os import time import argparse import csv from collections import OrderedDict import tempfile import traceback, sys from simtk import unit, openmm from openff.toolkit.topology import Molecule from simtk.openmm import app from openmmforcefields.generators import SystemGenerator import mdtraj as md import bz2 from openmmtools import integrators import numpy as np from rich.progress import track from openeye import oechem import yaml def setup_fah_run(destination_path, protein_pdb_filename, oemol=None, cache=None, restrain_rmsd=False, biounit='monomer'): """ Prepare simulation Parameters ---------- destination_path : str The path to the RUN to be created protein_pdb_filename : str Path to protein PDB file oemol : openeye.oechem.OEMol, optional, default=None The molecule to parameterize, with SDData attached If None, don't include the small molecule restrain_rmsd : bool, optional, default=False If True, restrain RMSD during first equilibration phase biounit : str, optional, default='monomer' 'monomer' or 'dimer' """ # Parameters protein_forcefield = 'amber14/protein.ff14SB.xml' solvent_forcefield = 'amber14/tip3p.xml' small_molecule_forcefield = 'openff-1.3.0' water_model = 'tip3p' solvent_padding = 10.0 * unit.angstrom ionic_strength = 70 * unit.millimolar # assay buffer: 20 mM HEPES pH 7.3, 1 mM TCEP, 50 mM NaCl, 0.01% Tween-20, 10% glycerol pressure = 1.0 * unit.atmospheres collision_rate = 1.0 / unit.picoseconds temperature = 300.0 * unit.kelvin timestep = 4.0 * unit.femtoseconds iterations = 1000 # 1 ns equilibration nsteps_per_iteration = 250 nsteps_per_snapshot = 250000 # 1 ns nsnapshots_per_wu = 20 # number of snapshots per WU # Prepare phases system_xml_filename = os.path.join(destination_path, 'system.xml.bz2') integrator_xml_filename = os.path.join(destination_path, 'integrator.xml.bz2') state_xml_filename = os.path.join(destination_path, 'state.xml.bz2') # Check if we can skip setup openmm_files_exist = os.path.exists(system_xml_filename) and os.path.exists(state_xml_filename) and os.path.exists( integrator_xml_filename) if openmm_files_exist: return # Create barostat barostat = openmm.MonteCarloBarostat(pressure, temperature) # Create RUN directory if it does not yet exist os.makedirs(destination_path, exist_ok=True) # Load any molecule(s) molecule = None molecules = [] if oemol is not None: molecule = Molecule.from_openeye(oemol, allow_undefined_stereo=True) molecule.name = 'MOL' # Ensure residue is MOL print([res for res in molecule.to_topology().to_openmm().residues()]) molecules = [molecule] # Create SystemGenerator forcefield_kwargs = {'removeCMMotion': False, 'hydrogenMass': 3.0 * unit.amu, 'constraints': app.HBonds, 'rigidWater': True} periodic_kwargs = {'nonbondedMethod': app.PME, 'ewaldErrorTolerance': 2.5e-04} forcefields = [protein_forcefield, solvent_forcefield] openmm_system_generator = SystemGenerator( forcefields=forcefields, molecules=molecules, small_molecule_forcefield=small_molecule_forcefield, cache=cache, barostat=barostat, forcefield_kwargs=forcefield_kwargs, periodic_forcefield_kwargs=periodic_kwargs) # Read protein print(f'Reading protein from {protein_pdb_filename}...') pdbfile = app.PDBFile(protein_pdb_filename) modeller = app.Modeller(pdbfile.topology, pdbfile.positions) if oemol is not None: # Add small molecule to the system modeller.add(molecule.to_topology().to_openmm(), molecule.conformers[0]) # Extract protein and molecule chains and indices before adding solvent mdtop = md.Topology.from_openmm(modeller.topology) # excludes solvent and ions protein_atom_indices = mdtop.select('protein and (mass > 1)') molecule_atom_indices = mdtop.select('(not protein) and (not water) and (mass > 1)') protein_chainids = list( set([atom.residue.chain.index for atom in mdtop.atoms if atom.index in protein_atom_indices])) n_protein_chains = len(protein_chainids) protein_chain_atom_indices = dict() for chainid in protein_chainids: protein_chain_atom_indices[chainid] = mdtop.select(f'protein and chainid {chainid}') # Add solvent print('Adding solvent...') kwargs = {'padding': solvent_padding} modeller.addSolvent(openmm_system_generator.forcefield, model='tip3p', ionicStrength=ionic_strength, **kwargs) # Write initial model and select atom subsets and chains with bz2.open(os.path.join(destination_path, 'initial-model.pdb.bz2'), 'wt') as outfile: app.PDBFile.writeFile(modeller.topology, modeller.positions, outfile, keepIds=True) # Create an OpenMM system print('Creating OpenMM system...') system = openmm_system_generator.create_system(modeller.topology) # # Add virtual bonds to ensure protein subunits and ligand are imaged together # virtual_bond_force = openmm.CustomBondForce('0') system.addForce(virtual_bond_force) # Add a virtual bond between protein chains if (n_protein_chains > 1): chainid = protein_chainids[0] iatom = protein_chain_atom_indices[chainid][0] for chainid in protein_chainids[1:]: jatom = protein_chain_atom_indices[chainid][0] print(f'Creating virtual bond between atoms {iatom} and {jatom}') virtual_bond_force.addBond(int(iatom), int(jatom), []) # Add a virtual bond between protein and ligand to make sure they are not imaged separately if oemol is not None: ligand_atom_indices = mdtop.select('((resname MOL) and (mass > 1))') # ligand heavy atoms protein_atom_index = int(protein_atom_indices[0]) ligand_atom_index = int(ligand_atom_indices[0]) print(f'Creating virtual bond between atoms {protein_atom_index} and {ligand_atom_index}') virtual_bond_force.addBond(int(protein_atom_index), int(ligand_atom_index), []) # Add RMSD restraints if requested if restrain_rmsd: print('Adding RMSD restraint...') kB = unit.AVOGADRO_CONSTANT_NA * unit.BOLTZMANN_CONSTANT_kB kT = kB * temperature rmsd_atom_indices = mdtop.select( '(protein and (name CA)) or ((resname MOL) and (mass > 1))') # CA atoms and ligand heavy atoms rmsd_atom_indices = [int(index) for index in rmsd_atom_indices] custom_cv_force = openmm.CustomCVForce('(K_RMSD/2)*RMSD^2') custom_cv_force.addGlobalParameter('K_RMSD', kT / unit.angstrom ** 2) rmsd_force = openmm.RMSDForce(modeller.positions, rmsd_atom_indices) custom_cv_force.addCollectiveVariable('RMSD', rmsd_force) force_index = system.addForce(custom_cv_force) # Create OpenM Context platform = openmm.Platform.getPlatformByName('CPU') # platform = openmm.Platform.findPlatform() # platform.setPropertyDefaultValue('Precision', 'mixed') integrator = integrators.LangevinIntegrator(temperature, collision_rate, timestep) context = openmm.Context(system, integrator, platform) context.setPositions(modeller.positions) # Report initial potential energy state = context.getState(getEnergy=True) print(f'Initial potential energy is {state.getPotentialEnergy() / unit.kilocalories_per_mole:.3f} kcal/mol') # Store snapshots in MDTraj trajectory to examine RMSD mdtop = md.Topology.from_openmm(pdbfile.topology) atom_indices = mdtop.select('all') # all solute atoms protein_atom_indices = mdtop.select('protein and (mass > 1)') # heavy solute atoms if oemol is not None: ligand_atom_indices = mdtop.select('(resname MOL) and (mass > 1)') # ligand heavy atoms trajectory = md.Trajectory(np.zeros([iterations + 1, len(atom_indices), 3], np.float32), mdtop) trajectory.xyz[0, :, :] = context.getState(getPositions=True).getPositions(asNumpy=True)[ atom_indices] / unit.nanometers # Minimize print('Minimizing...') openmm.LocalEnergyMinimizer.minimize(context) # Equilibrate (with RMSD restraint if needed) initial_time = time.time() for iteration in track(range(iterations), 'Equilibrating...'): integrator.step(nsteps_per_iteration) trajectory.xyz[iteration + 1, :, :] = context.getState(getPositions=True).getPositions(asNumpy=True)[ atom_indices] / unit.nanometers elapsed_time = (time.time() - initial_time) * unit.seconds ns_per_day = (context.getState().getTime() / elapsed_time) / (unit.nanoseconds / unit.day) print(f'Performance: {ns_per_day:8.3f} ns/day') if restrain_rmsd: # Disable RMSD restraint context.setParameter('K_RMSD', 0.0) print('Minimizing...') openmm.LocalEnergyMinimizer.minimize(context) for iteration in track(range(iterations), 'Equilibrating without RMSD restraint...'): integrator.step(nsteps_per_iteration) # Retrieve state state = context.getState(getPositions=True, getVelocities=True, getEnergy=True, getForces=True) system.setDefaultPeriodicBoxVectors(*state.getPeriodicBoxVectors()) modeller.topology.setPeriodicBoxVectors(state.getPeriodicBoxVectors()) print(f'Final potential energy is {state.getPotentialEnergy() / unit.kilocalories_per_mole:.3f} kcal/mol') # Equilibrate again if we restrained the RMSD if restrain_rmsd: print('Removing RMSD restraint from system...') system.removeForce(force_index) # if oemol is not None: # # Check final RMSD # print('checking RMSD...') # trajectory.superpose(trajectory, atom_indices=protein_atom_indices) # protein_rmsd = md.rmsd(trajectory, trajectory[-1], atom_indices=protein_atom_indices)[-1] * 10 # Angstroms # oechem.OESetSDData(oemol, 'equil_protein_rmsd', f'{protein_rmsd:.2f} A') # ligand_rmsd = md.rmsd(trajectory, trajectory[-1], atom_indices=ligand_atom_indices)[-1] * 10 # Angstroms # oechem.OESetSDData(oemol, 'equil_ligand_rmsd', f'{ligand_rmsd:.2f} A') # print('RMSD after equilibration: protein {protein_rmsd:8.2f} A | ligand {ligand_rmsd:8.3f} A') # Save as OpenMM print('Exporting for OpenMM FAH simulation...') with bz2.open(integrator_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(integrator)) with bz2.open(state_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(state)) with bz2.open(system_xml_filename, 'wt') as f: f.write(openmm.XmlSerializer.serialize(system)) with bz2.open(os.path.join(destination_path, 'equilibrated-all.pdb.bz2'), 'wt') as f: app.PDBFile.writeFile(modeller.topology, state.getPositions(), f, keepIds=True) with open(os.path.join(destination_path, 'equilibrated-solute.pdb'), 'wt') as f: mdtraj_topology = mdtraj.Topology.from_openmm(modeller.topology) mdtraj_trajectory = mdtraj.Trajectory([state.getPositions(asNumpy=True) / unit.nanometers], mdtraj_topology) selection = mdtraj_topology.select('not water') mdtraj_trajectory = mdtraj_trajectory.atom_slice(selection) app.PDBFile.writeFile(mdtraj_trajectory.topology.to_openmm(), mdtraj_trajectory.openmm_positions(0), f, keepIds=True) with open(os.path.join(destination_path, 'core.xml'), 'wt') as f: f.write(f'<config>\n') f.write(f' <numSteps>{nsteps_per_snapshot * nsnapshots_per_wu}</numSteps>\n') f.write(f' <xtcFreq>{nsteps_per_snapshot}</xtcFreq>\n') f.write(f' <precision>mixed</precision>\n') f.write(f' <xtcAtoms>{",".join([str(index) for index in selection])}</xtcAtoms>\n') f.write(f'</config>\n') if oemol is not None: # Write molecule as SDF, SMILES, and mol2 for extension in ['sdf', 'mol2', 'smi', 'csv']: filename = os.path.join(destination_path, f'molecule.{extension}') with oechem.oemolostream(filename) as ofs: oechem.OEWriteMolecule(ofs, oemol) # Clean up del context, integrator if __name__ == '__main__': # Parse arguments parser = argparse.ArgumentParser( description='Prepare the specified RUN for FAH by preparing all X-ray structure variants of a specific fragment') parser.add_argument('--receptors', dest='receptors_path', type=str, default='../receptors', help='directory of receptor conformations (default: ../receptors)') parser.add_argument('--metadata', dest='metadata_filename', type=str, default='../fah-xray/fah-metadata.csv', help='metadata (default: ../fah-xray/fah-metadata.csv)') parser.add_argument('--run', dest='run', type=str, required=True, help='RUN index to prepare (zero-indexes first column contents in Mpro.zip metadata.csv)') parser.add_argument('--output', dest='output_path', type=str, default='projects', help='base directory for produced output (default: projects/)') args = parser.parse_args() # Read DiamondMX/XChem structure medatadata metadata = OrderedDict() with open(args.metadata_filename, newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: run = row['RUN'] metadata[run] = row # Extract relevant metadata run = f'RUN{args.run}' if run not in metadata: raise Exception(f'{run} not found in metadata.csv') print(f'Preparing {run}') metadata = metadata[run] # Extract crystal_name crystal_name = metadata['crystal_name'] # Read molecule in the appropriate protonation state try: oemol = oechem.OEMol() molecule_filename = os.path.join(args.receptors_path, 'monomer', f'{crystal_name}_bound-ligand.mol2') if not os.path.exists(molecule_filename): msg = f'{molecule_filename} does not exist' print(msg) with oechem.oemolistream(molecule_filename) as ifs: oechem.OEReadMolecule(ifs, oemol) # Rename the molecule title = metadata['alternate_name'] print(f'Setting title to {title}') oemol.SetTitle(title) # Remove dummy atoms for atom in oemol.GetAtoms(): if atom.GetName().startswith('Du'): print('Removing dummy atom.') oemol.DeleteAtom(atom) # Attach all structure metadata to the molecule for key in metadata: oechem.OESetSDData(oemol, key, metadata[key]) except Exception as e: print(e) oemol = None # Set up all variants # TODO: Generalize this to just use just one protonation state # and maybe constant-pH simulations? with tempfile.TemporaryDirectory() as tmpdir: cache = os.path.join(tmpdir, 'cache.json') def prepare_variant(project, run, crystal_name, biounit, dyad_state, oemol): assert biounit in ['monomer', 'dimer'] try: print('') print(f'PROJ{project}') if dyad_state == 'His41(0) Cys145(0)': protein_pdb_filename = os.path.join(args.receptors_path, biounit, f'{crystal_name}_bound-protein.pdb') elif dyad_state == 'His41(+) Cys145(-)': protein_pdb_filename = os.path.join(args.receptors_path, biounit, f'{crystal_name}_bound-protein-thiolate.pdb') else: raise Exception("dyad_state must be one of ['His41(0) Cys145(0)', 'His41(+) Cys145(-)']") destination_path = os.path.join(args.output_path, project, 'RUNS', f'RUN{run}') # Create RUN directory if it does not yet exist os.makedirs(destination_path, exist_ok=True) # Write metadata with open(os.path.join(destination_path, 'metadata.yaml'), 'wt') as outfile: yaml.dump(dict(metadata), outfile) # Set up RUN setup_fah_run(destination_path, protein_pdb_filename, oemol=oemol, cache=cache, biounit=biounit) print('') except Exception as e: traceback.print_exc(file=sys.stdout) print(e) # prepare_variant('13430', args.run, crystal_name, 'monomer', 'His41(0) Cys145(0)', None) prepare_variant('13431', args.run, crystal_name, 'monomer', 'His41(+) Cys145(-)', None) if oemol is not None: # prepare_variant('13432', args.run, crystal_name, 'monomer', 'His41(0) Cys145(0)', oemol) prepare_variant('13433', args.run, crystal_name, 'monomer', 'His41(+) Cys145(-)', oemol) # prepare_variant('13434', args.run, crystal_name, 'dimer', 'His41(0) Cys145(0)', None) prepare_variant('13435', args.run, crystal_name, 'dimer', 'His41(+) Cys145(-)', None) if oemol is not None: # prepare_variant('13436', args.run, crystal_name, 'dimer', 'His41(0) Cys145(0)', oemol) prepare_variant('13437', args.run, crystal_name, 'dimer', 'His41(+) Cys145(-)', oemol)
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 from random import shuffle from unittest import TestCase import warnings from tsfresh.feature_extraction.feature_calculators import * from tsfresh.feature_extraction.feature_calculators import _roll from tsfresh.feature_extraction.feature_calculators import _get_length_sequences_where from tsfresh.feature_extraction.feature_calculators import _estimate_friedrich_coefficients from tsfresh.feature_extraction.feature_calculators import _aggregate_on_chunks from tsfresh.feature_extraction.feature_calculators import _into_subchunks from tsfresh.examples.driftbif_simulation import velocity import math class FeatureCalculationTestCase(TestCase): def setUp(self): # There will be a lot of warnings in the feature calculators. # Just ignore all of them in these tests warnings.simplefilter("ignore") def tearDown(self): warnings.resetwarnings() def assertIsNaN(self, result): self.assertTrue(np.isnan(result), msg="{} is not np.NaN") def assertEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs): expected_result = f(input_to_f, *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for lists: {} != {}".format(expected_result, result)) expected_result = f(np.array(input_to_f), *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for numpy.arrays: {} != {}".format(expected_result, result)) expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for pandas.Series: {} != {}".format(expected_result, result)) def assertTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(f(input_to_f, *args, **kwargs), msg="Not true for lists") self.assertTrue(f(np.array(input_to_f), *args, **kwargs), msg="Not true for numpy.arrays") self.assertTrue(f(pd.Series(input_to_f), *args, **kwargs), msg="Not true for pandas.Series") def assertAllTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(all(dict(f(input_to_f, *args, **kwargs)).values()), msg="Not true for lists") self.assertTrue(all(dict(f(np.array(input_to_f), *args, **kwargs)).values()), msg="Not true for numpy.arrays") self.assertTrue(all(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()), msg="Not true for pandas.Series") def assertFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertFalse(f(input_to_f, *args, **kwargs), msg="Not false for lists") self.assertFalse(f(np.array(input_to_f), *args, **kwargs), msg="Not false for numpy.arrays") self.assertFalse(f(pd.Series(input_to_f), *args, **kwargs), msg="Not false for pandas.Series") def assertAllFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertFalse(any(dict(f(input_to_f, *args, **kwargs)).values()), msg="Not false for lists") self.assertFalse(any(dict(f(np.array(input_to_f), *args, **kwargs)).values()), msg="Not false for numpy.arrays") self.assertFalse(any(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()), msg="Not false for pandas.Series") def assertAlmostEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs): expected_result = f(input_to_f, *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for lists: {} != {}".format(expected_result, result)) expected_result = f(np.array(input_to_f), *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for numpy.arrays: {} != {}".format(expected_result, result)) expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for pandas.Series: {} != {}".format(expected_result, result)) def assertIsNanOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(np.isnan(f(input_to_f, *args, **kwargs)), msg="Not NaN for lists") self.assertTrue(np.isnan(f(np.array(input_to_f), *args, **kwargs)), msg="Not NaN for numpy.arrays") self.assertTrue(np.isnan(f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)), msg="Not NaN for pandas.Series") def assertEqualPandasSeriesWrapper(self, f, input_to_f, result, *args, **kwargs): self.assertEqual(f(pd.Series(input_to_f), *args, **kwargs), result, msg="Not equal for pandas.Series: {} != {}".format( f(pd.Series(input_to_f), *args, **kwargs), result)) def test__roll(self): x = np.random.normal(size=30) for shift in [0, 1, 10, 11, 30, 31, 50, 51, 150, 151]: np.testing.assert_array_equal(_roll(x, shift), np.roll(x, shift)) np.testing.assert_array_equal(_roll(x, -shift), np.roll(x, -shift)) def test___get_length_sequences_where(self): self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, True, 0, 0, True, True, True, 0, 0, True, 0, True, True], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, True, 0, 0, 1, True, 1, 0, 0, True, 0, 1, True], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0] * 10, [0]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [], [0]) def test__into_subchunks(self): np.testing.assert_array_equal(_into_subchunks(range(7), 3, 2), np.array([[0, 1, 2], [2, 3, 4], [4, 5, 6]])) np.testing.assert_array_equal(_into_subchunks(range(5), 3), np.array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])) def test_variance_larger_than_standard_deviation(self): self.assertFalseOnAllArrayTypes(variance_larger_than_standard_deviation, [-1, -1, 1, 1, 1]) self.assertTrueOnAllArrayTypes(variance_larger_than_standard_deviation, [-1, -1, 1, 1, 2]) def test_large_standard_deviation(self): self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0) self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.25) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.3) self.assertFalseOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.5) def test_symmetry_looking(self): self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-1, -1, 1, 1], [dict(r=0.05), dict(r=0.75)]) self.assertAllFalseOnAllArrayTypes(symmetry_looking, [-1, -1, 1, 1], [dict(r=0)]) self.assertAllFalseOnAllArrayTypes(symmetry_looking, [-1, -1, -1, -1, 1], [dict(r=0.05)]) self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-2, -2, -2, -1, -1, -1], [dict(r=0.05)]) self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-0.9, -0.900001], [dict(r=0.05)]) def test_has_duplicate_max(self): self.assertTrueOnAllArrayTypes(has_duplicate_max, [2.1, 0, 0, 2.1, 1.1]) self.assertFalseOnAllArrayTypes(has_duplicate_max, np.array([2.1, 0, 0, 2, 1.1])) self.assertTrueOnAllArrayTypes(has_duplicate_max, [1, 1, 1, 1]) self.assertFalseOnAllArrayTypes(has_duplicate_max, np.array([0])) self.assertTrueOnAllArrayTypes(has_duplicate_max, np.array([1, 1])) def test_has_duplicate_min(self): self.assertTrueOnAllArrayTypes(has_duplicate_min, [-2.1, 0, 0, -2.1, 1.1]) self.assertFalseOnAllArrayTypes(has_duplicate_min, [2.1, 0, -1, 2, 1.1]) self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1, 1, 1])) self.assertFalseOnAllArrayTypes(has_duplicate_min, np.array([0])) self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1])) def test_has_duplicate(self): self.assertTrueOnAllArrayTypes(has_duplicate, np.array([-2.1, 0, 0, -2.1])) self.assertTrueOnAllArrayTypes(has_duplicate, [-2.1, 2.1, 2.1, 2.1]) self.assertFalseOnAllArrayTypes(has_duplicate, [1.1, 1.2, 1.3, 1.4]) self.assertFalseOnAllArrayTypes(has_duplicate, [1]) self.assertFalseOnAllArrayTypes(has_duplicate, []) def test_sum(self): self.assertEqualOnAllArrayTypes(sum_values, [1, 2, 3, 4.1], 10.1) self.assertEqualOnAllArrayTypes(sum_values, [-1.2, -2, -3, -4], -10.2) self.assertEqualOnAllArrayTypes(sum_values, [], 0) def test_agg_autocorrelation_returns_correct_values(self): param = [{"f_agg": "mean", "maxlag": 10}] x = [1, 1, 1, 1, 1, 1, 1] expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) x = [1, 2, -3] expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2) res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) np.random.seed(42) x = np.random.normal(size=3000) expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=2) param = [{"f_agg": "median", "maxlag": 10}] x = [1, 1, 1, 1, 1, 1, 1] expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"median\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) x = [1, 2, -3] expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2) res = dict(agg_autocorrelation(x, param=param))["f_agg_\"median\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) def test_agg_autocorrelation_returns_max_lag_does_not_affect_other_results(self): param = [{"f_agg": "mean", "maxlag": 1}, {"f_agg": "mean", "maxlag": 10}] x = range(10) res1 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_1"] res10 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res1, 0.77777777, places=4) self.assertAlmostEqual(res10, -0.64983164983165, places=4) param = [{"f_agg": "mean", "maxlag": 1}] x = range(10) res1 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_1"] self.assertAlmostEqual(res1, 0.77777777, places=4) def test_partial_autocorrelation(self): # Test for altering time series # len(x) < max_lag param = [{"lag": lag} for lag in range(10)] x = [1, 2, 1, 2, 1, 2] expected_res = [("lag_0", 1.0), ("lag_1", -1.0), ("lag_2", np.nan)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=4) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=4) self.assertIsNaN(res[2][1]) # Linear signal param = [{"lag": lag} for lag in range(10)] x = np.linspace(0, 1, 3000) expected_res = [("lag_0", 1.0), ("lag_1", 1.0), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=2) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=2) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=2) # Random noise np.random.seed(42) x = np.random.normal(size=3000) param = [{"lag": lag} for lag in range(10)] expected_res = [("lag_0", 1.0), ("lag_1", 0), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1) # On a simulated AR process np.random.seed(42) param = [{"lag": lag} for lag in range(10)] # Simulate AR process T = 3000 epsilon = np.random.randn(T) x = np.repeat(1.0, T) for t in range(T - 1): x[t + 1] = 0.5 * x[t] + 2 + epsilon[t] expected_res = [("lag_0", 1.0), ("lag_1", 0.5), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1) # Some pathological cases param = [{"lag": lag} for lag in range(10)] # List of length 1 res = partial_autocorrelation([1], param=param) for lag_no, lag_val in res: self.assertIsNaN(lag_val) # Empty list res = partial_autocorrelation([], param=param) for lag_no, lag_val in res: self.assertIsNaN(lag_val) # List contains only zeros res = partial_autocorrelation(np.zeros(100), param=param) for lag_no, lag_val in res: if lag_no == "lag_0": self.assertEqual(lag_val, 1.0) else: self.assertIsNaN(lag_val) def test_augmented_dickey_fuller(self): # todo: add unit test for the values of the test statistic # the adf hypothesis test checks for unit roots, # so H_0 = {random drift} vs H_1 = {AR(1) model} # H0 is true np.random.seed(seed=42) x = np.cumsum(np.random.uniform(size=100)) param = [ {"autolag": "BIC", "attr": "teststat"}, {"autolag": "BIC", "attr": "pvalue"}, {"autolag": "BIC", "attr": "usedlag"} ] expected_index = [ 'attr_"teststat"__autolag_"BIC"', 'attr_"pvalue"__autolag_"BIC"', 'attr_"usedlag"__autolag_"BIC"', ] res = augmented_dickey_fuller(x=x, param=param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertGreater(res['attr_"pvalue"__autolag_"BIC"'], 0.10) self.assertEqual(res['attr_"usedlag"__autolag_"BIC"'], 0) # H0 should be rejected for AR(1) model with x_{t} = 1/2 x_{t-1} + e_{t} np.random.seed(seed=42) e = np.random.normal(0.1, 0.1, size=100) m = 50 x = [0] * m x[0] = 100 for i in range(1, m): x[i] = x[i - 1] * 0.5 + e[i] param = [ {"autolag": "AIC", "attr": "teststat"}, {"autolag": "AIC", "attr": "pvalue"}, {"autolag": "AIC", "attr": "usedlag"} ] expected_index = [ 'attr_"teststat"__autolag_"AIC"', 'attr_"pvalue"__autolag_"AIC"', 'attr_"usedlag"__autolag_"AIC"', ] res = augmented_dickey_fuller(x=x, param=param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertLessEqual(res['attr_"pvalue"__autolag_"AIC"'], 0.05) self.assertEqual(res['attr_"usedlag"__autolag_"AIC"'], 0) # Check if LinAlgError and ValueError are catched res_linalg_error = augmented_dickey_fuller(x=np.repeat(np.nan, 100), param=param) res_value_error = augmented_dickey_fuller(x=[], param=param) for index, val in res_linalg_error: self.assertIsNaN(val) for index, val in res_value_error: self.assertIsNaN(val) # Should return NaN if "attr" is unknown res_attr_error = augmented_dickey_fuller(x=x, param=[{"autolag": "AIC", "attr": ""}]) for index, val in res_attr_error: self.assertIsNaN(val) def test_abs_energy(self): self.assertEqualOnAllArrayTypes(abs_energy, [1, 1, 1], 3) self.assertEqualOnAllArrayTypes(abs_energy, [1, 2, 3], 14) self.assertEqualOnAllArrayTypes(abs_energy, [-1, 2, -3], 14) self.assertAlmostEqualOnAllArrayTypes(abs_energy, [-1, 1.3], 2.69) self.assertEqualOnAllArrayTypes(abs_energy, [1], 1) def test_cid_ce(self): self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [0, 4], 2, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [100, 104], 2, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=False) self.assertEqualOnAllArrayTypes(cid_ce, [0.5, 3.5, 7.5], 5, normalize=False) self.assertEqualOnAllArrayTypes(cid_ce, [-4.33, -1.33, 2.67], 5, normalize=False) def test_lempel_ziv_complexity(self): self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1], 2. / 3, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1], 2. / 3, bins=5) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1, 1, 1, 1, 1], 0.4285714285, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1, 2, 1, 1, 1], 0.5714285714, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 0.8, bins=10) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 0.4, bins=10) def test_fourier_entropy(self): self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 2, 1], 0.693147180, bins=2) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 2, 1], 0.693147180, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 1, 2, 1, 1, 1, 1], 0.5623351446188083, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 1, 1, 1, 2, 1, 1], 1.0397207708399179, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 1.5607104090414063, bins=10) self.assertIsNanOnAllArrayTypes(fourier_entropy, [-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6], bins=10) def test_permutation_entropy(self): self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [4, 7, 9, 10, 6, 11, 3], 1.054920167, dimension=3, tau=1) # should grow self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [1, -1, 1, -1, 1, -1, 1, -1], 0.6931471805599453, dimension=3, tau=1) self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [1, -1, 1, -1, 1, 1, 1, -1], 1.3296613488547582, dimension=3, tau=1) self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 1.0397207708399179, dimension=3, tau=2) # nan is treated like any other number self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, np.nan, -3.4, 6], 1.0397207708399179, dimension=3, tau=2) # if too short, return nan self.assertIsNanOnAllArrayTypes(permutation_entropy, [1, -1], dimension=3, tau=1) def test_ratio_beyond_r_sigma(self): x = [0, 1] * 10 + [10, 20, -30] # std of x is 7.21, mean 3.04 self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 3. / len(x), r=1) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 2. / len(x), r=2) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 1. / len(x), r=3) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 0, r=20) def test_mean_abs_change(self): self.assertEqualOnAllArrayTypes(mean_abs_change, [-2, 2, 5], 3.5) self.assertEqualOnAllArrayTypes(mean_abs_change, [1, 2, -1], 2) def test_mean_change(self): self.assertEqualOnAllArrayTypes(mean_change, [-2, 2, 5], 3.5) self.assertEqualOnAllArrayTypes(mean_change, [1, 2, -1], -1) self.assertEqualOnAllArrayTypes(mean_change, [10, 20], 10) self.assertIsNanOnAllArrayTypes(mean_change, [1]) self.assertIsNanOnAllArrayTypes(mean_change, []) def test_mean_second_derivate_central(self): self.assertEqualOnAllArrayTypes(mean_second_derivative_central, list(range(10)), 0) self.assertEqualOnAllArrayTypes(mean_second_derivative_central, [1, 3, 5], 0) self.assertEqualOnAllArrayTypes(mean_second_derivative_central, [1, 3, 7, -3], -3) def test_median(self): self.assertEqualOnAllArrayTypes(median, [1, 1, 2, 2], 1.5) self.assertEqualOnAllArrayTypes(median, [0.5, 0.5, 2, 3.5, 10], 2) self.assertEqualOnAllArrayTypes(median, [0.5], 0.5) self.assertIsNanOnAllArrayTypes(median, []) def test_mean(self): self.assertEqualOnAllArrayTypes(mean, [1, 1, 2, 2], 1.5) self.assertEqualOnAllArrayTypes(mean, [0.5, 0.5, 2, 3.5, 10], 3.3) self.assertEqualOnAllArrayTypes(mean, [0.5], 0.5) self.assertIsNanOnAllArrayTypes(mean, []) def test_length(self): self.assertEqualOnAllArrayTypes(length, [1, 2, 3, 4], 4) self.assertEqualOnAllArrayTypes(length, [1, 2, 3], 3) self.assertEqualOnAllArrayTypes(length, [1, 2], 2) self.assertEqualOnAllArrayTypes(length, [1, 2, 3, np.NaN], 4) self.assertEqualOnAllArrayTypes(length, [], 0) def test_standard_deviation(self): self.assertAlmostEqualOnAllArrayTypes(standard_deviation, [1, 1, -1, -1], 1) self.assertAlmostEqualOnAllArrayTypes(standard_deviation, [1, 2, -2, -1], 1.58113883008) self.assertIsNanOnAllArrayTypes(standard_deviation, []) def test_variation_coefficient(self): self.assertIsNanOnAllArrayTypes(variation_coefficient, [1, 1, -1, -1], ) self.assertAlmostEqualOnAllArrayTypes(variation_coefficient, [1, 2, -3, -1], -7.681145747868608) self.assertAlmostEqualOnAllArrayTypes(variation_coefficient, [1, 2, 4, -1], 1.2018504251546631) self.assertIsNanOnAllArrayTypes(variation_coefficient, []) def test_variance(self): self.assertAlmostEqualOnAllArrayTypes(variance, [1, 1, -1, -1], 1) self.assertAlmostEqualOnAllArrayTypes(variance, [1, 2, -2, -1], 2.5) self.assertIsNanOnAllArrayTypes(variance, []) def test_skewness(self): self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1, 2, 2, 2], 0) self.assertAlmostEqualOnAllArrayTypes(skewness, [1, 1, 1, 2, 2], 0.6085806194501855) self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1], 0) self.assertIsNanOnAllArrayTypes(skewness, [1, 1]) def test_kurtosis(self): self.assertAlmostEqualOnAllArrayTypes(kurtosis, [1, 1, 1, 2, 2], -3.333333333333333) self.assertAlmostEqualOnAllArrayTypes(kurtosis, [1, 1, 1, 1], 0) self.assertIsNanOnAllArrayTypes(kurtosis, [1, 1, 1]) def test_absolute_sum_of_changes(self): self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, 1, 1, 1, 2, 1], 2) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, -1, 1, -1], 6) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1], 0) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [], 0) def test_longest_strike_below_mean(self): self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 1, 1, 1, 2, 2, 2], 3) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 3, 4, 5, 6], 3) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 3, 4, 5], 2) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 1], 1) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [], 0) def test_longest_strike_above_mean(self): self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 1, 2, 1, 2, 2, 1], 2) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 3, 4, 5, 6], 3) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 3, 4, 5], 2) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 1], 1) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [], 0) def test_count_above_mean(self): self.assertEqualOnAllArrayTypes(count_above_mean, [1, 2, 1, 2, 1, 2], 3) self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1, 2], 1) self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1], 0) self.assertEqualOnAllArrayTypes(count_above_mean, [], 0) def test_count_below_mean(self): self.assertEqualOnAllArrayTypes(count_below_mean, [1, 2, 1, 2, 1, 2], 3) self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1, 2], 5) self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1], 0) self.assertEqualOnAllArrayTypes(count_below_mean, [], 0) def test_last_location_maximum(self): self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 2, 1, 2, 1], 0.8) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 2, 1, 1, 2], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [2, 1, 1, 1, 1], 0.2) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 1, 1, 1, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1], 1.0) self.assertIsNanOnAllArrayTypes(last_location_of_maximum, []) def test_first_location_of_maximum(self): self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 2, 1, 2, 1], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 2, 1, 1, 2], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [2, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1], 0.0) self.assertIsNanOnAllArrayTypes(first_location_of_maximum, []) def test_last_location_of_minimum(self): self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 2, 1, 2, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 2, 1, 2, 2], 0.6) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [2, 1, 1, 1, 2], 0.8) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 1, 1, 1, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1], 1.0) self.assertIsNanOnAllArrayTypes(last_location_of_minimum, []) def test_first_location_of_minimum(self): self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1, 2, 1, 2, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [2, 2, 1, 2, 2], 0.4) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [2, 1, 1, 1, 2], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1], 0.0) self.assertIsNanOnAllArrayTypes(first_location_of_minimum, []) def test_percentage_of_doubled_datapoints(self): self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1, 2, 3, 4], 0.4) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1.111, -2.45, 1.111, 2.45], 0.5) self.assertIsNanOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, []) def test_ratio_of_doubled_values(self): self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1, 1, 2, 3, 4], 0.25) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1.111, -2.45, 1.111, 2.45], 1.0 / 3.0) self.assertIsNanOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, []) def test_sum_of_reoccurring_values(self): self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1, 1, 2, 3, 4, 4], 5) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1.111, -2.45, 1.111, 2.45], 1.111) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [], 0) def test_sum_of_reoccurring_data_points(self): self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1, 1, 2, 3, 4, 4], 10) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1.111, -2.45, 1.111, 2.45], 2.222) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [], 0) def test_uniqueness_factor(self): self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1, 1, 2, 3, 4], 0.8) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1, 1.5, 2, 3], 1) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1], 1) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1.111, -2.45, 1.111, 2.45], 0.75) self.assertIsNanOnAllArrayTypes(ratio_value_number_to_time_series_length, []) def test_fft_coefficient(self): x = range(10) param = [{"coeff": 0, "attr": "real"}, {"coeff": 1, "attr": "real"}, {"coeff": 2, "attr": "real"}, {"coeff": 0, "attr": "imag"}, {"coeff": 1, "attr": "imag"}, {"coeff": 2, "attr": "imag"}, {"coeff": 0, "attr": "angle"}, {"coeff": 1, "attr": "angle"}, {"coeff": 2, "attr": "angle"}, {"coeff": 0, "attr": "abs"}, {"coeff": 1, "attr": "abs"}, {"coeff": 2, "attr": "abs"}] expected_index = ['attr_"real"__coeff_0', 'attr_"real"__coeff_1', 'attr_"real"__coeff_2', 'attr_"imag"__coeff_0', 'attr_"imag"__coeff_1', 'attr_"imag"__coeff_2', 'attr_"angle"__coeff_0', 'attr_"angle"__coeff_1', 'attr_"angle"__coeff_2', 'attr_"abs"__coeff_0', 'attr_"abs"__coeff_1', 'attr_"abs"__coeff_2'] res = pd.Series(dict(fft_coefficient(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_0'], sum(x), places=6) self.assertAlmostEqual(res['attr_"angle"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"abs"__coeff_0'], sum(x), places=6) x = [0, 1, 0, 0] res = pd.Series(dict(fft_coefficient(x, param))) # see documentation of fft in numpy # should return array([1. + 0.j, 0. - 1.j, -1. + 0.j]) self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_0'], 1, places=6) self.assertAlmostEqual(res['attr_"imag"__coeff_1'], -1, places=6) self.assertAlmostEqual(res['attr_"angle"__coeff_1'], -90, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_1'], 0, places=6) self.assertAlmostEqual(res['attr_"imag"__coeff_2'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_2'], -1, places=6) # test what happens if coeff is biger than time series lenght x = range(5) param = [{"coeff": 10, "attr": "real"}] expected_index = ['attr_"real"__coeff_10'] res = pd.Series(dict(fft_coefficient(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertIsNaN(res['attr_"real"__coeff_10']) def test_fft_aggregated(self): param = [ {"aggtype": "centroid"}, {"aggtype": "variance"}, {"aggtype": "skew"}, {"aggtype": "kurtosis"} ] expected_index = ['aggtype_"centroid"', 'aggtype_"variance"', 'aggtype_"skew"', 'aggtype_"kurtosis"'] x = np.arange(10) res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3) self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3) self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3) self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3) # Scalar multiplying the distribution should not change the results: x = 10 * x res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3) self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3) self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3) self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3) # The fft of a sign wave is a dirac delta, variance and skew should be near zero, kurtosis should be near 3: # However, in the discrete limit, skew and kurtosis blow up in a manner that is noise dependent and are # therefore bad features, therefore an nan should be returned for these values x = np.sin(2 * np.pi / 10 * np.arange(30)) res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 3., places=5) self.assertAlmostEqual(res['aggtype_"variance"'], 0., places=5) self.assertIsNaN(res['aggtype_"skew"']) self.assertIsNaN(res['aggtype_"kurtosis"']) # Gaussian test: def normal(y, mean_, sigma_): return 1 / (2 * np.pi * sigma_ ** 2) * np.exp(-(y - mean_) ** 2 / (2 * sigma_ ** 2)) mean_ = 500. sigma_ = 1. range_ = int(2 * mean_) x = list(map(lambda x: normal(x, mean_, sigma_), range(range_))) # The fourier transform of a Normal dist in the positive halfspace is a half normal, # Hand calculated values of centroid and variance based for the half-normal dist: # (Ref: https://en.wikipedia.org/wiki/Half-normal_distribution) expected_fft_centroid = (range_ / (2 * np.pi * sigma_)) * np.sqrt(2 / np.pi) expected_fft_var = (range_ / (2 * np.pi * sigma_)) ** 2 * (1 - 2 / np.pi) # Calculate values for unit test: res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) # Compare against hand calculated values: rel_diff_allowed = 0.02 self.assertAlmostEqual( res['aggtype_"centroid"'], expected_fft_centroid, delta=rel_diff_allowed * expected_fft_centroid ) self.assertAlmostEqual( res['aggtype_"variance"'], expected_fft_var, delta=rel_diff_allowed * expected_fft_var ) def test_number_peaks(self): x = np.array([0, 1, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1]) self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 1) self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 2) self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 3) self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 4) self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 5) self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 6) def test_mass_quantile(self): x = [1] * 101 param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 0.5, places=1) # Test for parts of pandas series x = pd.Series([0] * 55 + [1] * 101) param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x[x > 0], param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 0.5, places=1) x = [0] * 1000 + [1] param = [{"q": 0.5}, {"q": 0.99}] expected_index = ["q_0.5", "q_0.99"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 1, places=1) self.assertAlmostEqual(res["q_0.99"], 1, places=1) x = [0, 1, 1, 0, 0, 1, 0, 0] param = [{"q": 0.30}, {"q": 0.60}, {"q": 0.90}] expected_index = ["q_0.3", "q_0.6", "q_0.9"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.3"], 0.25, places=1) self.assertAlmostEqual(res["q_0.6"], 0.375, places=1) self.assertAlmostEqual(res["q_0.9"], 0.75, places=1) x = [0, 0, 0] param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.isnan(res["q_0.5"])) x = [] param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.isnan(res["q_0.5"])) def test_number_cwt_peaks(self): x = [1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1] self.assertEqualOnAllArrayTypes(number_cwt_peaks, x, 2, 2) def test_spkt_welch_density(self): # todo: improve tests x = range(10) param = [{"coeff": 1}, {"coeff": 10}] expected_index = ["coeff_1", "coeff_10"] res = pd.Series(dict(spkt_welch_density(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertIsNaN(res["coeff_10"]) def test_cwt_coefficients(self): x = [0.1, 0.2, 0.3] param = [{"widths": (1, 2, 3), "coeff": 2, "w": 1}, {"widths": (1, 3), "coeff": 2, "w": 3}, {"widths": (1, 3), "coeff": 5, "w": 3}] shuffle(param) expected_index = ["coeff_2__w_1__widths_(1, 2, 3)", "coeff_2__w_3__widths_(1, 3)", "coeff_5__w_3__widths_(1, 3)"] res = cwt_coefficients(x, param) res = pd.Series(dict(res)) # todo: add unit test for the values self.assertCountEqual(list(res.index), expected_index) self.assertTrue(math.isnan(res["coeff_5__w_3__widths_(1, 3)"])) def test_ar_coefficient(self): # Test for X_i = 2.5 * X_{i-1} + 1 param = [{"k": 1, "coeff": 0}, {"k": 1, "coeff": 1}] shuffle(param) x = [1] + 9 * [0] for i in range(1, len(x)): x[i] = 2.5 * x[i - 1] + 1 res = ar_coefficient(x, param) expected_index = ["coeff_0__k_1", "coeff_1__k_1"] res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["coeff_0__k_1"], 1, places=2) self.assertAlmostEqual(res["coeff_1__k_1"], 2.5, places=2) # Test for X_i = 1.4 * X_{i-1} - 1 X_{i-2} + 1 param = [{"k": 1, "coeff": 0}, {"k": 1, "coeff": 1}, {"k": 2, "coeff": 0}, {"k": 2, "coeff": 1}, {"k": 2, "coeff": 2}, {"k": 2, "coeff": 3}] shuffle(param) x = [1, 1] + 5 * [0] for i in range(2, len(x)): x[i] = (-2) * x[i - 2] + 3.5 * x[i - 1] + 1 res = ar_coefficient(x, param) expected_index = ["coeff_0__k_1", "coeff_1__k_1", "coeff_0__k_2", "coeff_1__k_2", "coeff_2__k_2", "coeff_3__k_2"] res = pd.Series(dict(res)) self.assertIsInstance(res, pd.Series) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["coeff_0__k_2"], 1, places=2) self.assertAlmostEqual(res["coeff_1__k_2"], 3.5, places=2) self.assertAlmostEqual(res["coeff_2__k_2"], -2, places=2) self.assertTrue(np.isnan(res["coeff_3__k_2"])) def test_time_reversal_asymmetry_statistic(self): x = [1] * 10 self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 0) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 1) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 3) x = [1, 2, -3, 4] # 1/2 * ( (4^2 * -3 + 3 * 2^2) + (3^2*2)-(2*1^1)) = 1/2 * (-48+12+18-2) = 20/2 self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, -10, 1) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 3) def test_number_crossing_m(self): x = [10, -10, 10, -10] self.assertEqualOnAllArrayTypes(number_crossing_m, x, 3, 0) self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 10) x = [10, 20, 20, 30] self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 0) self.assertEqualOnAllArrayTypes(number_crossing_m, x, 1, 15) def test_c3(self): x = [1] * 10 self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 0) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 1) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 2) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 3) x = [1, 2, -3, 4] # 1/2 *(1*2*(-3)+2*(-3)*4) = 1/2 *(-6-24) = -30/2 self.assertAlmostEqualOnAllArrayTypes(c3, x, -15, 1) self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 3) def test_binned_entropy(self): self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 100, 0, 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 100) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, list(range(10)), - np.math.log(1 / 10), 100) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, list(range(100)), - np.math.log(1 / 2), 2) def test_sample_entropy(self): # "random" list -> large entropy ts = [1, 4, 5, 1, 7, 3, 1, 2, 5, 8, 9, 7, 3, 7, 9, 5, 4, 3, 9, 1, 2, 3, 4, 2, 9, 6, 7, 4, 9, 2, 9, 9, 6, 5, 1, 3, 8, 1, 5, 3, 8, 4, 1, 2, 2, 1, 6, 5, 3, 6, 5, 4, 8, 9, 6, 7, 5, 3, 2, 5, 4, 2, 5, 1, 6, 5, 3, 5, 6, 7, 8, 5, 2, 8, 6, 3, 8, 2, 7, 1, 7, 3, 5, 6, 2, 1, 3, 7, 3, 5, 3, 7, 6, 7, 7, 2, 3, 1, 7, 8] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 2.38262780) # This is not very complex, so it gives a small value ts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.25131442) # however adding a 2 increases complexity ts = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734) # and it does not matter where ts = [1, 1, 1, 2, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734) # negative numbers also work ts = [1, -1, 1, -1, 1, -1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.69314718) # nan gives nan ts = [1, -1, 1, np.nan, 1, -1] self.assertIsNanOnAllArrayTypes(sample_entropy, ts) # this is not a very "random" list, so it should give a small entropy ts = list(range(1000)) self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.0010314596066622707) def test_autocorrelation(self): self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], -1, 1) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 2) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], -1, 3) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 4) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, pd.Series([0, 1, 2, 0, 1, 2]), -0.75, 2) # Autocorrelation lag is larger than length of the time series self.assertIsNanOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 200) self.assertIsNanOnAllArrayTypes(autocorrelation, [np.nan], 0) self.assertIsNanOnAllArrayTypes(autocorrelation, [], 0) # time series with length 1 has no variance, therefore no result for autocorrelation at lag 0 self.assertIsNanOnAllArrayTypes(autocorrelation, [1], 0) def test_quantile(self): self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 1.0, 0.2) self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 0.9) self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 1.0) self.assertAlmostEqualOnAllArrayTypes(quantile, [1], 1, 0.5) self.assertIsNanOnAllArrayTypes(quantile, [], 0.5) def test_mean_abs_change_quantiles(self): self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 1, ql=0.1, qh=0.9, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.15, qh=0.18, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=0.6, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 5, ql=0, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0.5, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0, 1, 0], 0.75, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 1, ql=0.1, qh=0.9, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.15, qh=0.18, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=0.6, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0.5, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0, 1, 0], 0.25, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.1, qh=0.9, isabs=True, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.1, qh=0.9, isabs=False, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 1, 0], 1, ql=0, qh=1, isabs=False, f_agg="std") def test_value_count(self): self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 10, value=1) self.assertEqualPandasSeriesWrapper(value_count, list(range(10)), 1, value=0) self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 0, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.NaN, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.NINF, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.PINF, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [0.1, 0.2, 0.3] * 3, 3, value=0.2) self.assertEqualPandasSeriesWrapper(value_count, [np.NaN, 0, 1] * 3, 3, value=np.NaN) self.assertEqualPandasSeriesWrapper(value_count, [np.NINF, 0, 1] * 3, 3, value=np.NINF) self.assertEqualPandasSeriesWrapper(value_count, [np.PINF, 0, 1] * 3, 3, value=np.PINF) def test_range_count(self): self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=1, max=1) self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=0.9, max=1) self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 10, min=1, max=1.1) self.assertEqualPandasSeriesWrapper(range_count, list(range(10)), 9, min=0, max=9) self.assertEqualPandasSeriesWrapper(range_count, list(range(10)), 10, min=0, max=10) self.assertEqualPandasSeriesWrapper(range_count, list(range(0, -10, -1)), 9, min=-10, max=0) self.assertEqualPandasSeriesWrapper(range_count, [np.NaN, np.PINF, np.NINF] + list(range(10)), 10, min=0, max=10) def test_approximate_entropy(self): self.assertEqualOnAllArrayTypes(approximate_entropy, [1], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5) self.assertAlmostEqualOnAllArrayTypes(approximate_entropy, [12, 13, 15, 16, 17] * 10, 0.282456191, m=2, r=0.9) self.assertRaises(ValueError, approximate_entropy, x=[12, 13, 15, 16, 17] * 10, m=2, r=-0.5) def test_max_langevin_fixed_point(self): """ Estimating the intrinsic velocity of a dissipative soliton """ default_params = {"m": 3, "r": 30} # active Brownian motion ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(100000, v0=np.zeros(1)) v0 = max_langevin_fixed_point(v[:, 0], **default_params) self.assertLess(abs(ds.deterministic - v0), 0.001) # Brownian motion ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) v0 = max_langevin_fixed_point(v[:, 0], **default_params) self.assertLess(v0, 0.001) def test_linear_trend(self): # check linear up trend x = range(10) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend(x, param) res = pd.Series(dict(res)) expected_index = ["attr_\"pvalue\"", "attr_\"intercept\"", "attr_\"rvalue\"", "attr_\"slope\"", "attr_\"stderr\""] self.assertEqual(len(res), 5) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["attr_\"pvalue\""], 0) self.assertAlmostEqual(res["attr_\"stderr\""], 0) self.assertAlmostEqual(res["attr_\"intercept\""], 0) self.assertAlmostEqual(res["attr_\"slope\""], 1.0) # check p value for random trend np.random.seed(42) x = np.random.uniform(size=100) param = [{"attr": "rvalue"}] res = linear_trend(x, param) res = pd.Series(dict(res)) self.assertLess(abs(res["attr_\"rvalue\""]), 0.1) # check slope and intercept decreasing trend with intercept x = [42 - 2 * x for x in range(10)] param = [{"attr": "intercept"}, {"attr": "slope"}] res = linear_trend(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"intercept\""], 42) self.assertAlmostEqual(res["attr_\"slope\""], -2) def test__aggregate_on_chunks(self): self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="max", chunk_len=2), [1, 3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([1, 1, 3, 3]), f_agg="max", chunk_len=2), [1, 3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="min", chunk_len=2), [0, 2]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3, 5]), f_agg="min", chunk_len=2), [0, 2, 5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="mean", chunk_len=2), [0.5, 2.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=2), [0.5, 2, 5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=3), [1 / 3, 4.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3, 5, -2]), f_agg="median", chunk_len=2), [0.5, 2.5, 1.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([-10, 5, 3, -3, 4, -6]), f_agg="median", chunk_len=3), [3, -3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, np.NaN, 5]), f_agg="median", chunk_len=2), [0.5, 2, 5]) def test_agg_linear_trend(self): x = pd.Series(range(9), index=range(9)) param = [{"attr": "intercept", "chunk_len": 3, "f_agg": "max"}, {"attr": "slope", "chunk_len": 3, "f_agg": "max"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "min"}, {"attr": "slope", "chunk_len": 3, "f_agg": "min"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "mean"}, {"attr": "slope", "chunk_len": 3, "f_agg": "mean"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "median"}, {"attr": "slope", "chunk_len": 3, "f_agg": "median"}] expected_index = ['attr_"intercept"__chunk_len_3__f_agg_"max"', 'attr_"slope"__chunk_len_3__f_agg_"max"', 'attr_"intercept"__chunk_len_3__f_agg_"min"', 'attr_"slope"__chunk_len_3__f_agg_"min"', 'attr_"intercept"__chunk_len_3__f_agg_"mean"', 'attr_"slope"__chunk_len_3__f_agg_"mean"', 'attr_"intercept"__chunk_len_3__f_agg_"median"', 'attr_"slope"__chunk_len_3__f_agg_"median"'] res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertEqual(len(res), 8) self.maxDiff = 2000 self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], 2) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], 0) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], 1) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], 1) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 3) x = pd.Series([np.NaN, np.NaN, np.NaN, -3, -3, -3]) res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"max"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"max"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"min"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"min"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"mean"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"mean"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"median"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"median"']) x = pd.Series([np.NaN, np.NaN, -3, -3, -3, -3]) res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 0) def test_energy_ratio_by_chunks(self): x = pd.Series(range(90), index=range(90)) param = [{"num_segments": 6, "segment_focus": i} for i in range(6)] output = energy_ratio_by_chunks(x=x, param=param) self.assertAlmostEqual(output[0][1], 0.0043, places=3) self.assertAlmostEqual(output[1][1], 0.0316, places=3) self.assertAlmostEqual(output[2][1], 0.0871, places=3) self.assertAlmostEqual(output[3][1], 0.1709, places=3) self.assertAlmostEqual(output[4][1], 0.2829, places=3) self.assertAlmostEqual(output[5][1], 0.4232, places=3) # Sum of the ratios should be 1.0 sum = 0.0 for name, dat in output: sum = sum + dat self.assertAlmostEqual(sum, 1.0) x = pd.Series(1, index=range(10)) param = [{"num_segments": 3, "segment_focus": i} for i in range(3)] output = energy_ratio_by_chunks(x=x, param=param) self.assertAlmostEqual(output[0][1], 0.4, places=3) self.assertAlmostEqual(output[1][1], 0.3, places=3) self.assertAlmostEqual(output[2][1], 0.3, places=3) # Sum of the ratios should be 1.0 sum = 0.0 for name, dat in output: sum = sum + dat self.assertAlmostEqual(sum, 1.0) x = pd.Series(0, index=range(10)) param = [{"num_segments": 3, "segment_focus": i} for i in range(3)] output = energy_ratio_by_chunks(x=x, param=param) self.assertIsNaN(output[0][1]) self.assertIsNaN(output[1][1]) self.assertIsNaN(output[2][1]) def test_linear_trend_timewise_hours(self): """Test linear_trend_timewise function with hour intervals.""" x = pd.Series( [0, 1, 3, 6], index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 07:00:00', '2018-01-01 10:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) expected_index = ["attr_\"pvalue\"", "attr_\"intercept\"", "attr_\"rvalue\"", "attr_\"slope\"", "attr_\"stderr\""] self.assertEqual(len(res), 5) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_days(self): """Test linear_trend_timewise function with day intervals.""" # Try with different days x = pd.Series( [0, 24, 48, 72], index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2018-01-02 04:00:00', '2018-01-03 04:00:00', '2018-01-04 04:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_seconds(self): """Test linear_trend_timewise function with second intervals.""" # Try with different days x = pd.Series( [0, 1 / float(3600), 2 / float(3600), 3 / float(3600)], index=pd.DatetimeIndex([ '2018-01-01 04:00:01', '2018-01-01 04:00:02', '2018-01-01 04:00:03', '2018-01-01 04:00:04' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_years(self): """Test linear_trend_timewise function with year intervals.""" # Try with different days x = pd.Series( [0, 365 * 24, 365 * 48, 365 * 72 + 24], # Add 24 to the last one since it's a leap year index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2019-01-01 04:00:00', '2020-01-01 04:00:00', '2021-01-01 04:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_change_quantiles(self): """Test change_quantiles function when changing from `sum` to `np.sum`.""" np.random.seed(0) res = change_quantiles(np.random.rand(10000) * 1000, 0.1, 0.2, False, 'mean') self.assertAlmostEqual(res, -0.9443846621365727) def test_count_above(self): self.assertEqualPandasSeriesWrapper(count_above, [1] * 10, 1, t=1) self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 1, t=0) self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 0.5, t=5) self.assertEqualPandasSeriesWrapper(count_above, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2) self.assertEqualPandasSeriesWrapper(count_above, [np.NaN, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.NINF, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.PINF, 0, 1] * 3, 1, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.NaN, 0, 1] * 3, 0, t=np.NaN) self.assertEqualPandasSeriesWrapper(count_above, [np.NINF, 0, np.PINF] * 3, 1, t=np.NINF) self.assertEqualPandasSeriesWrapper(count_above, [np.PINF, 0, 1] * 3, 1 / 3, t=np.PINF) def test_count_below(self): self.assertEqualPandasSeriesWrapper(count_below, [1] * 10, 1, t=1) self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 1 / 10, t=0) self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 6 / 10, t=5) self.assertEqualPandasSeriesWrapper(count_below, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2) self.assertEqualPandasSeriesWrapper(count_below, [np.NaN, 0, 1] * 3, 1 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.NINF, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.PINF, 0, 1] * 3, 1 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.NaN, 0, 1] * 3, 0, t=np.NaN) self.assertEqualPandasSeriesWrapper(count_below, [np.NINF, 0, np.PINF] * 3, 1 / 3, t=np.NINF) self.assertEqualPandasSeriesWrapper(count_below, [np.PINF, 0, 1] * 3, 1, t=np.PINF) def test_benford_correlation(self): # A test with list of random values np.random.seed(42) random_list = np.random.uniform(size=100) # Fibonacci series is known to match the Newcomb-Benford's Distribution fibonacci_list = [0, 1] for i in range(2, 200): fibonacci_list.append(fibonacci_list[i - 1] + fibonacci_list[i - 2]) # A list of equally distributed digits (returns NaN) equal_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # A list containing NaN list_with_nan = [1.354, 0.058, 0.055, 0.99, 3.15, np.nan, 0.3, 2.3, 0, 0.59, 0.74] self.assertAlmostEqual(benford_correlation(random_list), 0.39458056) self.assertAlmostEqual(benford_correlation(fibonacci_list), 0.998003988) self.assertAlmostEqual(benford_correlation(list_with_nan), 0.10357511) self.assertIsNaN(benford_correlation(equal_list)) class FriedrichTestCase(TestCase): def test_estimate_friedrich_coefficients(self): """ Estimate friedrich coefficients """ default_params = {"m": 3, "r": 30} # active Brownian motion ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params) self.assertLess(abs(coeff[-1]), 0.0001) # Brownian motion ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params) self.assertLess(abs(coeff[-1]), 0.0001) def test_friedrich_coefficients(self): # Test binning error returns vector of NaNs param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)] x = np.zeros(100) res = pd.Series(dict(friedrich_coefficients(x, param))) expected_index = ["coeff_0__m_2__r_30", "coeff_1__m_2__r_30", "coeff_2__m_2__r_30", "coeff_3__m_2__r_30"] self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.sum(np.isnan(res)), 3) def test_friedrich_number_of_returned_features_is_equal_to_number_of_parameters(self): """ unit test for issue 501 """ param = [{'m': 3, 'r': 5, 'coeff': 2}, {'m': 3, 'r': 5, 'coeff': 3}, {'m': 3, 'r': 2, 'coeff': 3}] x = np.zeros(100) res = pd.Series(dict(friedrich_coefficients(x, param))) expected_index = ["coeff_2__m_3__r_5", "coeff_3__m_3__r_5", "coeff_3__m_3__r_2"] self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.sum(np.isnan(res)), 3) def test_friedrich_equal_to_snapshot(self): param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)] x = np.array([-0.53, -0.61, -1.26, -0.88, -0.34, 0.58, 2.86, -0.47, 0.78, -0.45, -0.27, 0.43, 1.72, 0.26, 1.02, -0.09, 0.65, 1.49, -0.95, -1.02, -0.64, -1.63, -0.71, -0.43, -1.69, 0.05, 1.58, 1.1, 0.55, -1.02]) res = pd.Series(dict(friedrich_coefficients(x, param))) self.assertAlmostEqual(res['coeff_0__m_2__r_30'], -0.24536975738843042) self.assertAlmostEqual(res['coeff_1__m_2__r_30'], -0.533309548662685) self.assertAlmostEqual(res['coeff_2__m_2__r_30'], 0.2759399238199404)
# -*- coding: utf-8 -*- # This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt) # Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016 from random import shuffle from unittest import TestCase import warnings from tsfresh.feature_extraction.feature_calculators import * from tsfresh.feature_extraction.feature_calculators import _roll from tsfresh.feature_extraction.feature_calculators import _get_length_sequences_where from tsfresh.feature_extraction.feature_calculators import _estimate_friedrich_coefficients from tsfresh.feature_extraction.feature_calculators import _aggregate_on_chunks from tsfresh.feature_extraction.feature_calculators import _into_subchunks from tsfresh.examples.driftbif_simulation import velocity import math class FeatureCalculationTestCase(TestCase): def setUp(self): # There will be a lot of warnings in the feature calculators. # Just ignore all of them in these tests warnings.simplefilter("ignore") def tearDown(self): warnings.resetwarnings() def assertIsNaN(self, result): self.assertTrue(np.isnan(result), msg="{} is not np.NaN") def assertEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs): expected_result = f(input_to_f, *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for lists: {} != {}".format(expected_result, result)) expected_result = f(np.array(input_to_f), *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for numpy.arrays: {} != {}".format(expected_result, result)) expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs) self.assertEqual(expected_result, result, msg="Not equal for pandas.Series: {} != {}".format(expected_result, result)) def assertTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(f(input_to_f, *args, **kwargs), msg="Not true for lists") self.assertTrue(f(np.array(input_to_f), *args, **kwargs), msg="Not true for numpy.arrays") self.assertTrue(f(pd.Series(input_to_f), *args, **kwargs), msg="Not true for pandas.Series") def assertAllTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(all(dict(f(input_to_f, *args, **kwargs)).values()), msg="Not true for lists") self.assertTrue(all(dict(f(np.array(input_to_f), *args, **kwargs)).values()), msg="Not true for numpy.arrays") self.assertTrue(all(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()), msg="Not true for pandas.Series") def assertFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertFalse(f(input_to_f, *args, **kwargs), msg="Not false for lists") self.assertFalse(f(np.array(input_to_f), *args, **kwargs), msg="Not false for numpy.arrays") self.assertFalse(f(pd.Series(input_to_f), *args, **kwargs), msg="Not false for pandas.Series") def assertAllFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertFalse(any(dict(f(input_to_f, *args, **kwargs)).values()), msg="Not false for lists") self.assertFalse(any(dict(f(np.array(input_to_f), *args, **kwargs)).values()), msg="Not false for numpy.arrays") self.assertFalse(any(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()), msg="Not false for pandas.Series") def assertAlmostEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs): expected_result = f(input_to_f, *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for lists: {} != {}".format(expected_result, result)) expected_result = f(np.array(input_to_f), *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for numpy.arrays: {} != {}".format(expected_result, result)) expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs) self.assertAlmostEqual(expected_result, result, msg="Not almost equal for pandas.Series: {} != {}".format(expected_result, result)) def assertIsNanOnAllArrayTypes(self, f, input_to_f, *args, **kwargs): self.assertTrue(np.isnan(f(input_to_f, *args, **kwargs)), msg="Not NaN for lists") self.assertTrue(np.isnan(f(np.array(input_to_f), *args, **kwargs)), msg="Not NaN for numpy.arrays") self.assertTrue(np.isnan(f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)), msg="Not NaN for pandas.Series") def assertEqualPandasSeriesWrapper(self, f, input_to_f, result, *args, **kwargs): self.assertEqual(f(pd.Series(input_to_f), *args, **kwargs), result, msg="Not equal for pandas.Series: {} != {}".format( f(pd.Series(input_to_f), *args, **kwargs), result)) def test__roll(self): x = np.random.normal(size=30) for shift in [0, 1, 10, 11, 30, 31, 50, 51, 150, 151]: np.testing.assert_array_equal(_roll(x, shift), np.roll(x, shift)) np.testing.assert_array_equal(_roll(x, -shift), np.roll(x, -shift)) def test___get_length_sequences_where(self): self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, True, 0, 0, True, True, True, 0, 0, True, 0, True, True], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0, True, 0, 0, 1, True, 1, 0, 0, True, 0, 1, True], [1, 3, 1, 2]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0] * 10, [0]) self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [], [0]) def test__into_subchunks(self): np.testing.assert_array_equal(_into_subchunks(range(7), 3, 2), np.array([[0, 1, 2], [2, 3, 4], [4, 5, 6]])) np.testing.assert_array_equal(_into_subchunks(range(5), 3), np.array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])) def test_variance_larger_than_standard_deviation(self): self.assertFalseOnAllArrayTypes(variance_larger_than_standard_deviation, [-1, -1, 1, 1, 1]) self.assertTrueOnAllArrayTypes(variance_larger_than_standard_deviation, [-1, -1, 1, 1, 2]) def test_large_standard_deviation(self): self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0) self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.25) self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.3) self.assertFalseOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.5) def test_symmetry_looking(self): self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-1, -1, 1, 1], [dict(r=0.05), dict(r=0.75)]) self.assertAllFalseOnAllArrayTypes(symmetry_looking, [-1, -1, 1, 1], [dict(r=0)]) self.assertAllFalseOnAllArrayTypes(symmetry_looking, [-1, -1, -1, -1, 1], [dict(r=0.05)]) self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-2, -2, -2, -1, -1, -1], [dict(r=0.05)]) self.assertAllTrueOnAllArrayTypes(symmetry_looking, [-0.9, -0.900001], [dict(r=0.05)]) def test_has_duplicate_max(self): self.assertTrueOnAllArrayTypes(has_duplicate_max, [2.1, 0, 0, 2.1, 1.1]) self.assertFalseOnAllArrayTypes(has_duplicate_max, np.array([2.1, 0, 0, 2, 1.1])) self.assertTrueOnAllArrayTypes(has_duplicate_max, [1, 1, 1, 1]) self.assertFalseOnAllArrayTypes(has_duplicate_max, np.array([0])) self.assertTrueOnAllArrayTypes(has_duplicate_max, np.array([1, 1])) def test_has_duplicate_min(self): self.assertTrueOnAllArrayTypes(has_duplicate_min, [-2.1, 0, 0, -2.1, 1.1]) self.assertFalseOnAllArrayTypes(has_duplicate_min, [2.1, 0, -1, 2, 1.1]) self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1, 1, 1])) self.assertFalseOnAllArrayTypes(has_duplicate_min, np.array([0])) self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1])) def test_has_duplicate(self): self.assertTrueOnAllArrayTypes(has_duplicate, np.array([-2.1, 0, 0, -2.1])) self.assertTrueOnAllArrayTypes(has_duplicate, [-2.1, 2.1, 2.1, 2.1]) self.assertFalseOnAllArrayTypes(has_duplicate, [1.1, 1.2, 1.3, 1.4]) self.assertFalseOnAllArrayTypes(has_duplicate, [1]) self.assertFalseOnAllArrayTypes(has_duplicate, []) def test_sum(self): self.assertEqualOnAllArrayTypes(sum_values, [1, 2, 3, 4.1], 10.1) self.assertEqualOnAllArrayTypes(sum_values, [-1.2, -2, -3, -4], -10.2) self.assertEqualOnAllArrayTypes(sum_values, [], 0) def test_agg_autocorrelation_returns_correct_values(self): param = [{"f_agg": "mean", "maxlag": 10}] x = [1, 1, 1, 1, 1, 1, 1] expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) x = [1, 2, -3] expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2) res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) np.random.seed(42) x = np.random.normal(size=3000) expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=2) param = [{"f_agg": "median", "maxlag": 10}] x = [1, 1, 1, 1, 1, 1, 1] expected_res = 0 res = dict(agg_autocorrelation(x, param=param))["f_agg_\"median\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) x = [1, 2, -3] expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2) res = dict(agg_autocorrelation(x, param=param))["f_agg_\"median\"__maxlag_10"] self.assertAlmostEqual(res, expected_res, places=4) def test_agg_autocorrelation_returns_max_lag_does_not_affect_other_results(self): param = [{"f_agg": "mean", "maxlag": 1}, {"f_agg": "mean", "maxlag": 10}] x = range(10) res1 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_1"] res10 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_10"] self.assertAlmostEqual(res1, 0.77777777, places=4) self.assertAlmostEqual(res10, -0.64983164983165, places=4) param = [{"f_agg": "mean", "maxlag": 1}] x = range(10) res1 = dict(agg_autocorrelation(x, param=param))["f_agg_\"mean\"__maxlag_1"] self.assertAlmostEqual(res1, 0.77777777, places=4) def test_partial_autocorrelation(self): # Test for altering time series # len(x) < max_lag param = [{"lag": lag} for lag in range(10)] x = [1, 2, 1, 2, 1, 2] expected_res = [("lag_0", 1.0), ("lag_1", -1.0), ("lag_2", np.nan)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=4) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=4) self.assertIsNaN(res[2][1]) # Linear signal param = [{"lag": lag} for lag in range(10)] x = np.linspace(0, 1, 3000) expected_res = [("lag_0", 1.0), ("lag_1", 1.0), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=2) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=2) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=2) # Random noise np.random.seed(42) x = np.random.normal(size=3000) param = [{"lag": lag} for lag in range(10)] expected_res = [("lag_0", 1.0), ("lag_1", 0), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1) # On a simulated AR process np.random.seed(42) param = [{"lag": lag} for lag in range(10)] # Simulate AR process T = 3000 epsilon = np.random.randn(T) x = np.repeat(1.0, T) for t in range(T - 1): x[t + 1] = 0.5 * x[t] + 2 + epsilon[t] expected_res = [("lag_0", 1.0), ("lag_1", 0.5), ("lag_2", 0)] res = partial_autocorrelation(x, param=param) self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1) self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1) self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1) # Some pathological cases param = [{"lag": lag} for lag in range(10)] # List of length 1 res = partial_autocorrelation([1], param=param) for lag_no, lag_val in res: self.assertIsNaN(lag_val) # Empty list res = partial_autocorrelation([], param=param) for lag_no, lag_val in res: self.assertIsNaN(lag_val) # List contains only zeros res = partial_autocorrelation(np.zeros(100), param=param) for lag_no, lag_val in res: if lag_no == "lag_0": self.assertEqual(lag_val, 1.0) else: self.assertIsNaN(lag_val) def test_augmented_dickey_fuller(self): # todo: add unit test for the values of the test statistic # the adf hypothesis test checks for unit roots, # so H_0 = {random drift} vs H_1 = {AR(1) model} # H0 is true np.random.seed(seed=42) x = np.cumsum(np.random.uniform(size=100)) param = [ {"autolag": "BIC", "attr": "teststat"}, {"autolag": "BIC", "attr": "pvalue"}, {"autolag": "BIC", "attr": "usedlag"} ] expected_index = [ 'attr_"teststat"__autolag_"BIC"', 'attr_"pvalue"__autolag_"BIC"', 'attr_"usedlag"__autolag_"BIC"', ] res = augmented_dickey_fuller(x=x, param=param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertGreater(res['attr_"pvalue"__autolag_"BIC"'], 0.10) self.assertEqual(res['attr_"usedlag"__autolag_"BIC"'], 0) # H0 should be rejected for AR(1) model with x_{t} = 1/2 x_{t-1} + e_{t} np.random.seed(seed=42) e = np.random.normal(0.1, 0.1, size=100) m = 50 x = [0] * m x[0] = 100 for i in range(1, m): x[i] = x[i - 1] * 0.5 + e[i] param = [ {"autolag": "AIC", "attr": "teststat"}, {"autolag": "AIC", "attr": "pvalue"}, {"autolag": "AIC", "attr": "usedlag"} ] expected_index = [ 'attr_"teststat"__autolag_"AIC"', 'attr_"pvalue"__autolag_"AIC"', 'attr_"usedlag"__autolag_"AIC"', ] res = augmented_dickey_fuller(x=x, param=param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertLessEqual(res['attr_"pvalue"__autolag_"AIC"'], 0.05) self.assertEqual(res['attr_"usedlag"__autolag_"AIC"'], 0) # Check if LinAlgError and ValueError are catched res_linalg_error = augmented_dickey_fuller(x=np.repeat(np.nan, 100), param=param) res_value_error = augmented_dickey_fuller(x=[], param=param) for index, val in res_linalg_error: self.assertIsNaN(val) for index, val in res_value_error: self.assertIsNaN(val) # Should return NaN if "attr" is unknown res_attr_error = augmented_dickey_fuller(x=x, param=[{"autolag": "AIC", "attr": ""}]) for index, val in res_attr_error: self.assertIsNaN(val) def test_abs_energy(self): self.assertEqualOnAllArrayTypes(abs_energy, [1, 1, 1], 3) self.assertEqualOnAllArrayTypes(abs_energy, [1, 2, 3], 14) self.assertEqualOnAllArrayTypes(abs_energy, [-1, 2, -3], 14) self.assertAlmostEqualOnAllArrayTypes(abs_energy, [-1, 1.3], 2.69) self.assertEqualOnAllArrayTypes(abs_energy, [1], 1) def test_cid_ce(self): self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [0, 4], 2, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [100, 104], 2, normalize=True) self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=False) self.assertEqualOnAllArrayTypes(cid_ce, [0.5, 3.5, 7.5], 5, normalize=False) self.assertEqualOnAllArrayTypes(cid_ce, [-4.33, -1.33, 2.67], 5, normalize=False) def test_lempel_ziv_complexity(self): self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1], 2. / 3, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1], 2. / 3, bins=5) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1, 1, 1, 1, 1], 0.4285714285, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [1, 1, 1, 2, 1, 1, 1], 0.5714285714, bins=2) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 0.8, bins=10) self.assertAlmostEqualOnAllArrayTypes(lempel_ziv_complexity, [-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 0.4, bins=10) def test_fourier_entropy(self): self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 2, 1], 0.693147180, bins=2) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 2, 1], 0.693147180, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 1, 2, 1, 1, 1, 1], 0.5623351446188083, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [1, 1, 1, 1, 2, 1, 1], 1.0397207708399179, bins=5) self.assertAlmostEqualOnAllArrayTypes(fourier_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 1.5607104090414063, bins=10) self.assertIsNanOnAllArrayTypes(fourier_entropy, [-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6], bins=10) def test_permutation_entropy(self): self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [4, 7, 9, 10, 6, 11, 3], 1.054920167, dimension=3, tau=1) # should grow self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [1, -1, 1, -1, 1, -1, 1, -1], 0.6931471805599453, dimension=3, tau=1) self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [1, -1, 1, -1, 1, 1, 1, -1], 1.3296613488547582, dimension=3, tau=1) self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 1.0397207708399179, dimension=3, tau=2) # nan is treated like any other number self.assertAlmostEqualOnAllArrayTypes(permutation_entropy, [-1, 4.3, 5, 1, -4.5, 1, 5, np.nan, -3.4, 6], 1.0397207708399179, dimension=3, tau=2) # if too short, return nan self.assertIsNanOnAllArrayTypes(permutation_entropy, [1, -1], dimension=3, tau=1) def test_ratio_beyond_r_sigma(self): x = [0, 1] * 10 + [10, 20, -30] # std of x is 7.21, mean 3.04 self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 3. / len(x), r=1) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 2. / len(x), r=2) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 1. / len(x), r=3) self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 0, r=20) def test_mean_abs_change(self): self.assertEqualOnAllArrayTypes(mean_abs_change, [-2, 2, 5], 3.5) self.assertEqualOnAllArrayTypes(mean_abs_change, [1, 2, -1], 2) def test_mean_change(self): self.assertEqualOnAllArrayTypes(mean_change, [-2, 2, 5], 3.5) self.assertEqualOnAllArrayTypes(mean_change, [1, 2, -1], -1) self.assertEqualOnAllArrayTypes(mean_change, [10, 20], 10) self.assertIsNanOnAllArrayTypes(mean_change, [1]) self.assertIsNanOnAllArrayTypes(mean_change, []) def test_mean_second_derivate_central(self): self.assertEqualOnAllArrayTypes(mean_second_derivative_central, list(range(10)), 0) self.assertEqualOnAllArrayTypes(mean_second_derivative_central, [1, 3, 5], 0) self.assertEqualOnAllArrayTypes(mean_second_derivative_central, [1, 3, 7, -3], -3) def test_median(self): self.assertEqualOnAllArrayTypes(median, [1, 1, 2, 2], 1.5) self.assertEqualOnAllArrayTypes(median, [0.5, 0.5, 2, 3.5, 10], 2) self.assertEqualOnAllArrayTypes(median, [0.5], 0.5) self.assertIsNanOnAllArrayTypes(median, []) def test_mean(self): self.assertEqualOnAllArrayTypes(mean, [1, 1, 2, 2], 1.5) self.assertEqualOnAllArrayTypes(mean, [0.5, 0.5, 2, 3.5, 10], 3.3) self.assertEqualOnAllArrayTypes(mean, [0.5], 0.5) self.assertIsNanOnAllArrayTypes(mean, []) def test_length(self): self.assertEqualOnAllArrayTypes(length, [1, 2, 3, 4], 4) self.assertEqualOnAllArrayTypes(length, [1, 2, 3], 3) self.assertEqualOnAllArrayTypes(length, [1, 2], 2) self.assertEqualOnAllArrayTypes(length, [1, 2, 3, np.NaN], 4) self.assertEqualOnAllArrayTypes(length, [], 0) def test_standard_deviation(self): self.assertAlmostEqualOnAllArrayTypes(standard_deviation, [1, 1, -1, -1], 1) self.assertAlmostEqualOnAllArrayTypes(standard_deviation, [1, 2, -2, -1], 1.58113883008) self.assertIsNanOnAllArrayTypes(standard_deviation, []) def test_variation_coefficient(self): self.assertIsNanOnAllArrayTypes(variation_coefficient, [1, 1, -1, -1], ) self.assertAlmostEqualOnAllArrayTypes(variation_coefficient, [1, 2, -3, -1], -7.681145747868608) self.assertAlmostEqualOnAllArrayTypes(variation_coefficient, [1, 2, 4, -1], 1.2018504251546631) self.assertIsNanOnAllArrayTypes(variation_coefficient, []) def test_variance(self): self.assertAlmostEqualOnAllArrayTypes(variance, [1, 1, -1, -1], 1) self.assertAlmostEqualOnAllArrayTypes(variance, [1, 2, -2, -1], 2.5) self.assertIsNanOnAllArrayTypes(variance, []) def test_skewness(self): self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1, 2, 2, 2], 0) self.assertAlmostEqualOnAllArrayTypes(skewness, [1, 1, 1, 2, 2], 0.6085806194501855) self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1], 0) self.assertIsNanOnAllArrayTypes(skewness, [1, 1]) def test_kurtosis(self): self.assertAlmostEqualOnAllArrayTypes(kurtosis, [1, 1, 1, 2, 2], -3.333333333333333) self.assertAlmostEqualOnAllArrayTypes(kurtosis, [1, 1, 1, 1], 0) self.assertIsNanOnAllArrayTypes(kurtosis, [1, 1, 1]) def test_absolute_sum_of_changes(self): self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, 1, 1, 1, 2, 1], 2) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, -1, 1, -1], 6) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1], 0) self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [], 0) def test_longest_strike_below_mean(self): self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 1, 1, 1, 2, 2, 2], 3) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 3, 4, 5, 6], 3) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 3, 4, 5], 2) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 1], 1) self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [], 0) def test_longest_strike_above_mean(self): self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 1, 2, 1, 2, 2, 1], 2) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 3, 4, 5, 6], 3) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 3, 4, 5], 2) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 1], 1) self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [], 0) def test_count_above_mean(self): self.assertEqualOnAllArrayTypes(count_above_mean, [1, 2, 1, 2, 1, 2], 3) self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1, 2], 1) self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1], 0) self.assertEqualOnAllArrayTypes(count_above_mean, [], 0) def test_count_below_mean(self): self.assertEqualOnAllArrayTypes(count_below_mean, [1, 2, 1, 2, 1, 2], 3) self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1, 2], 5) self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1], 0) self.assertEqualOnAllArrayTypes(count_below_mean, [], 0) def test_last_location_maximum(self): self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 2, 1, 2, 1], 0.8) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 2, 1, 1, 2], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [2, 1, 1, 1, 1], 0.2) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1, 1, 1, 1, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1], 1.0) self.assertIsNanOnAllArrayTypes(last_location_of_maximum, []) def test_first_location_of_maximum(self): self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 2, 1, 2, 1], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 2, 1, 1, 2], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [2, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1], 0.0) self.assertIsNanOnAllArrayTypes(first_location_of_maximum, []) def test_last_location_of_minimum(self): self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 2, 1, 2, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 2, 1, 2, 2], 0.6) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [2, 1, 1, 1, 2], 0.8) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1, 1, 1, 1, 1], 1.0) self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1], 1.0) self.assertIsNanOnAllArrayTypes(last_location_of_minimum, []) def test_first_location_of_minimum(self): self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1, 2, 1, 2, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [2, 2, 1, 2, 2], 0.4) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [2, 1, 1, 1, 2], 0.2) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1, 1, 1, 1, 1], 0.0) self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1], 0.0) self.assertIsNanOnAllArrayTypes(first_location_of_minimum, []) def test_percentage_of_doubled_datapoints(self): self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1, 2, 3, 4], 0.4) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, [1.111, -2.45, 1.111, 2.45], 0.5) self.assertIsNanOnAllArrayTypes(percentage_of_reoccurring_datapoints_to_all_datapoints, []) def test_ratio_of_doubled_values(self): self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1, 1, 2, 3, 4], 0.25) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1], 0) self.assertAlmostEqualOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, [1.111, -2.45, 1.111, 2.45], 1.0 / 3.0) self.assertIsNanOnAllArrayTypes(percentage_of_reoccurring_values_to_all_values, []) def test_sum_of_reoccurring_values(self): self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1, 1, 2, 3, 4, 4], 5) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1.111, -2.45, 1.111, 2.45], 1.111) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [], 0) def test_sum_of_reoccurring_data_points(self): self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1, 1, 2, 3, 4, 4], 10) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1, 1.5, 2, 3], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1], 0) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1.111, -2.45, 1.111, 2.45], 2.222) self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [], 0) def test_uniqueness_factor(self): self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1, 1, 2, 3, 4], 0.8) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1, 1.5, 2, 3], 1) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1], 1) self.assertAlmostEqualOnAllArrayTypes(ratio_value_number_to_time_series_length, [1.111, -2.45, 1.111, 2.45], 0.75) self.assertIsNanOnAllArrayTypes(ratio_value_number_to_time_series_length, []) def test_fft_coefficient(self): x = range(10) param = [{"coeff": 0, "attr": "real"}, {"coeff": 1, "attr": "real"}, {"coeff": 2, "attr": "real"}, {"coeff": 0, "attr": "imag"}, {"coeff": 1, "attr": "imag"}, {"coeff": 2, "attr": "imag"}, {"coeff": 0, "attr": "angle"}, {"coeff": 1, "attr": "angle"}, {"coeff": 2, "attr": "angle"}, {"coeff": 0, "attr": "abs"}, {"coeff": 1, "attr": "abs"}, {"coeff": 2, "attr": "abs"}] expected_index = ['attr_"real"__coeff_0', 'attr_"real"__coeff_1', 'attr_"real"__coeff_2', 'attr_"imag"__coeff_0', 'attr_"imag"__coeff_1', 'attr_"imag"__coeff_2', 'attr_"angle"__coeff_0', 'attr_"angle"__coeff_1', 'attr_"angle"__coeff_2', 'attr_"abs"__coeff_0', 'attr_"abs"__coeff_1', 'attr_"abs"__coeff_2'] res = pd.Series(dict(fft_coefficient(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_0'], sum(x), places=6) self.assertAlmostEqual(res['attr_"angle"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"abs"__coeff_0'], sum(x), places=6) x = [0, 1, 0, 0] res = pd.Series(dict(fft_coefficient(x, param))) # see documentation of fft in numpy # should return array([1. + 0.j, 0. - 1.j, -1. + 0.j]) self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_0'], 1, places=6) self.assertAlmostEqual(res['attr_"imag"__coeff_1'], -1, places=6) self.assertAlmostEqual(res['attr_"angle"__coeff_1'], -90, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_1'], 0, places=6) self.assertAlmostEqual(res['attr_"imag"__coeff_2'], 0, places=6) self.assertAlmostEqual(res['attr_"real"__coeff_2'], -1, places=6) # test what happens if coeff is biger than time series lenght x = range(5) param = [{"coeff": 10, "attr": "real"}] expected_index = ['attr_"real"__coeff_10'] res = pd.Series(dict(fft_coefficient(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertIsNaN(res['attr_"real"__coeff_10']) def test_fft_aggregated(self): param = [ {"aggtype": "centroid"}, {"aggtype": "variance"}, {"aggtype": "skew"}, {"aggtype": "kurtosis"} ] expected_index = ['aggtype_"centroid"', 'aggtype_"variance"', 'aggtype_"skew"', 'aggtype_"kurtosis"'] x = np.arange(10) res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3) self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3) self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3) self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3) # Scalar multiplying the distribution should not change the results: x = 10 * x res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3) self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3) self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3) self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3) # The fft of a sign wave is a dirac delta, variance and skew should be near zero, kurtosis should be near 3: # However, in the discrete limit, skew and kurtosis blow up in a manner that is noise dependent and are # therefore bad features, therefore an nan should be returned for these values x = np.sin(2 * np.pi / 10 * np.arange(30)) res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['aggtype_"centroid"'], 3., places=5) self.assertAlmostEqual(res['aggtype_"variance"'], 0., places=5) self.assertIsNaN(res['aggtype_"skew"']) self.assertIsNaN(res['aggtype_"kurtosis"']) # Gaussian test: def normal(y, mean_, sigma_): return 1 / (2 * np.pi * sigma_ ** 2) * np.exp(-(y - mean_) ** 2 / (2 * sigma_ ** 2)) mean_ = 500. sigma_ = 1. range_ = int(2 * mean_) x = list(map(lambda x: normal(x, mean_, sigma_), range(range_))) # The fourier transform of a Normal dist in the positive halfspace is a half normal, # Hand calculated values of centroid and variance based for the half-normal dist: # (Ref: https://en.wikipedia.org/wiki/Half-normal_distribution) expected_fft_centroid = (range_ / (2 * np.pi * sigma_)) * np.sqrt(2 / np.pi) expected_fft_var = (range_ / (2 * np.pi * sigma_)) ** 2 * (1 - 2 / np.pi) # Calculate values for unit test: res = pd.Series(dict(fft_aggregated(x, param))) self.assertCountEqual(list(res.index), expected_index) # Compare against hand calculated values: rel_diff_allowed = 0.02 self.assertAlmostEqual( res['aggtype_"centroid"'], expected_fft_centroid, delta=rel_diff_allowed * expected_fft_centroid ) self.assertAlmostEqual( res['aggtype_"variance"'], expected_fft_var, delta=rel_diff_allowed * expected_fft_var ) def test_number_peaks(self): x = np.array([0, 1, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1]) self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 1) self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 2) self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 3) self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 4) self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 5) self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 6) def test_mass_quantile(self): x = [1] * 101 param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 0.5, places=1) # Test for parts of pandas series x = pd.Series([0] * 55 + [1] * 101) param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x[x > 0], param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 0.5, places=1) x = [0] * 1000 + [1] param = [{"q": 0.5}, {"q": 0.99}] expected_index = ["q_0.5", "q_0.99"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.5"], 1, places=1) self.assertAlmostEqual(res["q_0.99"], 1, places=1) x = [0, 1, 1, 0, 0, 1, 0, 0] param = [{"q": 0.30}, {"q": 0.60}, {"q": 0.90}] expected_index = ["q_0.3", "q_0.6", "q_0.9"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["q_0.3"], 0.25, places=1) self.assertAlmostEqual(res["q_0.6"], 0.375, places=1) self.assertAlmostEqual(res["q_0.9"], 0.75, places=1) x = [0, 0, 0] param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.isnan(res["q_0.5"])) x = [] param = [{"q": 0.5}] expected_index = ["q_0.5"] res = index_mass_quantile(x, param) res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.isnan(res["q_0.5"])) def test_number_cwt_peaks(self): x = [1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1] self.assertEqualOnAllArrayTypes(number_cwt_peaks, x, 2, 2) def test_spkt_welch_density(self): # todo: improve tests x = range(10) param = [{"coeff": 1}, {"coeff": 10}] expected_index = ["coeff_1", "coeff_10"] res = pd.Series(dict(spkt_welch_density(x, param))) self.assertCountEqual(list(res.index), expected_index) self.assertIsNaN(res["coeff_10"]) def test_cwt_coefficients(self): x = [0.1, 0.2, 0.3] param = [{"widths": (1, 2, 3), "coeff": 2, "w": 1}, {"widths": (1, 3), "coeff": 2, "w": 3}, {"widths": (1, 3), "coeff": 5, "w": 3}] shuffle(param) expected_index = ["coeff_2__w_1__widths_(1, 2, 3)", "coeff_2__w_3__widths_(1, 3)", "coeff_5__w_3__widths_(1, 3)"] res = cwt_coefficients(x, param) res = pd.Series(dict(res)) # todo: add unit test for the values self.assertCountEqual(list(res.index), expected_index) self.assertTrue(math.isnan(res["coeff_5__w_3__widths_(1, 3)"])) def test_ar_coefficient(self): # Test for X_i = 2.5 * X_{i-1} + 1 param = [{"k": 1, "coeff": 0}, {"k": 1, "coeff": 1}] shuffle(param) x = [1] + 9 * [0] for i in range(1, len(x)): x[i] = 2.5 * x[i - 1] + 1 res = ar_coefficient(x, param) expected_index = ["coeff_0__k_1", "coeff_1__k_1"] res = pd.Series(dict(res)) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["coeff_0__k_1"], 1, places=2) self.assertAlmostEqual(res["coeff_1__k_1"], 2.5, places=2) # Test for X_i = 1.4 * X_{i-1} - 1 X_{i-2} + 1 param = [{"k": 1, "coeff": 0}, {"k": 1, "coeff": 1}, {"k": 2, "coeff": 0}, {"k": 2, "coeff": 1}, {"k": 2, "coeff": 2}, {"k": 2, "coeff": 3}] shuffle(param) x = [1, 1] + 5 * [0] for i in range(2, len(x)): x[i] = (-2) * x[i - 2] + 3.5 * x[i - 1] + 1 res = ar_coefficient(x, param) expected_index = ["coeff_0__k_1", "coeff_1__k_1", "coeff_0__k_2", "coeff_1__k_2", "coeff_2__k_2", "coeff_3__k_2"] res = pd.Series(dict(res)) self.assertIsInstance(res, pd.Series) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["coeff_0__k_2"], 1, places=2) self.assertAlmostEqual(res["coeff_1__k_2"], 3.5, places=2) self.assertAlmostEqual(res["coeff_2__k_2"], -2, places=2) self.assertTrue(np.isnan(res["coeff_3__k_2"])) def test_time_reversal_asymmetry_statistic(self): x = [1] * 10 self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 0) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 1) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 3) x = [1, 2, -3, 4] # 1/2 * ( (4^2 * -3 + 3 * 2^2) + (3^2*2)-(2*1^1)) = 1/2 * (-48+12+18-2) = 20/2 self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, -10, 1) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(time_reversal_asymmetry_statistic, x, 0, 3) def test_number_crossing_m(self): x = [10, -10, 10, -10] self.assertEqualOnAllArrayTypes(number_crossing_m, x, 3, 0) self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 10) x = [10, 20, 20, 30] self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 0) self.assertEqualOnAllArrayTypes(number_crossing_m, x, 1, 15) def test_c3(self): x = [1] * 10 self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 0) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 1) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 2) self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 3) x = [1, 2, -3, 4] # 1/2 *(1*2*(-3)+2*(-3)*4) = 1/2 *(-6-24) = -30/2 self.assertAlmostEqualOnAllArrayTypes(c3, x, -15, 1) self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 2) self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 3) def test_binned_entropy(self): self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 100, 0, 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 10) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 10 + [1], - (10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)), 100) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, list(range(10)), - np.math.log(1 / 10), 100) self.assertAlmostEqualOnAllArrayTypes(binned_entropy, list(range(100)), - np.math.log(1 / 2), 2) def test_sample_entropy(self): # "random" list -> large entropy ts = [1, 4, 5, 1, 7, 3, 1, 2, 5, 8, 9, 7, 3, 7, 9, 5, 4, 3, 9, 1, 2, 3, 4, 2, 9, 6, 7, 4, 9, 2, 9, 9, 6, 5, 1, 3, 8, 1, 5, 3, 8, 4, 1, 2, 2, 1, 6, 5, 3, 6, 5, 4, 8, 9, 6, 7, 5, 3, 2, 5, 4, 2, 5, 1, 6, 5, 3, 5, 6, 7, 8, 5, 2, 8, 6, 3, 8, 2, 7, 1, 7, 3, 5, 6, 2, 1, 3, 7, 3, 5, 3, 7, 6, 7, 7, 2, 3, 1, 7, 8] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 2.38262780) # This is not very complex, so it gives a small value ts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.25131442) # however adding a 2 increases complexity ts = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734) # and it does not matter where ts = [1, 1, 1, 2, 1, 1, 1, 1, 1, 1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734) # negative numbers also work ts = [1, -1, 1, -1, 1, -1] self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.69314718) # nan gives nan ts = [1, -1, 1, np.nan, 1, -1] self.assertIsNanOnAllArrayTypes(sample_entropy, ts) # this is not a very "random" list, so it should give a small entropy ts = list(range(1000)) self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.0010314596066622707) def test_autocorrelation(self): self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], -1, 1) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 2) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], -1, 3) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 4) self.assertAlmostEqualOnAllArrayTypes(autocorrelation, pd.Series([0, 1, 2, 0, 1, 2]), -0.75, 2) # Autocorrelation lag is larger than length of the time series self.assertIsNanOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 200) self.assertIsNanOnAllArrayTypes(autocorrelation, [np.nan], 0) self.assertIsNanOnAllArrayTypes(autocorrelation, [], 0) # time series with length 1 has no variance, therefore no result for autocorrelation at lag 0 self.assertIsNanOnAllArrayTypes(autocorrelation, [1], 0) def test_quantile(self): self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 1.0, 0.2) self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 0.9) self.assertAlmostEqualOnAllArrayTypes(quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 1.0) self.assertAlmostEqualOnAllArrayTypes(quantile, [1], 1, 0.5) self.assertIsNanOnAllArrayTypes(quantile, [], 0.5) def test_mean_abs_change_quantiles(self): self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 1, ql=0.1, qh=0.9, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.15, qh=0.18, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=0.6, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 5, ql=0, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0.5, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0, 1, 0], 0.75, ql=0.1, qh=1, isabs=True, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 1, ql=0.1, qh=0.9, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.15, qh=0.18, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0, ql=0.1, qh=0.6, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0], 0.5, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, -9, 0, 0, 1, 0], 0.25, ql=0.1, qh=1, isabs=False, f_agg="mean") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.1, qh=0.9, isabs=True, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, list(range(10)), 0, ql=0.1, qh=0.9, isabs=False, f_agg="std") self.assertAlmostEqualOnAllArrayTypes(change_quantiles, [0, 1, 0, 1, 0], 1, ql=0, qh=1, isabs=False, f_agg="std") def test_value_count(self): self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 10, value=1) self.assertEqualPandasSeriesWrapper(value_count, list(range(10)), 1, value=0) self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 0, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.NaN, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.NINF, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [np.PINF, 0, 1] * 3, 3, value=0) self.assertEqualPandasSeriesWrapper(value_count, [0.1, 0.2, 0.3] * 3, 3, value=0.2) self.assertEqualPandasSeriesWrapper(value_count, [np.NaN, 0, 1] * 3, 3, value=np.NaN) self.assertEqualPandasSeriesWrapper(value_count, [np.NINF, 0, 1] * 3, 3, value=np.NINF) self.assertEqualPandasSeriesWrapper(value_count, [np.PINF, 0, 1] * 3, 3, value=np.PINF) def test_range_count(self): self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=1, max=1) self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=0.9, max=1) self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 10, min=1, max=1.1) self.assertEqualPandasSeriesWrapper(range_count, list(range(10)), 9, min=0, max=9) self.assertEqualPandasSeriesWrapper(range_count, list(range(10)), 10, min=0, max=10) self.assertEqualPandasSeriesWrapper(range_count, list(range(0, -10, -1)), 9, min=-10, max=0) self.assertEqualPandasSeriesWrapper(range_count, [np.NaN, np.PINF, np.NINF] + list(range(10)), 10, min=0, max=10) def test_approximate_entropy(self): self.assertEqualOnAllArrayTypes(approximate_entropy, [1], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5) self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5) self.assertAlmostEqualOnAllArrayTypes(approximate_entropy, [12, 13, 15, 16, 17] * 10, 0.282456191, m=2, r=0.9) self.assertRaises(ValueError, approximate_entropy, x=[12, 13, 15, 16, 17] * 10, m=2, r=-0.5) def test_max_langevin_fixed_point(self): """ Estimating the intrinsic velocity of a dissipative soliton """ default_params = {"m": 3, "r": 30} # active Brownian motion ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(100000, v0=np.zeros(1)) v0 = max_langevin_fixed_point(v[:, 0], **default_params) self.assertLess(abs(ds.deterministic - v0), 0.001) # Brownian motion ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) v0 = max_langevin_fixed_point(v[:, 0], **default_params) self.assertLess(v0, 0.001) def test_linear_trend(self): # check linear up trend x = range(10) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend(x, param) res = pd.Series(dict(res)) expected_index = ["attr_\"pvalue\"", "attr_\"intercept\"", "attr_\"rvalue\"", "attr_\"slope\"", "attr_\"stderr\""] self.assertEqual(len(res), 5) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["attr_\"pvalue\""], 0) self.assertAlmostEqual(res["attr_\"stderr\""], 0) self.assertAlmostEqual(res["attr_\"intercept\""], 0) self.assertAlmostEqual(res["attr_\"slope\""], 1.0) # check p value for random trend np.random.seed(42) x = np.random.uniform(size=100) param = [{"attr": "rvalue"}] res = linear_trend(x, param) res = pd.Series(dict(res)) self.assertLess(abs(res["attr_\"rvalue\""]), 0.1) # check slope and intercept decreasing trend with intercept x = [42 - 2 * x for x in range(10)] param = [{"attr": "intercept"}, {"attr": "slope"}] res = linear_trend(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"intercept\""], 42) self.assertAlmostEqual(res["attr_\"slope\""], -2) def test__aggregate_on_chunks(self): self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="max", chunk_len=2), [1, 3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([1, 1, 3, 3]), f_agg="max", chunk_len=2), [1, 3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="min", chunk_len=2), [0, 2]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3, 5]), f_agg="min", chunk_len=2), [0, 2, 5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="mean", chunk_len=2), [0.5, 2.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=2), [0.5, 2, 5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=3), [1 / 3, 4.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3, 5, -2]), f_agg="median", chunk_len=2), [0.5, 2.5, 1.5]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([-10, 5, 3, -3, 4, -6]), f_agg="median", chunk_len=3), [3, -3]) self.assertListEqual(_aggregate_on_chunks(x=pd.Series([0, 1, 2, np.NaN, 5]), f_agg="median", chunk_len=2), [0.5, 2, 5]) def test_agg_linear_trend(self): x = pd.Series(range(9), index=range(9)) param = [{"attr": "intercept", "chunk_len": 3, "f_agg": "max"}, {"attr": "slope", "chunk_len": 3, "f_agg": "max"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "min"}, {"attr": "slope", "chunk_len": 3, "f_agg": "min"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "mean"}, {"attr": "slope", "chunk_len": 3, "f_agg": "mean"}, {"attr": "intercept", "chunk_len": 3, "f_agg": "median"}, {"attr": "slope", "chunk_len": 3, "f_agg": "median"}] expected_index = ['attr_"intercept"__chunk_len_3__f_agg_"max"', 'attr_"slope"__chunk_len_3__f_agg_"max"', 'attr_"intercept"__chunk_len_3__f_agg_"min"', 'attr_"slope"__chunk_len_3__f_agg_"min"', 'attr_"intercept"__chunk_len_3__f_agg_"mean"', 'attr_"slope"__chunk_len_3__f_agg_"mean"', 'attr_"intercept"__chunk_len_3__f_agg_"median"', 'attr_"slope"__chunk_len_3__f_agg_"median"'] res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertEqual(len(res), 8) self.maxDiff = 2000 self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], 2) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], 0) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], 1) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 3) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], 1) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 3) x = pd.Series([np.NaN, np.NaN, np.NaN, -3, -3, -3]) res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"max"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"max"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"min"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"min"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"mean"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"mean"']) self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"median"']) self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"median"']) x = pd.Series([np.NaN, np.NaN, -3, -3, -3, -3]) res = agg_linear_trend(x=x, param=param) res = pd.Series(dict(res)) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 0) self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], -3) self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 0) def test_energy_ratio_by_chunks(self): x = pd.Series(range(90), index=range(90)) param = [{"num_segments": 6, "segment_focus": i} for i in range(6)] output = energy_ratio_by_chunks(x=x, param=param) self.assertAlmostEqual(output[0][1], 0.0043, places=3) self.assertAlmostEqual(output[1][1], 0.0316, places=3) self.assertAlmostEqual(output[2][1], 0.0871, places=3) self.assertAlmostEqual(output[3][1], 0.1709, places=3) self.assertAlmostEqual(output[4][1], 0.2829, places=3) self.assertAlmostEqual(output[5][1], 0.4232, places=3) # Sum of the ratios should be 1.0 sum = 0.0 for name, dat in output: sum = sum + dat self.assertAlmostEqual(sum, 1.0) x = pd.Series(1, index=range(10)) param = [{"num_segments": 3, "segment_focus": i} for i in range(3)] output = energy_ratio_by_chunks(x=x, param=param) self.assertAlmostEqual(output[0][1], 0.4, places=3) self.assertAlmostEqual(output[1][1], 0.3, places=3) self.assertAlmostEqual(output[2][1], 0.3, places=3) # Sum of the ratios should be 1.0 sum = 0.0 for name, dat in output: sum = sum + dat self.assertAlmostEqual(sum, 1.0) x = pd.Series(0, index=range(10)) param = [{"num_segments": 3, "segment_focus": i} for i in range(3)] output = energy_ratio_by_chunks(x=x, param=param) self.assertIsNaN(output[0][1]) self.assertIsNaN(output[1][1]) self.assertIsNaN(output[2][1]) def test_linear_trend_timewise_hours(self): """Test linear_trend_timewise function with hour intervals.""" x = pd.Series( [0, 1, 3, 6], index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2018-01-01 05:00:00', '2018-01-01 07:00:00', '2018-01-01 10:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) expected_index = ["attr_\"pvalue\"", "attr_\"intercept\"", "attr_\"rvalue\"", "attr_\"slope\"", "attr_\"stderr\""] self.assertEqual(len(res), 5) self.assertCountEqual(list(res.index), expected_index) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_days(self): """Test linear_trend_timewise function with day intervals.""" # Try with different days x = pd.Series( [0, 24, 48, 72], index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2018-01-02 04:00:00', '2018-01-03 04:00:00', '2018-01-04 04:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_seconds(self): """Test linear_trend_timewise function with second intervals.""" # Try with different days x = pd.Series( [0, 1 / float(3600), 2 / float(3600), 3 / float(3600)], index=pd.DatetimeIndex([ '2018-01-01 04:00:01', '2018-01-01 04:00:02', '2018-01-01 04:00:03', '2018-01-01 04:00:04' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_linear_trend_timewise_years(self): """Test linear_trend_timewise function with year intervals.""" # Try with different days x = pd.Series( [0, 365 * 24, 365 * 48, 365 * 72 + 24], # Add 24 to the last one since it's a leap year index=pd.DatetimeIndex([ '2018-01-01 04:00:00', '2019-01-01 04:00:00', '2020-01-01 04:00:00', '2021-01-01 04:00:00' ]), ) param = [{"attr": "pvalue"}, {"attr": "rvalue"}, {"attr": "intercept"}, {"attr": "slope"}, {"attr": "stderr"}] res = linear_trend_timewise(x, param) res = pd.Series(dict(res)) self.assertAlmostEqual(res["attr_\"pvalue\""], 0, places=3) self.assertAlmostEqual(res["attr_\"stderr\""], 0, places=3) self.assertAlmostEqual(res["attr_\"intercept\""], 0, places=3) self.assertAlmostEqual(res["attr_\"slope\""], 1.0, places=3) def test_change_quantiles(self): """Test change_quantiles function when changing from `sum` to `np.sum`.""" np.random.seed(0) res = change_quantiles(np.random.rand(10000) * 1000, 0.1, 0.2, False, 'mean') self.assertAlmostEqual(res, -0.9443846621365727) def test_count_above(self): self.assertEqualPandasSeriesWrapper(count_above, [1] * 10, 1, t=1) self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 1, t=0) self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 0.5, t=5) self.assertEqualPandasSeriesWrapper(count_above, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2) self.assertEqualPandasSeriesWrapper(count_above, [np.NaN, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.NINF, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.PINF, 0, 1] * 3, 1, t=0) self.assertEqualPandasSeriesWrapper(count_above, [np.NaN, 0, 1] * 3, 0, t=np.NaN) self.assertEqualPandasSeriesWrapper(count_above, [np.NINF, 0, np.PINF] * 3, 1, t=np.NINF) self.assertEqualPandasSeriesWrapper(count_above, [np.PINF, 0, 1] * 3, 1 / 3, t=np.PINF) def test_count_below(self): self.assertEqualPandasSeriesWrapper(count_below, [1] * 10, 1, t=1) self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 1 / 10, t=0) self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 6 / 10, t=5) self.assertEqualPandasSeriesWrapper(count_below, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2) self.assertEqualPandasSeriesWrapper(count_below, [np.NaN, 0, 1] * 3, 1 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.NINF, 0, 1] * 3, 2 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.PINF, 0, 1] * 3, 1 / 3, t=0) self.assertEqualPandasSeriesWrapper(count_below, [np.NaN, 0, 1] * 3, 0, t=np.NaN) self.assertEqualPandasSeriesWrapper(count_below, [np.NINF, 0, np.PINF] * 3, 1 / 3, t=np.NINF) self.assertEqualPandasSeriesWrapper(count_below, [np.PINF, 0, 1] * 3, 1, t=np.PINF) def test_benford_correlation(self): # A test with list of random values np.random.seed(42) random_list = np.random.uniform(size=100) # Fibonacci series is known to match the Newcomb-Benford's Distribution fibonacci_list = [0, 1] for i in range(2, 200): fibonacci_list.append(fibonacci_list[i - 1] + fibonacci_list[i - 2]) # A list of equally distributed digits (returns NaN) equal_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] # A list containing NaN list_with_nan = [1.354, 0.058, 0.055, 0.99, 3.15, np.nan, 0.3, 2.3, 0, 0.59, 0.74] self.assertAlmostEqual(benford_correlation(random_list), 0.39458056) self.assertAlmostEqual(benford_correlation(fibonacci_list), 0.998003988) self.assertAlmostEqual(benford_correlation(list_with_nan), 0.10357511) self.assertIsNaN(benford_correlation(equal_list)) class FriedrichTestCase(TestCase): def test_estimate_friedrich_coefficients(self): """ Estimate friedrich coefficients """ default_params = {"m": 3, "r": 30} # active Brownian motion ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params) self.assertLess(abs(coeff[-1]), 0.0001) # Brownian motion ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0) v = ds.simulate(10000, v0=np.zeros(1)) coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params) self.assertLess(abs(coeff[-1]), 0.0001) def test_friedrich_coefficients(self): # Test binning error returns vector of NaNs param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)] x = np.zeros(100) res = pd.Series(dict(friedrich_coefficients(x, param))) expected_index = ["coeff_0__m_2__r_30", "coeff_1__m_2__r_30", "coeff_2__m_2__r_30", "coeff_3__m_2__r_30"] self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.sum(np.isnan(res)), 3) def test_friedrich_number_of_returned_features_is_equal_to_number_of_parameters(self): """ unit test for issue 501 """ param = [{'m': 3, 'r': 5, 'coeff': 2}, {'m': 3, 'r': 5, 'coeff': 3}, {'m': 3, 'r': 2, 'coeff': 3}] x = np.zeros(100) res = pd.Series(dict(friedrich_coefficients(x, param))) expected_index = ["coeff_2__m_3__r_5", "coeff_3__m_3__r_5", "coeff_3__m_3__r_2"] self.assertCountEqual(list(res.index), expected_index) self.assertTrue(np.sum(np.isnan(res)), 3) def test_friedrich_equal_to_snapshot(self): param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)] x = np.array([-0.53, -0.61, -1.26, -0.88, -0.34, 0.58, 2.86, -0.47, 0.78, -0.45, -0.27, 0.43, 1.72, 0.26, 1.02, -0.09, 0.65, 1.49, -0.95, -1.02, -0.64, -1.63, -0.71, -0.43, -1.69, 0.05, 1.58, 1.1, 0.55, -1.02]) res = pd.Series(dict(friedrich_coefficients(x, param))) self.assertAlmostEqual(res['coeff_0__m_2__r_30'], -0.24536975738843042) self.assertAlmostEqual(res['coeff_1__m_2__r_30'], -0.533309548662685) self.assertAlmostEqual(res['coeff_2__m_2__r_30'], 0.2759399238199404)
""" Copyright 2021 Nirlep_5252_ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import discord import traceback import json from discord.ext import commands from utils.embed import ( replace_things_in_string_fancy_lemao, process_embeds_from_json, error_embed ) from config import ( OWNERS, EMOJIS, MAIN_COLOR, SUPPORT_SERVER_LINK, VOTE_LINK, RED_COLOR ) from utils.random import gen_random_string from utils.custom_checks import NotVoted, NotBotMod, OptedOut, PrivateCommand from utils.converters import ImportantCategory, InvalidTimeZone, InvalidCategory from humanfriendly import format_timespan from utils.bot import EpicBot class ErrorHandling(commands.Cog): def __init__(self, client: EpicBot): self.client = client self.cd_mapping = commands.CooldownMapping.from_cooldown(5, 20, commands.BucketType.user) self.nice_spam_idiot = commands.CooldownMapping.from_cooldown(2, 10, commands.BucketType.user) async def process_custom_cmds(self, ctx: commands.Context, cmd_name): interseting_allowed_mentions = discord.AllowedMentions( everyone=False, roles=False, replied_user=False, users=True ) guild_config = await self.client.get_guild_config(ctx.guild.id) if "custom_cmds" not in guild_config: guild_config.update({"custom_cmds": []}) custom_cmds_list = guild_config["custom_cmds"] for e in custom_cmds_list: if e['name'] == cmd_name: if not e['embed']: h = await replace_things_in_string_fancy_lemao(self.client, [ctx.author, ctx.guild], e['reply']) await ctx.send(h, allowed_mentions=interseting_allowed_mentions) else: embed_json = json.loads(e['reply']) thing = await process_embeds_from_json(self.client, [ctx.author, ctx.guild], embed_json) if thing[0] is not None: await ctx.send(thing[0], embed=thing[1]) # use the function from utils.embed else: await ctx.send(embed=thing[1]) return @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error): bucket_pain = self.nice_spam_idiot.get_bucket(ctx.message) retry_after_pain = bucket_pain.update_rate_limit() prefix = ctx.clean_prefix if retry_after_pain: return if isinstance(error, commands.CommandNotFound): bucket = self.cd_mapping.get_bucket(ctx.message) retry_after = bucket.update_rate_limit() if retry_after and ctx.author.id not in OWNERS: return await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Calm down!", f"Please try again after **{format_timespan(round(error.retry_after, 2))}**."), delete_after=5 ) await self.process_custom_cmds(ctx, ctx.invoked_with) elif isinstance(error, commands.CommandOnCooldown): await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Calm down!", f"Please try again after **{format_timespan(round(error.retry_after, 2))}**.".format(error.retry_after)), delete_after=5 ) elif isinstance(error, commands.MaxConcurrencyReached): await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Limit reached!", f"An instance of this command is already running...\nYou can only run `{error.number}` instances at the same time." )) elif isinstance(error, commands.MissingPermissions): if ctx.author.id == 558861606063308822: return await ctx.reinvoke() ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Nah bro!", "You need **{}** perms to run this command.".format(' '.join(error.missing_permissions[0].split('_')).title()) )) elif isinstance(error, commands.BotMissingPermissions): ctx.command.reset_cooldown(ctx) if error.missing_permissions[0] == 'send_messages': return await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Error!", "I am missing **{}** permissions.".format(' '.join(error.missing_permissions[0].split('_')).title()) )) elif isinstance(error, commands.NSFWChannelRequired): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Go away horny!", "This command can only be used in a **NSFW** channel." )) elif isinstance(error, commands.NotOwner): await self.client.get_channel(800252938869669898).send( embed=discord.Embed( title="Someone tried to use Owner only command!", description=f"```{ctx.message.content}```", color=MAIN_COLOR ).add_field(name="User", value=f"{ctx.author.mention}```{ctx.author} ({ctx.author.id})```", inline=False) .add_field(name="Server", value=f"```{ctx.guild} ({ctx.guild.id})```", inline=False) ) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} No!", "Sowwi cutie but you cannot use this command!~" )) elif isinstance(error, commands.MemberNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", "I wasn't able to find **{}**, please try again.".format(error.argument) )) elif isinstance(error, commands.UserNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", "I wasn't able to find **{}**, please try again.".format(error.argument) )) elif isinstance(error, commands.ChannelNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", "No channel named **{}** was found, please try again.".format(error.argument) )) elif isinstance(error, commands.RoleNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", "No role named **{}** was found, please try again.".format(error.argument) )) elif isinstance(error, commands.EmojiNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", f"I wasn't able to find any emoji named: `{error.argument}`." )) elif isinstance(error, commands.PartialEmojiConversionFailure): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Not found!", f"I wasn't able to find any emoji named: `{error.argument}`." )) elif isinstance(error, NotVoted): await ctx.reply(embed=error_embed( f"{EMOJIS["weirdchamp"]} Voter only!", f"This command is restricted to voters only.\nClick **[here]({VOTE_LINK})** to vote!" )) elif isinstance(error, NotBotMod): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} No!", "Only bot moderators can use this command!" )) elif isinstance(error, OptedOut): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} No!", f"You cannot snipe, because you opted out!\nPlease use `{prefix}optout` to be able to snipe again." )) elif isinstance(error, InvalidTimeZone): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Invalid Timezone!", f"Please use a valid timezone.\nClick **[here](https://github.com/nirlep5252/epicbot/tree/main/other/timezones.txt)** to see the list of valid timezones.\n\nYou can also set your timezone using `{ctx.clean_prefix}settimezone <timezone>` for all commands." )) elif isinstance(error, InvalidCategory): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Invalid Category!", f"The category `{error.category}` is not a valid category!\nPlease use `{prefix}help` to see the list of valid categories." )) elif isinstance(error, ImportantCategory): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Important Category!", f"You cannot disable the `{error.category}` category!\nIt has contains the core features of epicbot\nFor more info join our [Support Server]({SUPPORT_SERVER_LINK})." )) elif isinstance(error, PrivateCommand): await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} Private Command!", "This command is private and you cannot use it." )) elif isinstance(error, commands.CheckFailure): ctx.command.reset_cooldown(ctx) if not self.client.beta: await ctx.message.add_reaction('❌') else: random_error_id = gen_random_string(10) ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS["tick_no"]} An unknown error occured!", error ).set_footer(text=f"ERROR ID: {random_error_id}")) error_text = "".join(traceback.format_exception(etype=type(error), value=error, tb=error.__traceback__))[:2000] error_embed_ = discord.Embed( title="Traceback", description=("```py\n" + error_text + "\n```"), color=RED_COLOR ).add_field(name="Command", value=f"```{ctx.message.content}```", inline=False ).add_field(name="User", value=f"{ctx.author.mention} ```{ctx.author} ({ctx.author.id})```", inline=False ).add_field(name="Server", value=f"```{ctx.guild}({ctx.guild.id})```", inline=False ).set_footer(text=f"ERROR ID: {random_error_id}") try: webhooks = self.client.get_cog("Webhooks").webhooks webhook = webhooks.get("cmd_error") await webhook.send(embed=error_embed_) except Exception: traceback.print_exception(etype=type(error), value=error, tb=error.__traceback__) def setup(client): client.add_cog(ErrorHandling(client))
""" Copyright 2021 Nirlep_5252_ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import discord import traceback import json from discord.ext import commands from utils.embed import ( replace_things_in_string_fancy_lemao, process_embeds_from_json, error_embed ) from config import ( OWNERS, EMOJIS, MAIN_COLOR, SUPPORT_SERVER_LINK, VOTE_LINK, RED_COLOR ) from utils.random import gen_random_string from utils.custom_checks import NotVoted, NotBotMod, OptedOut, PrivateCommand from utils.converters import ImportantCategory, InvalidTimeZone, InvalidCategory from humanfriendly import format_timespan from utils.bot import EpicBot class ErrorHandling(commands.Cog): def __init__(self, client: EpicBot): self.client = client self.cd_mapping = commands.CooldownMapping.from_cooldown(5, 20, commands.BucketType.user) self.nice_spam_idiot = commands.CooldownMapping.from_cooldown(2, 10, commands.BucketType.user) async def process_custom_cmds(self, ctx: commands.Context, cmd_name): interseting_allowed_mentions = discord.AllowedMentions( everyone=False, roles=False, replied_user=False, users=True ) guild_config = await self.client.get_guild_config(ctx.guild.id) if "custom_cmds" not in guild_config: guild_config.update({"custom_cmds": []}) custom_cmds_list = guild_config["custom_cmds"] for e in custom_cmds_list: if e['name'] == cmd_name: if not e['embed']: h = await replace_things_in_string_fancy_lemao(self.client, [ctx.author, ctx.guild], e['reply']) await ctx.send(h, allowed_mentions=interseting_allowed_mentions) else: embed_json = json.loads(e['reply']) thing = await process_embeds_from_json(self.client, [ctx.author, ctx.guild], embed_json) if thing[0] is not None: await ctx.send(thing[0], embed=thing[1]) # use the function from utils.embed else: await ctx.send(embed=thing[1]) return @commands.Cog.listener() async def on_command_error(self, ctx: commands.Context, error): bucket_pain = self.nice_spam_idiot.get_bucket(ctx.message) retry_after_pain = bucket_pain.update_rate_limit() prefix = ctx.clean_prefix if retry_after_pain: return if isinstance(error, commands.CommandNotFound): bucket = self.cd_mapping.get_bucket(ctx.message) retry_after = bucket.update_rate_limit() if retry_after and ctx.author.id not in OWNERS: return await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Calm down!", f"Please try again after **{format_timespan(round(error.retry_after, 2))}**."), delete_after=5 ) await self.process_custom_cmds(ctx, ctx.invoked_with) elif isinstance(error, commands.CommandOnCooldown): await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Calm down!", f"Please try again after **{format_timespan(round(error.retry_after, 2))}**.".format(error.retry_after)), delete_after=5 ) elif isinstance(error, commands.MaxConcurrencyReached): await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Limit reached!", f"An instance of this command is already running...\nYou can only run `{error.number}` instances at the same time." )) elif isinstance(error, commands.MissingPermissions): if ctx.author.id == 558861606063308822: return await ctx.reinvoke() ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Nah bro!", "You need **{}** perms to run this command.".format(' '.join(error.missing_permissions[0].split('_')).title()) )) elif isinstance(error, commands.BotMissingPermissions): ctx.command.reset_cooldown(ctx) if error.missing_permissions[0] == 'send_messages': return await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Error!", "I am missing **{}** permissions.".format(' '.join(error.missing_permissions[0].split('_')).title()) )) elif isinstance(error, commands.NSFWChannelRequired): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Go away horny!", "This command can only be used in a **NSFW** channel." )) elif isinstance(error, commands.NotOwner): await self.client.get_channel(800252938869669898).send( embed=discord.Embed( title="Someone tried to use Owner only command!", description=f"```{ctx.message.content}```", color=MAIN_COLOR ).add_field(name="User", value=f"{ctx.author.mention}```{ctx.author} ({ctx.author.id})```", inline=False) .add_field(name="Server", value=f"```{ctx.guild} ({ctx.guild.id})```", inline=False) ) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} No!", "Sowwi cutie but you cannot use this command!~" )) elif isinstance(error, commands.MemberNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", "I wasn't able to find **{}**, please try again.".format(error.argument) )) elif isinstance(error, commands.UserNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", "I wasn't able to find **{}**, please try again.".format(error.argument) )) elif isinstance(error, commands.ChannelNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", "No channel named **{}** was found, please try again.".format(error.argument) )) elif isinstance(error, commands.RoleNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", "No role named **{}** was found, please try again.".format(error.argument) )) elif isinstance(error, commands.EmojiNotFound): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", f"I wasn't able to find any emoji named: `{error.argument}`." )) elif isinstance(error, commands.PartialEmojiConversionFailure): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Not found!", f"I wasn't able to find any emoji named: `{error.argument}`." )) elif isinstance(error, NotVoted): await ctx.reply(embed=error_embed( f"{EMOJIS['weirdchamp']} Voter only!", f"This command is restricted to voters only.\nClick **[here]({VOTE_LINK})** to vote!" )) elif isinstance(error, NotBotMod): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} No!", "Only bot moderators can use this command!" )) elif isinstance(error, OptedOut): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} No!", f"You cannot snipe, because you opted out!\nPlease use `{prefix}optout` to be able to snipe again." )) elif isinstance(error, InvalidTimeZone): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Invalid Timezone!", f"Please use a valid timezone.\nClick **[here](https://github.com/nirlep5252/epicbot/tree/main/other/timezones.txt)** to see the list of valid timezones.\n\nYou can also set your timezone using `{ctx.clean_prefix}settimezone <timezone>` for all commands." )) elif isinstance(error, InvalidCategory): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Invalid Category!", f"The category `{error.category}` is not a valid category!\nPlease use `{prefix}help` to see the list of valid categories." )) elif isinstance(error, ImportantCategory): ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Important Category!", f"You cannot disable the `{error.category}` category!\nIt has contains the core features of epicbot\nFor more info join our [Support Server]({SUPPORT_SERVER_LINK})." )) elif isinstance(error, PrivateCommand): await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} Private Command!", "This command is private and you cannot use it." )) elif isinstance(error, commands.CheckFailure): ctx.command.reset_cooldown(ctx) if not self.client.beta: await ctx.message.add_reaction('❌') else: random_error_id = gen_random_string(10) ctx.command.reset_cooldown(ctx) await ctx.reply(embed=error_embed( f"{EMOJIS['tick_no']} An unknown error occured!", error ).set_footer(text=f"ERROR ID: {random_error_id}")) error_text = "".join(traceback.format_exception(etype=type(error), value=error, tb=error.__traceback__))[:2000] error_embed_ = discord.Embed( title="Traceback", description=("```py\n" + error_text + "\n```"), color=RED_COLOR ).add_field(name="Command", value=f"```{ctx.message.content}```", inline=False ).add_field(name="User", value=f"{ctx.author.mention} ```{ctx.author} ({ctx.author.id})```", inline=False ).add_field(name="Server", value=f"```{ctx.guild}({ctx.guild.id})```", inline=False ).set_footer(text=f"ERROR ID: {random_error_id}") try: webhooks = self.client.get_cog("Webhooks").webhooks webhook = webhooks.get("cmd_error") await webhook.send(embed=error_embed_) except Exception: traceback.print_exception(etype=type(error), value=error, tb=error.__traceback__) def setup(client): client.add_cog(ErrorHandling(client))
r""" From previous experiments, we saw that ephemeral pseudo-labelling helped boost accuracy despite starting with only 20 points. We could kick-start BALD with 85% accuracy with 24 iterations but it seems like using 80% accuracy at 10 iterations is a good trade-off. It's harder to gain more accuracy as the number of iteration increases. This experiment kick-starts BALD10 acquisition by warming the model to 80% accuracy (with 10 iterations of ephemeral pseudo-labelling). However, the acquisition loop will NOT run ephemeral P.L. as we've seen a decrease in performance when doing so. There are two possibilities: (1) warm-starting the model has caused it to lower its entropy on the pool dataset, hence causing it to actually perform worse. (2) warm-starting it actually helped! my bet is (unfortunately) on the former, given previous observations (i.e. ephemeral bald10 performs worse than bald10 -- but i'm hopeful, notwithstanding.). """ from collections import defaultdict from alr.utils import manual_seed, eval_fwd_exp, timeop from alr.acquisition import BALD from alr import MCDropout from alr.data.datasets import Dataset from alr.training.samplers import RandomFixedLengthSampler from alr.data import UnlabelledDataset, DataManager from alr.training import Trainer from alr.training.repeated_acquisition_utils import ( get_confident_indices, RelabelledDataset, ) import torch import torch.utils.data as torchdata import pickle from torch.nn import functional as F from pathlib import Path def main(b, threshold, warm_start_iters, log_every): manual_seed(42) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") kwargs = dict(num_workers=4, pin_memory=True) # --- constants --- BATCH_SIZE = 64 EPOCHS = 200 REPS = 6 ITERS = 23 # +1 because of the structure of our loop warm_start_iters += 1 VAL_SIZE = 5_000 MIN_TRAIN_LEN = 12_500 # --- setup --- train, pool, test = Dataset.MNIST.get_fixed() val, pool = torchdata.random_split(pool, (VAL_SIZE, len(pool) - VAL_SIZE)) pool = UnlabelledDataset(pool, debug=True) model = MCDropout(Dataset.MNIST.model, forward=20, fast=True).to(device) bald = BALD(eval_fwd_exp(model), device=device, batch_size=1024, **kwargs) dm = DataManager(train, pool, bald) val_loader = torchdata.DataLoader( val, batch_size=1024, shuffle=False, **kwargs, ) test_loader = torchdata.DataLoader( test, batch_size=1024, shuffle=False, **kwargs, ) warm_start_accs = [] accs = defaultdict(list) template = f"wsi={warm_start_iters}_b={b}_thresh={threshold}" pl_metrics = Path("pl_metrics") / template metrics = Path("metrics") / template saved_models = Path("saved_models") / template metrics.mkdir(parents=True) saved_models.mkdir(parents=True) for r in range(1, REPS + 1): print(f"- Repeat {r} of {REPS} -") dm.reset() ws_accs_r = {} # store temporarily labelled points (will be union-ed with the training dataset) pseudo_labelled_points = None for i in range(1, warm_start_iters + 1): if pseudo_labelled_points is not None: full_train_dataset = torchdata.ConcatDataset( (dm.labelled, pseudo_labelled_points) ) else: full_train_dataset = dm.labelled train_length = len(full_train_dataset) print( f"=== Warm start iteration {i} of {warm_start_iters} ({i / warm_start_iters:.2%}) ===" ) print( f"\ttrain: {train_length}; " f"pool: {dm.n_unlabelled}; " f"val: {len(val)}; " f"test: {len(test)}" ) model.reset_weights() # -- stage 1: train -- trainer = Trainer( model, F.nll_loss, "Adam", patience=3, reload_best=True, device=device ) train_loader = torchdata.DataLoader( full_train_dataset, batch_size=BATCH_SIZE, sampler=RandomFixedLengthSampler( full_train_dataset, MIN_TRAIN_LEN, shuffle=True ), **kwargs, ) with timeop() as t: history = trainer.fit(train_loader, val_loader, epochs=EPOCHS) test_metrics = trainer.evaluate(test_loader) ws_accs_r[train_length] = test_metrics["acc"] print( f"\t[test] loss, acc: ({test_metrics["loss"]:.4f}, {test_metrics["acc"]:.4f}); time: {t}" ) with open( metrics / f"repeat_{r}_dsize_{train_length}_metrics.pkl", "wb" ) as fp: payload = { "history": history, "test_metrics": test_metrics, } pickle.dump(payload, fp) if (i - 1) % log_every == 0: torch.save( model.state_dict(), saved_models / f"repeat_{r}_dsize_{train_length}_weights.pth", ) # skip if this is the last iteration if i == warm_start_iters: accs[dm.n_labelled].append(test_metrics["acc"]) continue # -- stage 2: acquire more data into the training set -- # -- acquire using pseudo-labels -- dm.unlabelled.debug = True idxs, plabs = get_confident_indices( model=model, dataset=dm.unlabelled, threshold=threshold, root=((pl_metrics / f"repeat_{r}") if r == 1 else None), step=i, device=device, **kwargs, ) if idxs.shape[0]: truth = torchdata.Subset(dm.unlabelled, idxs) # replace true labels with pseudo-labels pseudo_labelled_points = RelabelledDataset(truth, plabs) assert len(pseudo_labelled_points) == idxs.shape[0] else: print( f"\tSelf-labelling didn't happen because none of the pseudo-labels are confident enough." ) warm_start_accs.append(ws_accs_r) dm.unlabelled.debug = False print( f"Warm-started with {warm_start_iters} iterations. Beginning AL acquisitions" ) for i in range(1, ITERS + 1): dm.acquire(b=b) print(f"=== Iteration {i} of {ITERS} ({i / ITERS:.2%}) ===") print( f"\ttrain: {dm.n_labelled}; val: {len(val)}; " f"pool: {dm.n_unlabelled}; test: {len(test)}" ) # model.reset_weights() # leverage p.l. from before, DON'T reset! trainer = Trainer( model, F.nll_loss, optimiser="Adam", patience=3, reload_best=True, device=device, ) train_loader = torchdata.DataLoader( dm.labelled, batch_size=BATCH_SIZE, sampler=RandomFixedLengthSampler( dm.labelled, MIN_TRAIN_LEN, shuffle=True ), **kwargs, ) with timeop() as t: trainer.fit(train_loader, val_loader, epochs=EPOCHS) test_metric = trainer.evaluate(test_loader) print(f"\t[test] acc: {test_metric["acc"]}, time: {t}") accs[dm.n_labelled].append(test_metric["acc"]) with open(f"{template}_warm_start_accs.pkl", "wb") as fp: pickle.dump(warm_start_accs, fp) with open(f"{template}_accs.pkl", "wb") as fp: pickle.dump(accs, fp) if __name__ == "__main__": main(b=10, threshold=0.9, warm_start_iters=10, log_every=2)
r""" From previous experiments, we saw that ephemeral pseudo-labelling helped boost accuracy despite starting with only 20 points. We could kick-start BALD with 85% accuracy with 24 iterations but it seems like using 80% accuracy at 10 iterations is a good trade-off. It's harder to gain more accuracy as the number of iteration increases. This experiment kick-starts BALD10 acquisition by warming the model to 80% accuracy (with 10 iterations of ephemeral pseudo-labelling). However, the acquisition loop will NOT run ephemeral P.L. as we've seen a decrease in performance when doing so. There are two possibilities: (1) warm-starting the model has caused it to lower its entropy on the pool dataset, hence causing it to actually perform worse. (2) warm-starting it actually helped! my bet is (unfortunately) on the former, given previous observations (i.e. ephemeral bald10 performs worse than bald10 -- but i'm hopeful, notwithstanding.). """ from collections import defaultdict from alr.utils import manual_seed, eval_fwd_exp, timeop from alr.acquisition import BALD from alr import MCDropout from alr.data.datasets import Dataset from alr.training.samplers import RandomFixedLengthSampler from alr.data import UnlabelledDataset, DataManager from alr.training import Trainer from alr.training.repeated_acquisition_utils import ( get_confident_indices, RelabelledDataset, ) import torch import torch.utils.data as torchdata import pickle from torch.nn import functional as F from pathlib import Path def main(b, threshold, warm_start_iters, log_every): manual_seed(42) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") kwargs = dict(num_workers=4, pin_memory=True) # --- constants --- BATCH_SIZE = 64 EPOCHS = 200 REPS = 6 ITERS = 23 # +1 because of the structure of our loop warm_start_iters += 1 VAL_SIZE = 5_000 MIN_TRAIN_LEN = 12_500 # --- setup --- train, pool, test = Dataset.MNIST.get_fixed() val, pool = torchdata.random_split(pool, (VAL_SIZE, len(pool) - VAL_SIZE)) pool = UnlabelledDataset(pool, debug=True) model = MCDropout(Dataset.MNIST.model, forward=20, fast=True).to(device) bald = BALD(eval_fwd_exp(model), device=device, batch_size=1024, **kwargs) dm = DataManager(train, pool, bald) val_loader = torchdata.DataLoader( val, batch_size=1024, shuffle=False, **kwargs, ) test_loader = torchdata.DataLoader( test, batch_size=1024, shuffle=False, **kwargs, ) warm_start_accs = [] accs = defaultdict(list) template = f"wsi={warm_start_iters}_b={b}_thresh={threshold}" pl_metrics = Path("pl_metrics") / template metrics = Path("metrics") / template saved_models = Path("saved_models") / template metrics.mkdir(parents=True) saved_models.mkdir(parents=True) for r in range(1, REPS + 1): print(f"- Repeat {r} of {REPS} -") dm.reset() ws_accs_r = {} # store temporarily labelled points (will be union-ed with the training dataset) pseudo_labelled_points = None for i in range(1, warm_start_iters + 1): if pseudo_labelled_points is not None: full_train_dataset = torchdata.ConcatDataset( (dm.labelled, pseudo_labelled_points) ) else: full_train_dataset = dm.labelled train_length = len(full_train_dataset) print( f"=== Warm start iteration {i} of {warm_start_iters} ({i / warm_start_iters:.2%}) ===" ) print( f"\ttrain: {train_length}; " f"pool: {dm.n_unlabelled}; " f"val: {len(val)}; " f"test: {len(test)}" ) model.reset_weights() # -- stage 1: train -- trainer = Trainer( model, F.nll_loss, "Adam", patience=3, reload_best=True, device=device ) train_loader = torchdata.DataLoader( full_train_dataset, batch_size=BATCH_SIZE, sampler=RandomFixedLengthSampler( full_train_dataset, MIN_TRAIN_LEN, shuffle=True ), **kwargs, ) with timeop() as t: history = trainer.fit(train_loader, val_loader, epochs=EPOCHS) test_metrics = trainer.evaluate(test_loader) ws_accs_r[train_length] = test_metrics["acc"] print( f"\t[test] loss, acc: ({test_metrics['loss']:.4f}, {test_metrics['acc']:.4f}); time: {t}" ) with open( metrics / f"repeat_{r}_dsize_{train_length}_metrics.pkl", "wb" ) as fp: payload = { "history": history, "test_metrics": test_metrics, } pickle.dump(payload, fp) if (i - 1) % log_every == 0: torch.save( model.state_dict(), saved_models / f"repeat_{r}_dsize_{train_length}_weights.pth", ) # skip if this is the last iteration if i == warm_start_iters: accs[dm.n_labelled].append(test_metrics["acc"]) continue # -- stage 2: acquire more data into the training set -- # -- acquire using pseudo-labels -- dm.unlabelled.debug = True idxs, plabs = get_confident_indices( model=model, dataset=dm.unlabelled, threshold=threshold, root=((pl_metrics / f"repeat_{r}") if r == 1 else None), step=i, device=device, **kwargs, ) if idxs.shape[0]: truth = torchdata.Subset(dm.unlabelled, idxs) # replace true labels with pseudo-labels pseudo_labelled_points = RelabelledDataset(truth, plabs) assert len(pseudo_labelled_points) == idxs.shape[0] else: print( f"\tSelf-labelling didn't happen because none of the pseudo-labels are confident enough." ) warm_start_accs.append(ws_accs_r) dm.unlabelled.debug = False print( f"Warm-started with {warm_start_iters} iterations. Beginning AL acquisitions" ) for i in range(1, ITERS + 1): dm.acquire(b=b) print(f"=== Iteration {i} of {ITERS} ({i / ITERS:.2%}) ===") print( f"\ttrain: {dm.n_labelled}; val: {len(val)}; " f"pool: {dm.n_unlabelled}; test: {len(test)}" ) # model.reset_weights() # leverage p.l. from before, DON'T reset! trainer = Trainer( model, F.nll_loss, optimiser="Adam", patience=3, reload_best=True, device=device, ) train_loader = torchdata.DataLoader( dm.labelled, batch_size=BATCH_SIZE, sampler=RandomFixedLengthSampler( dm.labelled, MIN_TRAIN_LEN, shuffle=True ), **kwargs, ) with timeop() as t: trainer.fit(train_loader, val_loader, epochs=EPOCHS) test_metric = trainer.evaluate(test_loader) print(f"\t[test] acc: {test_metric['acc']}, time: {t}") accs[dm.n_labelled].append(test_metric["acc"]) with open(f"{template}_warm_start_accs.pkl", "wb") as fp: pickle.dump(warm_start_accs, fp) with open(f"{template}_accs.pkl", "wb") as fp: pickle.dump(accs, fp) if __name__ == "__main__": main(b=10, threshold=0.9, warm_start_iters=10, log_every=2)
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import time from contextlib import contextmanager from threading import Lock from typing import Dict, Tuple from pants.base.exiter import PANTS_FAILED_EXIT_CODE, ExitCode from pants.bin.local_pants_runner import LocalPantsRunner from pants.engine.internals.native import Native, RawFdRunner from pants.init.logging import ( clear_logging_handlers, get_logging_handlers, set_logging_handlers, setup_logging, ) from pants.init.util import clean_global_runtime_state from pants.option.options_bootstrapper import OptionsBootstrapper from pants.pantsd.pants_daemon_core import PantsDaemonCore from pants.util.contextutil import argv_as, hermetic_environment_as, stdio_as logger = logging.getLogger(__name__) class ExclusiveRequestTimeout(Exception): """Represents a timeout while waiting for another request to complete.""" class DaemonPantsRunner(RawFdRunner): """A RawFdRunner (callable) that will be called for each client request to Pantsd.""" def __init__(self, core: PantsDaemonCore) -> None: super().__init__() self._core = core self._run_lock = Lock() @staticmethod def _send_stderr(stderr_fd: int, msg: str) -> None: """Used to send stderr on a raw filehandle _before_ stdio replacement. After stdio replacement has happened via `stdio_as` (which mutates sys.std*, and thus cannot happen until the request lock has been acquired), sys.std* should be used directly. """ with os.fdopen(stderr_fd, mode="w", closefd=False) as stderr: print(msg, file=stderr, flush=True) @contextmanager def _one_run_at_a_time(self, stderr_fd: int, timeout: float): """Acquires exclusive access within the daemon. Periodically prints a message on the given stderr_fd while exclusive access cannot be acquired. """ should_poll_forever = timeout <= 0 start = time.time() deadline = None if should_poll_forever else start + timeout def should_keep_polling(now): return not deadline or deadline > now acquired = self._run_lock.acquire(blocking=False) if not acquired: # If we don't acquire immediately, send an explanation. length = "forever" if should_poll_forever else "up to {} seconds".format(timeout) self._send_stderr( stderr_fd, f"Another pants invocation is running. Will wait {length} for it to finish before giving up.\n" "If you don't want to wait for the first run to finish, please press Ctrl-C and run " "this command with PANTS_CONCURRENT=True in the environment.\n", ) while True: now = time.time() if acquired: try: yield break finally: self._run_lock.release() elif should_keep_polling(now): self._send_stderr( stderr_fd, f"Waiting for invocation to finish (waited for {int(now - start)}s so far)...\n", ) acquired = self._run_lock.acquire(blocking=True, timeout=5) else: raise ExclusiveRequestTimeout( "Timed out while waiting for another pants invocation to finish." ) @contextmanager def _stderr_logging(self, global_bootstrap_options): """Temporarily replaces existing handlers (ie, the pantsd handler) with a stderr handler. In the context of pantsd, there will be an existing handler for the pantsd log, which we temporarily replace. Making them additive would cause per-run logs to go to pantsd, which we don't want. TODO: It would be good to handle logging destinations entirely via the threadlocal state rather than via handler mutations. """ handlers = get_logging_handlers() try: clear_logging_handlers() Native().override_thread_logging_destination_to_just_stderr() setup_logging(global_bootstrap_options, stderr_logging=True) yield finally: Native().override_thread_logging_destination_to_just_pantsd() set_logging_handlers(handlers) def single_daemonized_run(self, working_dir: str) -> ExitCode: """Run a single daemonized run of Pants. All aspects of the `sys` global should already have been replaced in `__call__`, so this method should not need any special handling for the fact that it's running in a proxied environment. """ # Capture the client's start time, which we propagate here in order to get an accurate # view of total time. env_start_time = os.environ.get("PANTSD_RUNTRACKER_CLIENT_START_TIME", None) start_time = float(env_start_time) if env_start_time else time.time() # Clear global mutable state before entering `LocalPantsRunner`. Note that we use # `sys.argv` and `os.environ`, since they have been mutated to maintain the illusion # of a local run: once we allow for concurrent runs, this information should be # propagated down from the caller. # see https://github.com/pantsbuild/pants/issues/7654 clean_global_runtime_state(reset_subsystem=True) options_bootstrapper = OptionsBootstrapper.create( env=os.environ, args=sys.argv, allow_pantsrc=True ) bootstrap_options = options_bootstrapper.bootstrap_options global_bootstrap_options = bootstrap_options.for_global_scope() # Run using the pre-warmed Session. with self._stderr_logging(global_bootstrap_options): try: scheduler = self._core.prepare_scheduler(options_bootstrapper) runner = LocalPantsRunner.create( os.environ, options_bootstrapper, scheduler=scheduler ) return runner.run(start_time) except Exception as e: logger.exception(e) return PANTS_FAILED_EXIT_CODE except KeyboardInterrupt: print("Interrupted by user.\n", file=sys.stderr) return PANTS_FAILED_EXIT_CODE def __call__( self, command: str, args: Tuple[str, ...], env: Dict[str, str], working_directory: bytes, stdin_fd: int, stdout_fd: int, stderr_fd: int, ) -> ExitCode: request_timeout = float(env.get("PANTSD_REQUEST_TIMEOUT_LIMIT", -1)) # NB: Order matters: we acquire a lock before mutating either `sys.std*`, `os.environ`, etc. with self._one_run_at_a_time(stderr_fd, timeout=request_timeout), stdio_as( stdin_fd=stdin_fd, stdout_fd=stdout_fd, stderr_fd=stderr_fd ), hermetic_environment_as(**env), argv_as((command,) + args): # NB: Run implements exception handling, so only the most primitive errors will escape # this function, where they will be logged to the pantsd.log by the server. logger.info(f"handling request: `{" ".join(args)}`") try: return self.single_daemonized_run(working_directory.decode()) finally: logger.info(f"request completed: `{" ".join(args)}`")
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import logging import os import sys import time from contextlib import contextmanager from threading import Lock from typing import Dict, Tuple from pants.base.exiter import PANTS_FAILED_EXIT_CODE, ExitCode from pants.bin.local_pants_runner import LocalPantsRunner from pants.engine.internals.native import Native, RawFdRunner from pants.init.logging import ( clear_logging_handlers, get_logging_handlers, set_logging_handlers, setup_logging, ) from pants.init.util import clean_global_runtime_state from pants.option.options_bootstrapper import OptionsBootstrapper from pants.pantsd.pants_daemon_core import PantsDaemonCore from pants.util.contextutil import argv_as, hermetic_environment_as, stdio_as logger = logging.getLogger(__name__) class ExclusiveRequestTimeout(Exception): """Represents a timeout while waiting for another request to complete.""" class DaemonPantsRunner(RawFdRunner): """A RawFdRunner (callable) that will be called for each client request to Pantsd.""" def __init__(self, core: PantsDaemonCore) -> None: super().__init__() self._core = core self._run_lock = Lock() @staticmethod def _send_stderr(stderr_fd: int, msg: str) -> None: """Used to send stderr on a raw filehandle _before_ stdio replacement. After stdio replacement has happened via `stdio_as` (which mutates sys.std*, and thus cannot happen until the request lock has been acquired), sys.std* should be used directly. """ with os.fdopen(stderr_fd, mode="w", closefd=False) as stderr: print(msg, file=stderr, flush=True) @contextmanager def _one_run_at_a_time(self, stderr_fd: int, timeout: float): """Acquires exclusive access within the daemon. Periodically prints a message on the given stderr_fd while exclusive access cannot be acquired. """ should_poll_forever = timeout <= 0 start = time.time() deadline = None if should_poll_forever else start + timeout def should_keep_polling(now): return not deadline or deadline > now acquired = self._run_lock.acquire(blocking=False) if not acquired: # If we don't acquire immediately, send an explanation. length = "forever" if should_poll_forever else "up to {} seconds".format(timeout) self._send_stderr( stderr_fd, f"Another pants invocation is running. Will wait {length} for it to finish before giving up.\n" "If you don't want to wait for the first run to finish, please press Ctrl-C and run " "this command with PANTS_CONCURRENT=True in the environment.\n", ) while True: now = time.time() if acquired: try: yield break finally: self._run_lock.release() elif should_keep_polling(now): self._send_stderr( stderr_fd, f"Waiting for invocation to finish (waited for {int(now - start)}s so far)...\n", ) acquired = self._run_lock.acquire(blocking=True, timeout=5) else: raise ExclusiveRequestTimeout( "Timed out while waiting for another pants invocation to finish." ) @contextmanager def _stderr_logging(self, global_bootstrap_options): """Temporarily replaces existing handlers (ie, the pantsd handler) with a stderr handler. In the context of pantsd, there will be an existing handler for the pantsd log, which we temporarily replace. Making them additive would cause per-run logs to go to pantsd, which we don't want. TODO: It would be good to handle logging destinations entirely via the threadlocal state rather than via handler mutations. """ handlers = get_logging_handlers() try: clear_logging_handlers() Native().override_thread_logging_destination_to_just_stderr() setup_logging(global_bootstrap_options, stderr_logging=True) yield finally: Native().override_thread_logging_destination_to_just_pantsd() set_logging_handlers(handlers) def single_daemonized_run(self, working_dir: str) -> ExitCode: """Run a single daemonized run of Pants. All aspects of the `sys` global should already have been replaced in `__call__`, so this method should not need any special handling for the fact that it's running in a proxied environment. """ # Capture the client's start time, which we propagate here in order to get an accurate # view of total time. env_start_time = os.environ.get("PANTSD_RUNTRACKER_CLIENT_START_TIME", None) start_time = float(env_start_time) if env_start_time else time.time() # Clear global mutable state before entering `LocalPantsRunner`. Note that we use # `sys.argv` and `os.environ`, since they have been mutated to maintain the illusion # of a local run: once we allow for concurrent runs, this information should be # propagated down from the caller. # see https://github.com/pantsbuild/pants/issues/7654 clean_global_runtime_state(reset_subsystem=True) options_bootstrapper = OptionsBootstrapper.create( env=os.environ, args=sys.argv, allow_pantsrc=True ) bootstrap_options = options_bootstrapper.bootstrap_options global_bootstrap_options = bootstrap_options.for_global_scope() # Run using the pre-warmed Session. with self._stderr_logging(global_bootstrap_options): try: scheduler = self._core.prepare_scheduler(options_bootstrapper) runner = LocalPantsRunner.create( os.environ, options_bootstrapper, scheduler=scheduler ) return runner.run(start_time) except Exception as e: logger.exception(e) return PANTS_FAILED_EXIT_CODE except KeyboardInterrupt: print("Interrupted by user.\n", file=sys.stderr) return PANTS_FAILED_EXIT_CODE def __call__( self, command: str, args: Tuple[str, ...], env: Dict[str, str], working_directory: bytes, stdin_fd: int, stdout_fd: int, stderr_fd: int, ) -> ExitCode: request_timeout = float(env.get("PANTSD_REQUEST_TIMEOUT_LIMIT", -1)) # NB: Order matters: we acquire a lock before mutating either `sys.std*`, `os.environ`, etc. with self._one_run_at_a_time(stderr_fd, timeout=request_timeout), stdio_as( stdin_fd=stdin_fd, stdout_fd=stdout_fd, stderr_fd=stderr_fd ), hermetic_environment_as(**env), argv_as((command,) + args): # NB: Run implements exception handling, so only the most primitive errors will escape # this function, where they will be logged to the pantsd.log by the server. logger.info(f"handling request: `{' '.join(args)}`") try: return self.single_daemonized_run(working_directory.decode()) finally: logger.info(f"request completed: `{' '.join(args)}`")
from snappy import ProductIO, HashMap, GPF import os def apply_orbit_file(product): parameters = HashMap() parameters.put("Apply-Orbit-File", True) operator_name = "Apply-Orbit-File" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def thermal_noise_removal(product, remove_thermal_noise=True): parameters = HashMap() parameters.put("removeThermalNoise", remove_thermal_noise) operator_name = "ThermalNoiseRemoval" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def border_noise_remove(product, border_margin_limit=500, thresold=0.5): parameters = HashMap() parameters.put("borderMarginLimit", border_margin_limit) parameters.put("Threshold", thresold) operator_name = "Remove-GRD-Border-Noise" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def calibration(product, output_type="sigma0", polarization="both"): """ Passes the snap product from border_noise_removal and calibrates it to either sigma0, beta0 or gamma0 depending on the users selection. :param product: The product from ProductIO. :param output_type: The type of calibration to undertake, choose from ["sigma0", "beta0", "gamma0"]. :param polarization: The polarization of the images being passed to calibration. Choose from: ["both", "vv", "vh"]. :return: The calibrated product. """ parameters = HashMap() polarization = polarization.lower() output_type = output_type.lower() if polarization not in ["both", "vv", "vh"]: raise ValueError("The polarization chosen is not supported, choose from 'both', 'vv' or 'vh'") if output_type not in ["sigma0", "beta0", "gamma0"]: raise ValueError("The output type chosen isn't possible, choose from 'sigma0', 'beta0' or 'gamma0'") # Choose calibration to undertake. if output_type == "sigma0": parameters.put("outputSigmaBand", True) elif output_type == "gamma0": parameters.put("outputGammaBand", True) else: parameters.put("outputBetaBand", True) # Choose polarizations to use. if polarization == "both": parameters.put("sourceBands", "Intensity_VH,Intensity_VV") elif polarization == "vh": parameters.put("sourceBands", "Intensity_VH") elif polarization == "vv": parameters.put("sourceBands", "Intensity_VV") operator_name = "Calibration" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def terrain_correction(product): parameters = HashMap() parameters.put("demName", "ACE30") parameters.put("imgResamplingMethod", "BICUBIC_INTERPOLATION") parameters.put("saveProjectedLocalIncidenceAngle", True) parameters.put('saveSelectedSourceBand', True) operator_name = "Terrain-Correction" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def speckle_filtering(product, filter_type="lee", filter_size=5): """ Attempts to filter the speckle from the image, without too much loss of edges. :param product: The input product processed to calibration or terrain correction level. :param filter_type: Choose from lee, lee_sigma, refined_lee, median and cnn. It should be noted that cnn is a tool external from the SNAP toolbox and therefore if CNN is chosen here, we move into numpy arrays. :param filter_size: An odd number is required, the base size is 5 but it's recommended to change this for some settings. :return: """ if filter_size % 2 == 0: raise ValueError("The filter size must be an odd value.") if filter_type not in ["lee", "lee_sigma", "refined_lee", "median", "cnn"]: raise ValueError("The filter type chosen is not valid in this pipeline, choose from 'lee', 'lee_sigma'," " 'refine_lee', 'median', 'cnn'") parameters = HashMap() parameters.put("filterSizeX", filter_size) parameters.put("filterSizeY", filter_size) # Apply the chosen filter. if filter_type == "lee": parameters.put("filter", "Lee") elif filter_type == "lee_sigma": parameters.put("filter", "LeeSigma") elif filter_type == "refine_lee": parameters.put("filter", "RefineLee") elif filter_type == "median": parameters.put("filter", "Median") else: print("This is not ready yet.") operator_name = "Speckle-Filter" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def run_sar_pipeline(path_to_product: str, out_path: str, filter_image=False, remove_thermal=True, border_margin_limit=500, threshold=0.5, output_type="sigma0", polarization="both", filter_type="lee", filter_size=5): """ Runs the sar pipeline to process a single input. :param path_to_product: :param out_path: :param filter_image: :param remove_thermal: :param border_margin_limit: :param threshold: :param output_type: :param polarization: :param filter_type: :param filter_size: :return: """ # Load s1_img = ProductIO.readProduct(path_to_product) # Process the image. # Apply orbit file. s1_img = apply_orbit_file(s1_img) # Remove thermal noise. s1_img = thermal_noise_removal(s1_img, remove_thermal) # Remove border noise. s1_img = border_noise_remove(s1_img, border_margin_limit, threshold) # Calibrate. s1_img = calibration(s1_img, output_type, polarization) # Terrain correction. s1_img = terrain_correction(s1_img) # Filtering. if filter_image: speckle_filtering(s1_img, filter_type, filter_size) # Write the imagery. ProductIO.writeProduct(s1_img, out_path, "BEAM-DIMAP") run_sar_pipeline("D:/sar/s1_denmark/S1B_IW_GRDH_1SDV_20190305T053954_20190305T054019_015215_01C76B_406C.SAFE", "D:/sar/20190305T053954.dim") if __name__ == '__main__': for product in os.listdir("D:/sar/s1_denmark"): out_name = f"{out_name.split("_")[4]}.dim" out_path = f"D:/sar/s1_denmark_processed/{out_name}" run_sar_pipeline(f"D:/sar/s1_denmark/{product}", out_path)
from snappy import ProductIO, HashMap, GPF import os def apply_orbit_file(product): parameters = HashMap() parameters.put("Apply-Orbit-File", True) operator_name = "Apply-Orbit-File" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def thermal_noise_removal(product, remove_thermal_noise=True): parameters = HashMap() parameters.put("removeThermalNoise", remove_thermal_noise) operator_name = "ThermalNoiseRemoval" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def border_noise_remove(product, border_margin_limit=500, thresold=0.5): parameters = HashMap() parameters.put("borderMarginLimit", border_margin_limit) parameters.put("Threshold", thresold) operator_name = "Remove-GRD-Border-Noise" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def calibration(product, output_type="sigma0", polarization="both"): """ Passes the snap product from border_noise_removal and calibrates it to either sigma0, beta0 or gamma0 depending on the users selection. :param product: The product from ProductIO. :param output_type: The type of calibration to undertake, choose from ["sigma0", "beta0", "gamma0"]. :param polarization: The polarization of the images being passed to calibration. Choose from: ["both", "vv", "vh"]. :return: The calibrated product. """ parameters = HashMap() polarization = polarization.lower() output_type = output_type.lower() if polarization not in ["both", "vv", "vh"]: raise ValueError("The polarization chosen is not supported, choose from 'both', 'vv' or 'vh'") if output_type not in ["sigma0", "beta0", "gamma0"]: raise ValueError("The output type chosen isn't possible, choose from 'sigma0', 'beta0' or 'gamma0'") # Choose calibration to undertake. if output_type == "sigma0": parameters.put("outputSigmaBand", True) elif output_type == "gamma0": parameters.put("outputGammaBand", True) else: parameters.put("outputBetaBand", True) # Choose polarizations to use. if polarization == "both": parameters.put("sourceBands", "Intensity_VH,Intensity_VV") elif polarization == "vh": parameters.put("sourceBands", "Intensity_VH") elif polarization == "vv": parameters.put("sourceBands", "Intensity_VV") operator_name = "Calibration" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def terrain_correction(product): parameters = HashMap() parameters.put("demName", "ACE30") parameters.put("imgResamplingMethod", "BICUBIC_INTERPOLATION") parameters.put("saveProjectedLocalIncidenceAngle", True) parameters.put('saveSelectedSourceBand', True) operator_name = "Terrain-Correction" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def speckle_filtering(product, filter_type="lee", filter_size=5): """ Attempts to filter the speckle from the image, without too much loss of edges. :param product: The input product processed to calibration or terrain correction level. :param filter_type: Choose from lee, lee_sigma, refined_lee, median and cnn. It should be noted that cnn is a tool external from the SNAP toolbox and therefore if CNN is chosen here, we move into numpy arrays. :param filter_size: An odd number is required, the base size is 5 but it's recommended to change this for some settings. :return: """ if filter_size % 2 == 0: raise ValueError("The filter size must be an odd value.") if filter_type not in ["lee", "lee_sigma", "refined_lee", "median", "cnn"]: raise ValueError("The filter type chosen is not valid in this pipeline, choose from 'lee', 'lee_sigma'," " 'refine_lee', 'median', 'cnn'") parameters = HashMap() parameters.put("filterSizeX", filter_size) parameters.put("filterSizeY", filter_size) # Apply the chosen filter. if filter_type == "lee": parameters.put("filter", "Lee") elif filter_type == "lee_sigma": parameters.put("filter", "LeeSigma") elif filter_type == "refine_lee": parameters.put("filter", "RefineLee") elif filter_type == "median": parameters.put("filter", "Median") else: print("This is not ready yet.") operator_name = "Speckle-Filter" target_product = GPF.createProduct(operator_name, parameters, product) return target_product def run_sar_pipeline(path_to_product: str, out_path: str, filter_image=False, remove_thermal=True, border_margin_limit=500, threshold=0.5, output_type="sigma0", polarization="both", filter_type="lee", filter_size=5): """ Runs the sar pipeline to process a single input. :param path_to_product: :param out_path: :param filter_image: :param remove_thermal: :param border_margin_limit: :param threshold: :param output_type: :param polarization: :param filter_type: :param filter_size: :return: """ # Load s1_img = ProductIO.readProduct(path_to_product) # Process the image. # Apply orbit file. s1_img = apply_orbit_file(s1_img) # Remove thermal noise. s1_img = thermal_noise_removal(s1_img, remove_thermal) # Remove border noise. s1_img = border_noise_remove(s1_img, border_margin_limit, threshold) # Calibrate. s1_img = calibration(s1_img, output_type, polarization) # Terrain correction. s1_img = terrain_correction(s1_img) # Filtering. if filter_image: speckle_filtering(s1_img, filter_type, filter_size) # Write the imagery. ProductIO.writeProduct(s1_img, out_path, "BEAM-DIMAP") run_sar_pipeline("D:/sar/s1_denmark/S1B_IW_GRDH_1SDV_20190305T053954_20190305T054019_015215_01C76B_406C.SAFE", "D:/sar/20190305T053954.dim") if __name__ == '__main__': for product in os.listdir("D:/sar/s1_denmark"): out_name = f"{out_name.split('_')[4]}.dim" out_path = f"D:/sar/s1_denmark_processed/{out_name}" run_sar_pipeline(f"D:/sar/s1_denmark/{product}", out_path)
# -*- coding: utf-8 -*- # author: https://github.com/Zfour import json import yaml from bs4 import BeautifulSoup from request_data import request data_pool = [] def load_config(): f = open('_config.yml', 'r', encoding='utf-8') ystr = f.read() ymllist = yaml.load(ystr, Loader=yaml.FullLoader) return ymllist def github_issuse(): print('\n') print('------- github issues start ----------') baselink = 'https://github.com/' config = load_config() try: for number in range(1, 100): print(number) if config['issues']['label']: label_plus = '+label%3A' + config['issues']['label'] else: label_plus = '' github = request.get_data( f"https://github.com/{config["issues"]["repo"]}/issues?q=is%3A{config["issues"]["state"]}{str(label_plus)}&page={str(number)}") soup = BeautifulSoup(github, 'html.parser') main_content = soup.find_all('div', {'aria-label': 'Issues'}) linklist = main_content[0].find_all('a', {'class': 'Link--primary'}) if len(linklist) == 0: print('> end') break for item in linklist: issueslink = baselink + item['href'] issues_page = request.get_data(issueslink) issues_soup = BeautifulSoup(issues_page, 'html.parser') try: issues_linklist = issues_soup.find_all('pre') source = issues_linklist[0].text if "{" in source: source = json.loads(source) print(source) data_pool.append(source) except: continue except: print('> end') print('------- github issues end ----------') print('\n') # 友链规则 github_issuse() filename = 'generator/output/v1/data.json' with open(filename, 'w', encoding='utf-8') as file_obj: json.dump(data_pool, file_obj, ensure_ascii=False)
# -*- coding: utf-8 -*- # author: https://github.com/Zfour import json import yaml from bs4 import BeautifulSoup from request_data import request data_pool = [] def load_config(): f = open('_config.yml', 'r', encoding='utf-8') ystr = f.read() ymllist = yaml.load(ystr, Loader=yaml.FullLoader) return ymllist def github_issuse(): print('\n') print('------- github issues start ----------') baselink = 'https://github.com/' config = load_config() try: for number in range(1, 100): print(number) if config['issues']['label']: label_plus = '+label%3A' + config['issues']['label'] else: label_plus = '' github = request.get_data( f"https://github.com/{config['issues']['repo']}/issues?q=is%3A{config['issues']['state']}{str(label_plus)}&page={str(number)}") soup = BeautifulSoup(github, 'html.parser') main_content = soup.find_all('div', {'aria-label': 'Issues'}) linklist = main_content[0].find_all('a', {'class': 'Link--primary'}) if len(linklist) == 0: print('> end') break for item in linklist: issueslink = baselink + item['href'] issues_page = request.get_data(issueslink) issues_soup = BeautifulSoup(issues_page, 'html.parser') try: issues_linklist = issues_soup.find_all('pre') source = issues_linklist[0].text if "{" in source: source = json.loads(source) print(source) data_pool.append(source) except: continue except: print('> end') print('------- github issues end ----------') print('\n') # 友链规则 github_issuse() filename = 'generator/output/v1/data.json' with open(filename, 'w', encoding='utf-8') as file_obj: json.dump(data_pool, file_obj, ensure_ascii=False)
#!/usr/bin/env python import logging import numpy as np import time from flask import Flask, request, jsonify from os import getenv import sentry_sdk sentry_sdk.init(getenv("SENTRY_DSN")) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) @app.route("/respond", methods=["POST"]) def respond(): st_time = time.time() dialogs = request.json["dialogs"] response_candidates = [dialog["utterances"][-1]["hypotheses"] for dialog in dialogs] logger.error(dialogs) logger.error(response_candidates) selected_skill_names = [] selected_responses = [] selected_confidences = [] selected_human_attributes = [] selected_bot_attributes = [] for i, dialog in enumerate(dialogs): confidences = [] responses = [] skill_names = [] human_attributes = [] bot_attributes = [] for skill_data in response_candidates[i]: if skill_data["text"] and skill_data["confidence"]: logger.info(f"Skill {skill_data["skill_name"]} returned non-empty hypothesis with non-zero confidence.") confidences += [skill_data["confidence"]] responses += [skill_data["text"]] skill_names += [skill_data["skill_name"]] human_attributes += [skill_data.get("human_attributes", {})] bot_attributes += [skill_data.get("bot_attributes", {})] if skill_data["skill_name"] == "dff_bot_persona_2_skill" and skill_data["confidence"] == 1.0: confidences[-1] = 100.0 logger.info("DFF Persona was superpowered!") logger.error(confidences) best_id = np.argmax(confidences) selected_skill_names.append(skill_names[best_id]) selected_responses.append(responses[best_id]) selected_confidences.append(confidences[best_id]) selected_human_attributes.append(human_attributes[best_id]) selected_bot_attributes.append(bot_attributes[best_id]) total_time = time.time() - st_time logger.info(f"rule_based_response_selector exec time = {total_time:.3f}s") return jsonify(list(zip(selected_skill_names, selected_responses, selected_confidences, selected_human_attributes, selected_bot_attributes))) if __name__ == "__main__": app.run(debug=False, host="0.0.0.0", port=3003)
#!/usr/bin/env python import logging import numpy as np import time from flask import Flask, request, jsonify from os import getenv import sentry_sdk sentry_sdk.init(getenv("SENTRY_DSN")) logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) app = Flask(__name__) @app.route("/respond", methods=["POST"]) def respond(): st_time = time.time() dialogs = request.json["dialogs"] response_candidates = [dialog["utterances"][-1]["hypotheses"] for dialog in dialogs] logger.error(dialogs) logger.error(response_candidates) selected_skill_names = [] selected_responses = [] selected_confidences = [] selected_human_attributes = [] selected_bot_attributes = [] for i, dialog in enumerate(dialogs): confidences = [] responses = [] skill_names = [] human_attributes = [] bot_attributes = [] for skill_data in response_candidates[i]: if skill_data["text"] and skill_data["confidence"]: logger.info(f"Skill {skill_data['skill_name']} returned non-empty hypothesis with non-zero confidence.") confidences += [skill_data["confidence"]] responses += [skill_data["text"]] skill_names += [skill_data["skill_name"]] human_attributes += [skill_data.get("human_attributes", {})] bot_attributes += [skill_data.get("bot_attributes", {})] if skill_data["skill_name"] == "dff_bot_persona_2_skill" and skill_data["confidence"] == 1.0: confidences[-1] = 100.0 logger.info("DFF Persona was superpowered!") logger.error(confidences) best_id = np.argmax(confidences) selected_skill_names.append(skill_names[best_id]) selected_responses.append(responses[best_id]) selected_confidences.append(confidences[best_id]) selected_human_attributes.append(human_attributes[best_id]) selected_bot_attributes.append(bot_attributes[best_id]) total_time = time.time() - st_time logger.info(f"rule_based_response_selector exec time = {total_time:.3f}s") return jsonify(list(zip(selected_skill_names, selected_responses, selected_confidences, selected_human_attributes, selected_bot_attributes))) if __name__ == "__main__": app.run(debug=False, host="0.0.0.0", port=3003)
#!/usr/bin/env python import argparse import logging import os import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import gevent from gevent.lock import Semaphore from typing_extensions import Literal from rotkehlchen.accounting.accountant import Accountant from rotkehlchen.assets.asset import Asset, EthereumToken from rotkehlchen.assets.resolver import AssetResolver from rotkehlchen.balances.manual import account_for_manually_tracked_balances from rotkehlchen.chain.ethereum.manager import EthereumManager from rotkehlchen.chain.manager import BlockchainBalancesUpdate, ChainManager from rotkehlchen.config import default_data_directory from rotkehlchen.constants.assets import A_USD from rotkehlchen.data.importer import DataImporter from rotkehlchen.data_handler import DataHandler from rotkehlchen.db.settings import DBSettings, ModifiableDBSettings from rotkehlchen.errors import ( EthSyncError, InputError, PremiumAuthenticationError, RemoteError, SystemPermissionError, ) from rotkehlchen.exchanges.manager import ExchangeManager from rotkehlchen.externalapis.alethio import Alethio from rotkehlchen.externalapis.cryptocompare import Cryptocompare from rotkehlchen.externalapis.etherscan import Etherscan from rotkehlchen.fval import FVal from rotkehlchen.greenlets import GreenletManager from rotkehlchen.history import PriceHistorian, TradesHistorian from rotkehlchen.inquirer import Inquirer from rotkehlchen.logging import DEFAULT_ANONYMIZED_LOGS, LoggingSettings, RotkehlchenLogsAdapter from rotkehlchen.premium.premium import Premium, PremiumCredentials, premium_create_and_verify from rotkehlchen.premium.sync import PremiumSyncManager from rotkehlchen.transactions import EthereumAnalyzer from rotkehlchen.typing import ( ApiKey, ApiSecret, BlockchainAccountData, ListOfBlockchainAddresses, SupportedBlockchain, Timestamp, ) from rotkehlchen.usage_analytics import maybe_submit_usage_analytics from rotkehlchen.user_messages import MessagesAggregator from rotkehlchen.utils.misc import combine_stat_dicts, dict_get_sumof, merge_dicts logger = logging.getLogger(__name__) log = RotkehlchenLogsAdapter(logger) MAIN_LOOP_SECS_DELAY = 15 class Rotkehlchen(): def __init__(self, args: argparse.Namespace) -> None: """Initialize the Rotkehlchen object May Raise: - SystemPermissionError if the given data directory's permissions are not correct. """ self.lock = Semaphore() self.lock.acquire() # Can also be None after unlock if premium credentials did not # authenticate or premium server temporarily offline self.premium: Optional[Premium] = None self.user_is_logged_in = False logfilename = None if args.logtarget == 'file': logfilename = args.logfile if args.loglevel == 'debug': loglevel = logging.DEBUG elif args.loglevel == 'info': loglevel = logging.INFO elif args.loglevel == 'warn': loglevel = logging.WARN elif args.loglevel == 'error': loglevel = logging.ERROR elif args.loglevel == 'critical': loglevel = logging.CRITICAL else: raise AssertionError('Should never get here. Illegal log value') logging.basicConfig( filename=logfilename, filemode='w', level=loglevel, format='%(asctime)s -- %(levelname)s:%(name)s:%(message)s', datefmt='%d/%m/%Y %H:%M:%S %Z', ) if not args.logfromothermodules: logging.getLogger('urllib3').setLevel(logging.CRITICAL) logging.getLogger('urllib3.connectionpool').setLevel(logging.CRITICAL) self.sleep_secs = args.sleep_secs if args.data_dir is None: self.data_dir = default_data_directory() else: self.data_dir = Path(args.data_dir) if not os.access(self.data_dir, os.W_OK | os.R_OK): raise SystemPermissionError( f'The given data directory {self.data_dir} is not readable or writable', ) self.args = args self.msg_aggregator = MessagesAggregator() self.greenlet_manager = GreenletManager(msg_aggregator=self.msg_aggregator) self.exchange_manager = ExchangeManager(msg_aggregator=self.msg_aggregator) self.all_eth_tokens = AssetResolver().get_all_eth_tokens() self.data = DataHandler(self.data_dir, self.msg_aggregator) self.cryptocompare = Cryptocompare(data_directory=self.data_dir, database=None) # Initialize the Inquirer singleton Inquirer(data_dir=self.data_dir, cryptocompare=self.cryptocompare) self.lock.release() self.shutdown_event = gevent.event.Event() def reset_after_failed_account_creation_or_login(self) -> None: """If the account creation or login failed make sure that the Rotki instance is clear Tricky instances are when after either failed premium credentials or user refusal to sync premium databases we relogged in. """ self.cryptocompare.db = None def unlock_user( self, user: str, password: str, create_new: bool, sync_approval: Literal['yes', 'no', 'unknown'], premium_credentials: Optional[PremiumCredentials], initial_settings: Optional[ModifiableDBSettings] = None, ) -> None: """Unlocks an existing user or creates a new one if `create_new` is True May raise: - PremiumAuthenticationError if the password can't unlock the database. - AuthenticationError if premium_credentials are given and are invalid or can't authenticate with the server - DBUpgradeError if the rotki DB version is newer than the software or there is a DB upgrade and there is an error. - SystemPermissionError if the directory or DB file can not be accessed """ log.info( 'Unlocking user', user=user, create_new=create_new, sync_approval=sync_approval, initial_settings=initial_settings, ) # unlock or create the DB self.password = password self.user_directory = self.data.unlock(user, password, create_new, initial_settings) self.data_importer = DataImporter(db=self.data.db) self.last_data_upload_ts = self.data.db.get_last_data_upload_ts() self.premium_sync_manager = PremiumSyncManager(data=self.data, password=password) # set the DB in the external services instances that need it self.cryptocompare.set_database(self.data.db) # Anything that was set above here has to be cleaned in case of failure in the next step # by reset_after_failed_account_creation_or_login() try: self.premium = self.premium_sync_manager.try_premium_at_start( given_premium_credentials=premium_credentials, username=user, create_new=create_new, sync_approval=sync_approval, ) except PremiumAuthenticationError: # Reraise it only if this is during the creation of a new account where # the premium credentials were given by the user if create_new: raise # else let's just continue. User signed in succesfully, but he just # has unauthenticable/invalid premium credentials remaining in his DB settings = self.get_settings() maybe_submit_usage_analytics(settings.submit_usage_analytics) self.etherscan = Etherscan(database=self.data.db, msg_aggregator=self.msg_aggregator) alethio = Alethio( database=self.data.db, msg_aggregator=self.msg_aggregator, all_eth_tokens=self.all_eth_tokens, ) historical_data_start = settings.historical_data_start eth_rpc_endpoint = settings.eth_rpc_endpoint # Initialize the price historian singleton PriceHistorian( data_directory=self.data_dir, history_date_start=historical_data_start, cryptocompare=self.cryptocompare, ) self.accountant = Accountant( db=self.data.db, user_directory=self.user_directory, msg_aggregator=self.msg_aggregator, create_csv=True, ) # Initialize the rotkehlchen logger LoggingSettings(anonymized_logs=settings.anonymized_logs) exchange_credentials = self.data.db.get_exchange_credentials() self.exchange_manager.initialize_exchanges( exchange_credentials=exchange_credentials, database=self.data.db, ) # Initialize blockchain querying modules ethereum_manager = EthereumManager( ethrpc_endpoint=eth_rpc_endpoint, etherscan=self.etherscan, msg_aggregator=self.msg_aggregator, ) self.chain_manager = ChainManager( blockchain_accounts=self.data.db.get_blockchain_accounts(), owned_eth_tokens=self.data.db.get_owned_tokens(), ethereum_manager=ethereum_manager, msg_aggregator=self.msg_aggregator, alethio=alethio, greenlet_manager=self.greenlet_manager, premium=self.premium, eth_modules=settings.active_modules, ) self.ethereum_analyzer = EthereumAnalyzer( ethereum_manager=ethereum_manager, database=self.data.db, ) self.trades_historian = TradesHistorian( user_directory=self.user_directory, db=self.data.db, msg_aggregator=self.msg_aggregator, exchange_manager=self.exchange_manager, chain_manager=self.chain_manager, ) self.user_is_logged_in = True def logout(self) -> None: if not self.user_is_logged_in: return user = self.data.username log.info( 'Logging out user', user=user, ) del self.chain_manager self.exchange_manager.delete_all_exchanges() # Reset rotkehlchen logger to default LoggingSettings(anonymized_logs=DEFAULT_ANONYMIZED_LOGS) del self.accountant del self.trades_historian del self.data_importer if self.premium is not None: del self.premium self.data.logout() self.password = '' self.cryptocompare.unset_database() # Make sure no messages leak to other user sessions self.msg_aggregator.consume_errors() self.msg_aggregator.consume_warnings() self.user_is_logged_in = False log.info( 'User successfully logged out', user=user, ) def set_premium_credentials(self, credentials: PremiumCredentials) -> None: """ Sets the premium credentials for Rotki Raises PremiumAuthenticationError if the given key is rejected by the Rotkehlchen server """ log.info('Setting new premium credentials') if self.premium is not None: self.premium.set_credentials(credentials) else: self.premium = premium_create_and_verify(credentials) self.data.db.set_rotkehlchen_premium(credentials) def delete_premium_credentials(self, name: str) -> Tuple[bool, str]: """Deletes the premium credentials for Rotki""" success: bool msg = '' if name != self.data.username: msg = f'Provided user "{name}" is not the logged in user' success = False success = self.data.db.del_rotkehlchen_premium() if success is False: msg = 'The database was unable to delete the Premium keys for the logged-in user' self.deactivate_premium_status() return success, msg def deactivate_premium_status(self) -> None: """Deactivate premium in the current session""" self.premium = None self.premium_sync_manager.premium = None self.chain_manager.deactivate_premium_status() def start(self) -> gevent.Greenlet: return gevent.spawn(self.main_loop) def main_loop(self) -> None: """Rotki main loop that fires often and manages many different tasks Each task remembers the last time it run sucesfully and know how often it should run. So each task manages itself. """ while self.shutdown_event.wait(MAIN_LOOP_SECS_DELAY) is not True: if self.user_is_logged_in: log.debug('Main loop start') self.premium_sync_manager.maybe_upload_data_to_server() self.ethereum_analyzer.analyze_ethereum_transactions() log.debug('Main loop end') def add_blockchain_accounts( self, blockchain: SupportedBlockchain, account_data: List[BlockchainAccountData], ) -> BlockchainBalancesUpdate: """Adds new blockchain accounts Adds the accounts to the blockchain instance and queries them to get the updated balances. Also adds them in the DB May raise: - EthSyncError from modify_blockchain_account - InputError if the given accounts list is empty. - TagConstraintError if any of the given account data contain unknown tags. - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. """ self.data.db.ensure_tags_exist( given_data=account_data, action='adding', data_type='blockchain accounts', ) address_type = blockchain.get_address_type() updated_balances = self.chain_manager.add_blockchain_accounts( blockchain=blockchain, accounts=[address_type(entry.address) for entry in account_data], ) self.data.db.add_blockchain_accounts( blockchain=blockchain, account_data=account_data, ) return updated_balances def edit_blockchain_accounts( self, blockchain: SupportedBlockchain, account_data: List[BlockchainAccountData], ) -> None: """Edits blockchain accounts Edits blockchain account data for the given accounts May raise: - InputError if the given accounts list is empty or if any of the accounts to edit do not exist. - TagConstraintError if any of the given account data contain unknown tags. """ # First check for validity of account data addresses if len(account_data) == 0: raise InputError('Empty list of blockchain account data to edit was given') accounts = [x.address for x in account_data] unknown_accounts = set(accounts).difference(self.chain_manager.accounts.get(blockchain)) if len(unknown_accounts) != 0: raise InputError( f'Tried to edit unknown {blockchain.value} ' f'accounts {','.join(unknown_accounts)}', ) self.data.db.ensure_tags_exist( given_data=account_data, action='editing', data_type='blockchain accounts', ) # Finally edit the accounts self.data.db.edit_blockchain_accounts( blockchain=blockchain, account_data=account_data, ) return None def remove_blockchain_accounts( self, blockchain: SupportedBlockchain, accounts: ListOfBlockchainAddresses, ) -> BlockchainBalancesUpdate: """Removes blockchain accounts Removes the accounts from the blockchain instance and queries them to get the updated balances. Also removes them from the DB May raise: - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - InputError if a non-existing account was given to remove """ balances_update = self.chain_manager.remove_blockchain_accounts( blockchain=blockchain, accounts=accounts, ) self.data.db.remove_blockchain_accounts(blockchain, accounts) return balances_update def add_owned_eth_tokens( self, tokens: List[EthereumToken], ) -> BlockchainBalancesUpdate: """Adds tokens to the blockchain state and updates balance of all accounts May raise: - InputError if some of the tokens already exist - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - EthSyncError if querying the token balances through a provided ethereum client and the chain is not synced """ new_data = self.chain_manager.track_new_tokens(tokens) self.data.write_owned_eth_tokens(self.chain_manager.owned_eth_tokens) return new_data def remove_owned_eth_tokens( self, tokens: List[EthereumToken], ) -> BlockchainBalancesUpdate: """ Removes tokens from the state and stops their balance from being tracked for each account May raise: - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - EthSyncError if querying the token balances through a provided ethereum client and the chain is not synced """ new_data = self.chain_manager.remove_eth_tokens(tokens) self.data.write_owned_eth_tokens(self.chain_manager.owned_eth_tokens) return new_data def process_history( self, start_ts: Timestamp, end_ts: Timestamp, ) -> Tuple[Dict[str, Any], str]: ( error_or_empty, history, loan_history, asset_movements, eth_transactions, defi_events, ) = self.trades_historian.get_history( start_ts=start_ts, end_ts=end_ts, has_premium=self.premium is not None, ) result = self.accountant.process_history( start_ts=start_ts, end_ts=end_ts, trade_history=history, loan_history=loan_history, asset_movements=asset_movements, eth_transactions=eth_transactions, defi_events=defi_events, ) return result, error_or_empty def query_fiat_balances(self) -> Dict[Asset, Dict[str, FVal]]: result = {} balances = self.data.get_fiat_balances() for currency, str_amount in balances.items(): amount = FVal(str_amount) usd_rate = Inquirer().query_fiat_pair(currency, A_USD) result[currency] = { 'amount': amount, 'usd_value': amount * usd_rate, } return result def query_balances( self, requested_save_data: bool = False, timestamp: Timestamp = None, ignore_cache: bool = False, ) -> Dict[str, Any]: """Query all balances rotkehlchen can see. If requested_save_data is True then the data are always saved in the DB, if it is False then data are saved if self.data.should_save_balances() is True. If timestamp is None then the current timestamp is used. If a timestamp is given then that is the time that the balances are going to be saved in the DB If ignore_cache is True then all underlying calls that have a cache ignore it Returns a dictionary with the queried balances. """ log.info('query_balances called', requested_save_data=requested_save_data) balances = {} problem_free = True for _, exchange in self.exchange_manager.connected_exchanges.items(): exchange_balances, _ = exchange.query_balances(ignore_cache=ignore_cache) # If we got an error, disregard that exchange but make sure we don't save data if not isinstance(exchange_balances, dict): problem_free = False else: balances[exchange.name] = exchange_balances try: blockchain_result = self.chain_manager.query_balances( blockchain=None, ignore_cache=ignore_cache, ) balances['blockchain'] = { asset: balance.to_dict() for asset, balance in blockchain_result.totals.items() } except (RemoteError, EthSyncError) as e: problem_free = False log.error(f'Querying blockchain balances failed due to: {str(e)}') result = self.query_fiat_balances() if result != {}: balances['banks'] = result balances = account_for_manually_tracked_balances(db=self.data.db, balances=balances) combined = combine_stat_dicts([v for k, v in balances.items()]) total_usd_per_location = [(k, dict_get_sumof(v, 'usd_value')) for k, v in balances.items()] # calculate net usd value net_usd = FVal(0) for _, v in combined.items(): net_usd += FVal(v['usd_value']) stats: Dict[str, Any] = { 'location': { }, 'net_usd': net_usd, } for entry in total_usd_per_location: name = entry[0] total = entry[1] if net_usd != FVal(0): percentage = (total / net_usd).to_percentage() else: percentage = '0%' stats['location'][name] = { 'usd_value': total, 'percentage_of_net_value': percentage, } for k, v in combined.items(): if net_usd != FVal(0): percentage = (v['usd_value'] / net_usd).to_percentage() else: percentage = '0%' combined[k]['percentage_of_net_value'] = percentage result_dict = merge_dicts(combined, stats) allowed_to_save = requested_save_data or self.data.should_save_balances() if problem_free and allowed_to_save: if not timestamp: timestamp = Timestamp(int(time.time())) self.data.save_balances_data(data=result_dict, timestamp=timestamp) log.debug('query_balances data saved') else: log.debug( 'query_balances data not saved', allowed_to_save=allowed_to_save, problem_free=problem_free, ) # After adding it to the saved file we can overlay additional data that # is not required to be saved in the history file try: details = self.accountant.events.details for asset, (tax_free_amount, average_buy_value) in details.items(): if asset not in result_dict: continue result_dict[asset]['tax_free_amount'] = tax_free_amount result_dict[asset]['average_buy_value'] = average_buy_value current_price = result_dict[asset]['usd_value'] / result_dict[asset]['amount'] if average_buy_value != FVal(0): result_dict[asset]['percent_change'] = ( ((current_price - average_buy_value) / average_buy_value) * 100 ) else: result_dict[asset]['percent_change'] = 'INF' except AttributeError: pass return result_dict def set_settings(self, settings: ModifiableDBSettings) -> Tuple[bool, str]: """Tries to set new settings. Returns True in success or False with message if error""" with self.lock: if settings.eth_rpc_endpoint is not None: result, msg = self.chain_manager.set_eth_rpc_endpoint(settings.eth_rpc_endpoint) if not result: return False, msg if settings.kraken_account_type is not None: kraken = self.exchange_manager.get('kraken') if kraken: kraken.set_account_type(settings.kraken_account_type) # type: ignore self.data.db.set_settings(settings) return True, '' def get_settings(self) -> DBSettings: """Returns the db settings with a check whether premium is active or not""" db_settings = self.data.db.get_settings(have_premium=self.premium is not None) return db_settings def setup_exchange( self, name: str, api_key: ApiKey, api_secret: ApiSecret, passphrase: Optional[str] = None, ) -> Tuple[bool, str]: """ Setup a new exchange with an api key and an api secret and optionally a passphrase By default the api keys are always validated unless validate is False. """ is_success, msg = self.exchange_manager.setup_exchange( name=name, api_key=api_key, api_secret=api_secret, database=self.data.db, passphrase=passphrase, ) if is_success: # Success, save the result in the DB self.data.db.add_exchange(name, api_key, api_secret, passphrase=passphrase) return is_success, msg def remove_exchange(self, name: str) -> Tuple[bool, str]: if not self.exchange_manager.has_exchange(name): return False, 'Exchange {} is not registered'.format(name) self.exchange_manager.delete_exchange(name) # Success, remove it also from the DB self.data.db.remove_exchange(name) self.data.db.delete_used_query_range_for_exchange(name) return True, '' def query_periodic_data(self) -> Dict[str, Union[bool, Timestamp]]: """Query for frequently changing data""" result: Dict[str, Union[bool, Timestamp]] = {} if self.user_is_logged_in: result['last_balance_save'] = self.data.db.get_last_balance_save_time() result['eth_node_connection'] = self.chain_manager.ethereum.web3 is not None result['history_process_start_ts'] = self.accountant.started_processing_timestamp result['history_process_current_ts'] = self.accountant.currently_processing_timestamp return result def shutdown(self) -> None: self.logout() self.shutdown_event.set()
#!/usr/bin/env python import argparse import logging import os import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Union import gevent from gevent.lock import Semaphore from typing_extensions import Literal from rotkehlchen.accounting.accountant import Accountant from rotkehlchen.assets.asset import Asset, EthereumToken from rotkehlchen.assets.resolver import AssetResolver from rotkehlchen.balances.manual import account_for_manually_tracked_balances from rotkehlchen.chain.ethereum.manager import EthereumManager from rotkehlchen.chain.manager import BlockchainBalancesUpdate, ChainManager from rotkehlchen.config import default_data_directory from rotkehlchen.constants.assets import A_USD from rotkehlchen.data.importer import DataImporter from rotkehlchen.data_handler import DataHandler from rotkehlchen.db.settings import DBSettings, ModifiableDBSettings from rotkehlchen.errors import ( EthSyncError, InputError, PremiumAuthenticationError, RemoteError, SystemPermissionError, ) from rotkehlchen.exchanges.manager import ExchangeManager from rotkehlchen.externalapis.alethio import Alethio from rotkehlchen.externalapis.cryptocompare import Cryptocompare from rotkehlchen.externalapis.etherscan import Etherscan from rotkehlchen.fval import FVal from rotkehlchen.greenlets import GreenletManager from rotkehlchen.history import PriceHistorian, TradesHistorian from rotkehlchen.inquirer import Inquirer from rotkehlchen.logging import DEFAULT_ANONYMIZED_LOGS, LoggingSettings, RotkehlchenLogsAdapter from rotkehlchen.premium.premium import Premium, PremiumCredentials, premium_create_and_verify from rotkehlchen.premium.sync import PremiumSyncManager from rotkehlchen.transactions import EthereumAnalyzer from rotkehlchen.typing import ( ApiKey, ApiSecret, BlockchainAccountData, ListOfBlockchainAddresses, SupportedBlockchain, Timestamp, ) from rotkehlchen.usage_analytics import maybe_submit_usage_analytics from rotkehlchen.user_messages import MessagesAggregator from rotkehlchen.utils.misc import combine_stat_dicts, dict_get_sumof, merge_dicts logger = logging.getLogger(__name__) log = RotkehlchenLogsAdapter(logger) MAIN_LOOP_SECS_DELAY = 15 class Rotkehlchen(): def __init__(self, args: argparse.Namespace) -> None: """Initialize the Rotkehlchen object May Raise: - SystemPermissionError if the given data directory's permissions are not correct. """ self.lock = Semaphore() self.lock.acquire() # Can also be None after unlock if premium credentials did not # authenticate or premium server temporarily offline self.premium: Optional[Premium] = None self.user_is_logged_in = False logfilename = None if args.logtarget == 'file': logfilename = args.logfile if args.loglevel == 'debug': loglevel = logging.DEBUG elif args.loglevel == 'info': loglevel = logging.INFO elif args.loglevel == 'warn': loglevel = logging.WARN elif args.loglevel == 'error': loglevel = logging.ERROR elif args.loglevel == 'critical': loglevel = logging.CRITICAL else: raise AssertionError('Should never get here. Illegal log value') logging.basicConfig( filename=logfilename, filemode='w', level=loglevel, format='%(asctime)s -- %(levelname)s:%(name)s:%(message)s', datefmt='%d/%m/%Y %H:%M:%S %Z', ) if not args.logfromothermodules: logging.getLogger('urllib3').setLevel(logging.CRITICAL) logging.getLogger('urllib3.connectionpool').setLevel(logging.CRITICAL) self.sleep_secs = args.sleep_secs if args.data_dir is None: self.data_dir = default_data_directory() else: self.data_dir = Path(args.data_dir) if not os.access(self.data_dir, os.W_OK | os.R_OK): raise SystemPermissionError( f'The given data directory {self.data_dir} is not readable or writable', ) self.args = args self.msg_aggregator = MessagesAggregator() self.greenlet_manager = GreenletManager(msg_aggregator=self.msg_aggregator) self.exchange_manager = ExchangeManager(msg_aggregator=self.msg_aggregator) self.all_eth_tokens = AssetResolver().get_all_eth_tokens() self.data = DataHandler(self.data_dir, self.msg_aggregator) self.cryptocompare = Cryptocompare(data_directory=self.data_dir, database=None) # Initialize the Inquirer singleton Inquirer(data_dir=self.data_dir, cryptocompare=self.cryptocompare) self.lock.release() self.shutdown_event = gevent.event.Event() def reset_after_failed_account_creation_or_login(self) -> None: """If the account creation or login failed make sure that the Rotki instance is clear Tricky instances are when after either failed premium credentials or user refusal to sync premium databases we relogged in. """ self.cryptocompare.db = None def unlock_user( self, user: str, password: str, create_new: bool, sync_approval: Literal['yes', 'no', 'unknown'], premium_credentials: Optional[PremiumCredentials], initial_settings: Optional[ModifiableDBSettings] = None, ) -> None: """Unlocks an existing user or creates a new one if `create_new` is True May raise: - PremiumAuthenticationError if the password can't unlock the database. - AuthenticationError if premium_credentials are given and are invalid or can't authenticate with the server - DBUpgradeError if the rotki DB version is newer than the software or there is a DB upgrade and there is an error. - SystemPermissionError if the directory or DB file can not be accessed """ log.info( 'Unlocking user', user=user, create_new=create_new, sync_approval=sync_approval, initial_settings=initial_settings, ) # unlock or create the DB self.password = password self.user_directory = self.data.unlock(user, password, create_new, initial_settings) self.data_importer = DataImporter(db=self.data.db) self.last_data_upload_ts = self.data.db.get_last_data_upload_ts() self.premium_sync_manager = PremiumSyncManager(data=self.data, password=password) # set the DB in the external services instances that need it self.cryptocompare.set_database(self.data.db) # Anything that was set above here has to be cleaned in case of failure in the next step # by reset_after_failed_account_creation_or_login() try: self.premium = self.premium_sync_manager.try_premium_at_start( given_premium_credentials=premium_credentials, username=user, create_new=create_new, sync_approval=sync_approval, ) except PremiumAuthenticationError: # Reraise it only if this is during the creation of a new account where # the premium credentials were given by the user if create_new: raise # else let's just continue. User signed in succesfully, but he just # has unauthenticable/invalid premium credentials remaining in his DB settings = self.get_settings() maybe_submit_usage_analytics(settings.submit_usage_analytics) self.etherscan = Etherscan(database=self.data.db, msg_aggregator=self.msg_aggregator) alethio = Alethio( database=self.data.db, msg_aggregator=self.msg_aggregator, all_eth_tokens=self.all_eth_tokens, ) historical_data_start = settings.historical_data_start eth_rpc_endpoint = settings.eth_rpc_endpoint # Initialize the price historian singleton PriceHistorian( data_directory=self.data_dir, history_date_start=historical_data_start, cryptocompare=self.cryptocompare, ) self.accountant = Accountant( db=self.data.db, user_directory=self.user_directory, msg_aggregator=self.msg_aggregator, create_csv=True, ) # Initialize the rotkehlchen logger LoggingSettings(anonymized_logs=settings.anonymized_logs) exchange_credentials = self.data.db.get_exchange_credentials() self.exchange_manager.initialize_exchanges( exchange_credentials=exchange_credentials, database=self.data.db, ) # Initialize blockchain querying modules ethereum_manager = EthereumManager( ethrpc_endpoint=eth_rpc_endpoint, etherscan=self.etherscan, msg_aggregator=self.msg_aggregator, ) self.chain_manager = ChainManager( blockchain_accounts=self.data.db.get_blockchain_accounts(), owned_eth_tokens=self.data.db.get_owned_tokens(), ethereum_manager=ethereum_manager, msg_aggregator=self.msg_aggregator, alethio=alethio, greenlet_manager=self.greenlet_manager, premium=self.premium, eth_modules=settings.active_modules, ) self.ethereum_analyzer = EthereumAnalyzer( ethereum_manager=ethereum_manager, database=self.data.db, ) self.trades_historian = TradesHistorian( user_directory=self.user_directory, db=self.data.db, msg_aggregator=self.msg_aggregator, exchange_manager=self.exchange_manager, chain_manager=self.chain_manager, ) self.user_is_logged_in = True def logout(self) -> None: if not self.user_is_logged_in: return user = self.data.username log.info( 'Logging out user', user=user, ) del self.chain_manager self.exchange_manager.delete_all_exchanges() # Reset rotkehlchen logger to default LoggingSettings(anonymized_logs=DEFAULT_ANONYMIZED_LOGS) del self.accountant del self.trades_historian del self.data_importer if self.premium is not None: del self.premium self.data.logout() self.password = '' self.cryptocompare.unset_database() # Make sure no messages leak to other user sessions self.msg_aggregator.consume_errors() self.msg_aggregator.consume_warnings() self.user_is_logged_in = False log.info( 'User successfully logged out', user=user, ) def set_premium_credentials(self, credentials: PremiumCredentials) -> None: """ Sets the premium credentials for Rotki Raises PremiumAuthenticationError if the given key is rejected by the Rotkehlchen server """ log.info('Setting new premium credentials') if self.premium is not None: self.premium.set_credentials(credentials) else: self.premium = premium_create_and_verify(credentials) self.data.db.set_rotkehlchen_premium(credentials) def delete_premium_credentials(self, name: str) -> Tuple[bool, str]: """Deletes the premium credentials for Rotki""" success: bool msg = '' if name != self.data.username: msg = f'Provided user "{name}" is not the logged in user' success = False success = self.data.db.del_rotkehlchen_premium() if success is False: msg = 'The database was unable to delete the Premium keys for the logged-in user' self.deactivate_premium_status() return success, msg def deactivate_premium_status(self) -> None: """Deactivate premium in the current session""" self.premium = None self.premium_sync_manager.premium = None self.chain_manager.deactivate_premium_status() def start(self) -> gevent.Greenlet: return gevent.spawn(self.main_loop) def main_loop(self) -> None: """Rotki main loop that fires often and manages many different tasks Each task remembers the last time it run sucesfully and know how often it should run. So each task manages itself. """ while self.shutdown_event.wait(MAIN_LOOP_SECS_DELAY) is not True: if self.user_is_logged_in: log.debug('Main loop start') self.premium_sync_manager.maybe_upload_data_to_server() self.ethereum_analyzer.analyze_ethereum_transactions() log.debug('Main loop end') def add_blockchain_accounts( self, blockchain: SupportedBlockchain, account_data: List[BlockchainAccountData], ) -> BlockchainBalancesUpdate: """Adds new blockchain accounts Adds the accounts to the blockchain instance and queries them to get the updated balances. Also adds them in the DB May raise: - EthSyncError from modify_blockchain_account - InputError if the given accounts list is empty. - TagConstraintError if any of the given account data contain unknown tags. - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. """ self.data.db.ensure_tags_exist( given_data=account_data, action='adding', data_type='blockchain accounts', ) address_type = blockchain.get_address_type() updated_balances = self.chain_manager.add_blockchain_accounts( blockchain=blockchain, accounts=[address_type(entry.address) for entry in account_data], ) self.data.db.add_blockchain_accounts( blockchain=blockchain, account_data=account_data, ) return updated_balances def edit_blockchain_accounts( self, blockchain: SupportedBlockchain, account_data: List[BlockchainAccountData], ) -> None: """Edits blockchain accounts Edits blockchain account data for the given accounts May raise: - InputError if the given accounts list is empty or if any of the accounts to edit do not exist. - TagConstraintError if any of the given account data contain unknown tags. """ # First check for validity of account data addresses if len(account_data) == 0: raise InputError('Empty list of blockchain account data to edit was given') accounts = [x.address for x in account_data] unknown_accounts = set(accounts).difference(self.chain_manager.accounts.get(blockchain)) if len(unknown_accounts) != 0: raise InputError( f'Tried to edit unknown {blockchain.value} ' f'accounts {",".join(unknown_accounts)}', ) self.data.db.ensure_tags_exist( given_data=account_data, action='editing', data_type='blockchain accounts', ) # Finally edit the accounts self.data.db.edit_blockchain_accounts( blockchain=blockchain, account_data=account_data, ) return None def remove_blockchain_accounts( self, blockchain: SupportedBlockchain, accounts: ListOfBlockchainAddresses, ) -> BlockchainBalancesUpdate: """Removes blockchain accounts Removes the accounts from the blockchain instance and queries them to get the updated balances. Also removes them from the DB May raise: - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - InputError if a non-existing account was given to remove """ balances_update = self.chain_manager.remove_blockchain_accounts( blockchain=blockchain, accounts=accounts, ) self.data.db.remove_blockchain_accounts(blockchain, accounts) return balances_update def add_owned_eth_tokens( self, tokens: List[EthereumToken], ) -> BlockchainBalancesUpdate: """Adds tokens to the blockchain state and updates balance of all accounts May raise: - InputError if some of the tokens already exist - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - EthSyncError if querying the token balances through a provided ethereum client and the chain is not synced """ new_data = self.chain_manager.track_new_tokens(tokens) self.data.write_owned_eth_tokens(self.chain_manager.owned_eth_tokens) return new_data def remove_owned_eth_tokens( self, tokens: List[EthereumToken], ) -> BlockchainBalancesUpdate: """ Removes tokens from the state and stops their balance from being tracked for each account May raise: - RemoteError if an external service such as Etherscan is queried and there is a problem with its query. - EthSyncError if querying the token balances through a provided ethereum client and the chain is not synced """ new_data = self.chain_manager.remove_eth_tokens(tokens) self.data.write_owned_eth_tokens(self.chain_manager.owned_eth_tokens) return new_data def process_history( self, start_ts: Timestamp, end_ts: Timestamp, ) -> Tuple[Dict[str, Any], str]: ( error_or_empty, history, loan_history, asset_movements, eth_transactions, defi_events, ) = self.trades_historian.get_history( start_ts=start_ts, end_ts=end_ts, has_premium=self.premium is not None, ) result = self.accountant.process_history( start_ts=start_ts, end_ts=end_ts, trade_history=history, loan_history=loan_history, asset_movements=asset_movements, eth_transactions=eth_transactions, defi_events=defi_events, ) return result, error_or_empty def query_fiat_balances(self) -> Dict[Asset, Dict[str, FVal]]: result = {} balances = self.data.get_fiat_balances() for currency, str_amount in balances.items(): amount = FVal(str_amount) usd_rate = Inquirer().query_fiat_pair(currency, A_USD) result[currency] = { 'amount': amount, 'usd_value': amount * usd_rate, } return result def query_balances( self, requested_save_data: bool = False, timestamp: Timestamp = None, ignore_cache: bool = False, ) -> Dict[str, Any]: """Query all balances rotkehlchen can see. If requested_save_data is True then the data are always saved in the DB, if it is False then data are saved if self.data.should_save_balances() is True. If timestamp is None then the current timestamp is used. If a timestamp is given then that is the time that the balances are going to be saved in the DB If ignore_cache is True then all underlying calls that have a cache ignore it Returns a dictionary with the queried balances. """ log.info('query_balances called', requested_save_data=requested_save_data) balances = {} problem_free = True for _, exchange in self.exchange_manager.connected_exchanges.items(): exchange_balances, _ = exchange.query_balances(ignore_cache=ignore_cache) # If we got an error, disregard that exchange but make sure we don't save data if not isinstance(exchange_balances, dict): problem_free = False else: balances[exchange.name] = exchange_balances try: blockchain_result = self.chain_manager.query_balances( blockchain=None, ignore_cache=ignore_cache, ) balances['blockchain'] = { asset: balance.to_dict() for asset, balance in blockchain_result.totals.items() } except (RemoteError, EthSyncError) as e: problem_free = False log.error(f'Querying blockchain balances failed due to: {str(e)}') result = self.query_fiat_balances() if result != {}: balances['banks'] = result balances = account_for_manually_tracked_balances(db=self.data.db, balances=balances) combined = combine_stat_dicts([v for k, v in balances.items()]) total_usd_per_location = [(k, dict_get_sumof(v, 'usd_value')) for k, v in balances.items()] # calculate net usd value net_usd = FVal(0) for _, v in combined.items(): net_usd += FVal(v['usd_value']) stats: Dict[str, Any] = { 'location': { }, 'net_usd': net_usd, } for entry in total_usd_per_location: name = entry[0] total = entry[1] if net_usd != FVal(0): percentage = (total / net_usd).to_percentage() else: percentage = '0%' stats['location'][name] = { 'usd_value': total, 'percentage_of_net_value': percentage, } for k, v in combined.items(): if net_usd != FVal(0): percentage = (v['usd_value'] / net_usd).to_percentage() else: percentage = '0%' combined[k]['percentage_of_net_value'] = percentage result_dict = merge_dicts(combined, stats) allowed_to_save = requested_save_data or self.data.should_save_balances() if problem_free and allowed_to_save: if not timestamp: timestamp = Timestamp(int(time.time())) self.data.save_balances_data(data=result_dict, timestamp=timestamp) log.debug('query_balances data saved') else: log.debug( 'query_balances data not saved', allowed_to_save=allowed_to_save, problem_free=problem_free, ) # After adding it to the saved file we can overlay additional data that # is not required to be saved in the history file try: details = self.accountant.events.details for asset, (tax_free_amount, average_buy_value) in details.items(): if asset not in result_dict: continue result_dict[asset]['tax_free_amount'] = tax_free_amount result_dict[asset]['average_buy_value'] = average_buy_value current_price = result_dict[asset]['usd_value'] / result_dict[asset]['amount'] if average_buy_value != FVal(0): result_dict[asset]['percent_change'] = ( ((current_price - average_buy_value) / average_buy_value) * 100 ) else: result_dict[asset]['percent_change'] = 'INF' except AttributeError: pass return result_dict def set_settings(self, settings: ModifiableDBSettings) -> Tuple[bool, str]: """Tries to set new settings. Returns True in success or False with message if error""" with self.lock: if settings.eth_rpc_endpoint is not None: result, msg = self.chain_manager.set_eth_rpc_endpoint(settings.eth_rpc_endpoint) if not result: return False, msg if settings.kraken_account_type is not None: kraken = self.exchange_manager.get('kraken') if kraken: kraken.set_account_type(settings.kraken_account_type) # type: ignore self.data.db.set_settings(settings) return True, '' def get_settings(self) -> DBSettings: """Returns the db settings with a check whether premium is active or not""" db_settings = self.data.db.get_settings(have_premium=self.premium is not None) return db_settings def setup_exchange( self, name: str, api_key: ApiKey, api_secret: ApiSecret, passphrase: Optional[str] = None, ) -> Tuple[bool, str]: """ Setup a new exchange with an api key and an api secret and optionally a passphrase By default the api keys are always validated unless validate is False. """ is_success, msg = self.exchange_manager.setup_exchange( name=name, api_key=api_key, api_secret=api_secret, database=self.data.db, passphrase=passphrase, ) if is_success: # Success, save the result in the DB self.data.db.add_exchange(name, api_key, api_secret, passphrase=passphrase) return is_success, msg def remove_exchange(self, name: str) -> Tuple[bool, str]: if not self.exchange_manager.has_exchange(name): return False, 'Exchange {} is not registered'.format(name) self.exchange_manager.delete_exchange(name) # Success, remove it also from the DB self.data.db.remove_exchange(name) self.data.db.delete_used_query_range_for_exchange(name) return True, '' def query_periodic_data(self) -> Dict[str, Union[bool, Timestamp]]: """Query for frequently changing data""" result: Dict[str, Union[bool, Timestamp]] = {} if self.user_is_logged_in: result['last_balance_save'] = self.data.db.get_last_balance_save_time() result['eth_node_connection'] = self.chain_manager.ethereum.web3 is not None result['history_process_start_ts'] = self.accountant.started_processing_timestamp result['history_process_current_ts'] = self.accountant.currently_processing_timestamp return result def shutdown(self) -> None: self.logout() self.shutdown_event.set()
""" MIT License Copyright (c) 2020 Airbyte Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import csv import io import json import pkgutil import time from typing import Dict, List, Optional, Tuple, Union import msal import requests from airbyte_protocol import AirbyteStream from msal.exceptions import MsalServiceError class Client: """ Microsoft Teams API Reference: https://docs.microsoft.com/en-us/graph/api/resources/teams-api-overview?view=graph-rest-1.0 """ MICROSOFT_GRAPH_BASE_API_URL: str = "https://graph.microsoft.com/" MICROSOFT_GRAPH_API_VERSION: str = "v1.0" PAGINATION_COUNT: Optional[int] = 20 def __init__(self, config: json): self.ENTITY_MAP = { "users": self.get_users, "groups": self.get_groups, "group_members": self.get_group_members, "group_owners": self.get_group_owners, "channels": self.get_channels, "channel_members": self.get_channel_members, "channel_tabs": self.get_channel_tabs, "conversations": self.get_conversations, "conversation_threads": self.get_conversation_threads, "conversation_posts": self.get_conversation_posts, "team_drives": self.get_team_drives, "team_device_usage_report": self.get_team_device_usage_report, } self.configs = config self._group_ids = None self.msal_app = msal.ConfidentialClientApplication( self.configs["client_id"], authority=f"https://login.microsoftonline.com/" f"{self.configs["tenant_id"]}", client_credential=self.configs["client_secret"], ) def _get_api_url(self, endpoint: str) -> str: api_url = f"{self.MICROSOFT_GRAPH_BASE_API_URL}{self.MICROSOFT_GRAPH_API_VERSION}/{endpoint}/" return api_url def _get_access_token(self) -> str: scope = ["https://graph.microsoft.com/.default"] # First, the code looks up a token from the cache. result = self.msal_app.acquire_token_silent(scope, account=None) # If no suitable token exists in cache. Let's get a new one from AAD. if not result: result = self.msal_app.acquire_token_for_client(scopes=scope) if "access_token" in result: return result["access_token"] else: raise MsalServiceError(error=result.get("error"), error_description=result.get("error_description")) def _make_request(self, api_url: str, params: Optional[Dict] = None) -> Union[Dict, object]: access_token = self._get_access_token() headers = {"Authorization": f"Bearer {access_token}"} response = requests.get(api_url, headers=headers, params=params) if response.status_code == 429: if "Retry-After" in response.headers: pause_time = float(response.headers["Retry-After"]) time.sleep(pause_time) response = requests.get(api_url, headers=headers, params=params) if response.status_code != 200: raise requests.exceptions.RequestException(response.text) if response.headers["Content-Type"] == "application/octet-stream": raw_response = response.content else: raw_response = response.json() return raw_response @staticmethod def _get_response_value_unsafe(raw_response: Dict) -> List: if "value" not in raw_response: raise requests.exceptions.RequestException() value = raw_response["value"] return value def _get_request_params(self, params: Optional[Dict] = None, pagination: bool = True) -> Dict: if self.PAGINATION_COUNT and pagination: params = params if params else {} if "$top" not in params: params["$top"] = self.PAGINATION_COUNT return params def _fetch_data(self, endpoint: str, params: Optional[Dict] = None, pagination: bool = True): api_url = self._get_api_url(endpoint) params = self._get_request_params(params, pagination) while True: raw_response = self._make_request(api_url, params) value = self._get_response_value_unsafe(raw_response) yield value if "@odata.nextLink" not in raw_response: break params = None api_url = raw_response["@odata.nextLink"] def health_check(self) -> Tuple[bool, object]: try: self._get_access_token() return True, None except MsalServiceError as err: return False, err.args[0] def get_streams(self): streams = [] for schema, method in self.ENTITY_MAP.items(): raw_schema = json.loads(pkgutil.get_data(self.__class__.__module__.split(".")[0], f"schemas/{schema}.json")) streams.append(AirbyteStream(name=schema, json_schema=raw_schema)) return streams def get_users(self): for users in self._fetch_data("users"): yield users def get_groups(self): for groups in self._fetch_data("groups"): yield filter(lambda item: "Team" in item["resourceProvisioningOptions"], groups) def _get_group_ids(self): if not self._group_ids: api_url = self._get_api_url("groups") params = {"$select": "id,resourceProvisioningOptions"} groups = self._get_response_value_unsafe(self._make_request(api_url, params=params)) self._group_ids = [item["id"] for item in groups if "Team" in item["resourceProvisioningOptions"]] return self._group_ids def get_group_members(self): for group_id in self._get_group_ids(): for members in self._fetch_data(f"groups/{group_id}/members"): yield members def get_group_owners(self): for group_id in self._get_group_ids(): for owners in self._fetch_data(f"groups/{group_id}/owners"): yield owners def get_channels(self): for group_id in self._get_group_ids(): for channels in self._fetch_data(f"teams/{group_id}/channels", pagination=False): yield channels def _get_channel_ids(self, group_id: str): api_url = self._get_api_url(f"teams/{group_id}/channels") params = {"$select": "id"} channels_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return channels_ids def get_channel_members(self): for group_id in self._get_group_ids(): channels = self._get_channel_ids(group_id=group_id) for channel in channels: for members in self._fetch_data(f'teams/{group_id}/channels/{channel['id']}/members'): yield members def get_channel_tabs(self): for group_id in self._get_group_ids(): channels = self._get_channel_ids(group_id=group_id) for channel in channels: for tabs in self._fetch_data(f'teams/{group_id}/channels/{channel['id']}/tabs', pagination=False): yield tabs def get_conversations(self): for group_id in self._get_group_ids(): for conversations in self._fetch_data(f"groups/{group_id}/conversations"): yield conversations def _get_conversation_ids(self, group_id: str): api_url = self._get_api_url(f"groups/{group_id}/conversations") params = {"$select": "id"} conversation_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return conversation_ids def get_conversation_threads(self): for group_id in self._get_group_ids(): conversations = self._get_conversation_ids(group_id=group_id) for conversation in conversations: for threads in self._fetch_data(f'groups/{group_id}/conversations/{conversation['id']}/threads'): yield threads def _get_thread_ids(self, group_id: str, conversation_id: str): api_url = self._get_api_url(f"groups/{group_id}/conversations/{conversation_id}/threads") params = {"$select": "id"} thread_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return thread_ids def get_conversation_posts(self): for group_id in self._get_group_ids(): conversations = self._get_conversation_ids(group_id=group_id) for conversation in conversations: threads = self._get_thread_ids(group_id, conversation["id"]) for thread in threads: for posts in self._fetch_data(f'groups/{group_id}/conversations/{conversation['id']}/threads/{thread['id']}/posts'): yield posts def get_team_drives(self): for group_id in self._get_group_ids(): for drives in self._fetch_data(f"groups/{group_id}/drives"): yield drives def get_team_device_usage_report(self): period = self.configs["period"] api_url = self._get_api_url(f"reports/getTeamsDeviceUsageUserDetail(period='{period}')") csv_response = io.BytesIO(self._make_request(api_url)) csv_response.readline() with io.TextIOWrapper(csv_response, encoding="utf-8-sig") as text_file: field_names = [ "report_refresh_date", "user_principal_name", "last_activity_date", "is_deleted", "deleted_date", "used_web", "used_windows_phone", "used_i_os", "used_mac", "used_android_phone", "used_windows", "report_period", ] reader = csv.DictReader(text_file, fieldnames=field_names) for row in reader: yield [ row, ]
""" MIT License Copyright (c) 2020 Airbyte Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import csv import io import json import pkgutil import time from typing import Dict, List, Optional, Tuple, Union import msal import requests from airbyte_protocol import AirbyteStream from msal.exceptions import MsalServiceError class Client: """ Microsoft Teams API Reference: https://docs.microsoft.com/en-us/graph/api/resources/teams-api-overview?view=graph-rest-1.0 """ MICROSOFT_GRAPH_BASE_API_URL: str = "https://graph.microsoft.com/" MICROSOFT_GRAPH_API_VERSION: str = "v1.0" PAGINATION_COUNT: Optional[int] = 20 def __init__(self, config: json): self.ENTITY_MAP = { "users": self.get_users, "groups": self.get_groups, "group_members": self.get_group_members, "group_owners": self.get_group_owners, "channels": self.get_channels, "channel_members": self.get_channel_members, "channel_tabs": self.get_channel_tabs, "conversations": self.get_conversations, "conversation_threads": self.get_conversation_threads, "conversation_posts": self.get_conversation_posts, "team_drives": self.get_team_drives, "team_device_usage_report": self.get_team_device_usage_report, } self.configs = config self._group_ids = None self.msal_app = msal.ConfidentialClientApplication( self.configs["client_id"], authority=f"https://login.microsoftonline.com/" f"{self.configs['tenant_id']}", client_credential=self.configs["client_secret"], ) def _get_api_url(self, endpoint: str) -> str: api_url = f"{self.MICROSOFT_GRAPH_BASE_API_URL}{self.MICROSOFT_GRAPH_API_VERSION}/{endpoint}/" return api_url def _get_access_token(self) -> str: scope = ["https://graph.microsoft.com/.default"] # First, the code looks up a token from the cache. result = self.msal_app.acquire_token_silent(scope, account=None) # If no suitable token exists in cache. Let's get a new one from AAD. if not result: result = self.msal_app.acquire_token_for_client(scopes=scope) if "access_token" in result: return result["access_token"] else: raise MsalServiceError(error=result.get("error"), error_description=result.get("error_description")) def _make_request(self, api_url: str, params: Optional[Dict] = None) -> Union[Dict, object]: access_token = self._get_access_token() headers = {"Authorization": f"Bearer {access_token}"} response = requests.get(api_url, headers=headers, params=params) if response.status_code == 429: if "Retry-After" in response.headers: pause_time = float(response.headers["Retry-After"]) time.sleep(pause_time) response = requests.get(api_url, headers=headers, params=params) if response.status_code != 200: raise requests.exceptions.RequestException(response.text) if response.headers["Content-Type"] == "application/octet-stream": raw_response = response.content else: raw_response = response.json() return raw_response @staticmethod def _get_response_value_unsafe(raw_response: Dict) -> List: if "value" not in raw_response: raise requests.exceptions.RequestException() value = raw_response["value"] return value def _get_request_params(self, params: Optional[Dict] = None, pagination: bool = True) -> Dict: if self.PAGINATION_COUNT and pagination: params = params if params else {} if "$top" not in params: params["$top"] = self.PAGINATION_COUNT return params def _fetch_data(self, endpoint: str, params: Optional[Dict] = None, pagination: bool = True): api_url = self._get_api_url(endpoint) params = self._get_request_params(params, pagination) while True: raw_response = self._make_request(api_url, params) value = self._get_response_value_unsafe(raw_response) yield value if "@odata.nextLink" not in raw_response: break params = None api_url = raw_response["@odata.nextLink"] def health_check(self) -> Tuple[bool, object]: try: self._get_access_token() return True, None except MsalServiceError as err: return False, err.args[0] def get_streams(self): streams = [] for schema, method in self.ENTITY_MAP.items(): raw_schema = json.loads(pkgutil.get_data(self.__class__.__module__.split(".")[0], f"schemas/{schema}.json")) streams.append(AirbyteStream(name=schema, json_schema=raw_schema)) return streams def get_users(self): for users in self._fetch_data("users"): yield users def get_groups(self): for groups in self._fetch_data("groups"): yield filter(lambda item: "Team" in item["resourceProvisioningOptions"], groups) def _get_group_ids(self): if not self._group_ids: api_url = self._get_api_url("groups") params = {"$select": "id,resourceProvisioningOptions"} groups = self._get_response_value_unsafe(self._make_request(api_url, params=params)) self._group_ids = [item["id"] for item in groups if "Team" in item["resourceProvisioningOptions"]] return self._group_ids def get_group_members(self): for group_id in self._get_group_ids(): for members in self._fetch_data(f"groups/{group_id}/members"): yield members def get_group_owners(self): for group_id in self._get_group_ids(): for owners in self._fetch_data(f"groups/{group_id}/owners"): yield owners def get_channels(self): for group_id in self._get_group_ids(): for channels in self._fetch_data(f"teams/{group_id}/channels", pagination=False): yield channels def _get_channel_ids(self, group_id: str): api_url = self._get_api_url(f"teams/{group_id}/channels") params = {"$select": "id"} channels_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return channels_ids def get_channel_members(self): for group_id in self._get_group_ids(): channels = self._get_channel_ids(group_id=group_id) for channel in channels: for members in self._fetch_data(f'teams/{group_id}/channels/{channel["id"]}/members'): yield members def get_channel_tabs(self): for group_id in self._get_group_ids(): channels = self._get_channel_ids(group_id=group_id) for channel in channels: for tabs in self._fetch_data(f'teams/{group_id}/channels/{channel["id"]}/tabs', pagination=False): yield tabs def get_conversations(self): for group_id in self._get_group_ids(): for conversations in self._fetch_data(f"groups/{group_id}/conversations"): yield conversations def _get_conversation_ids(self, group_id: str): api_url = self._get_api_url(f"groups/{group_id}/conversations") params = {"$select": "id"} conversation_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return conversation_ids def get_conversation_threads(self): for group_id in self._get_group_ids(): conversations = self._get_conversation_ids(group_id=group_id) for conversation in conversations: for threads in self._fetch_data(f'groups/{group_id}/conversations/{conversation["id"]}/threads'): yield threads def _get_thread_ids(self, group_id: str, conversation_id: str): api_url = self._get_api_url(f"groups/{group_id}/conversations/{conversation_id}/threads") params = {"$select": "id"} thread_ids = self._get_response_value_unsafe(self._make_request(api_url, params=params)) return thread_ids def get_conversation_posts(self): for group_id in self._get_group_ids(): conversations = self._get_conversation_ids(group_id=group_id) for conversation in conversations: threads = self._get_thread_ids(group_id, conversation["id"]) for thread in threads: for posts in self._fetch_data(f'groups/{group_id}/conversations/{conversation["id"]}/threads/{thread["id"]}/posts'): yield posts def get_team_drives(self): for group_id in self._get_group_ids(): for drives in self._fetch_data(f"groups/{group_id}/drives"): yield drives def get_team_device_usage_report(self): period = self.configs["period"] api_url = self._get_api_url(f"reports/getTeamsDeviceUsageUserDetail(period='{period}')") csv_response = io.BytesIO(self._make_request(api_url)) csv_response.readline() with io.TextIOWrapper(csv_response, encoding="utf-8-sig") as text_file: field_names = [ "report_refresh_date", "user_principal_name", "last_activity_date", "is_deleted", "deleted_date", "used_web", "used_windows_phone", "used_i_os", "used_mac", "used_android_phone", "used_windows", "report_period", ] reader = csv.DictReader(text_file, fieldnames=field_names) for row in reader: yield [ row, ]
import sqlite3 from os import listdir import pandas as pd from transfer_data import pick_path def database_pipeline(path): connection = sqlite3.connect("./baseData/allPlayerStats.db") cursor = connection.cursor() # See this for various ways to import CSV into sqlite using Python. Pandas used here because files are not prohibitively large. # https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python print("SQL scripts starting...") # Drop old tables, might not be necessary since we're dropping them sql_file = open("./scripts/SQL/drop_old_tables.sql") try: sql_as_string = sql_file.read() cursor.executescript(sql_as_string) sql_file.close() except Exception: pass # Decide whether to have user pick path or just set it automatically... for fileName in listdir(path): if fileName.endswith('.csv'): # Avoid any accidents df = pd.read_csv(f'{path}/{fileName}') df.to_sql( f'{fileName.replace('.csv','').split('_')[0]}', connection, if_exists='replace', index=False) try: date = f'{fileName.replace('.csv','').split('_')[1]}' except Exception: pass # Make changes to tables sql_file = open("./scripts/SQL/prep_tables_for_extraction.sql") try: sql_as_string = sql_file.read() cursor.executescript(sql_as_string) except Exception: pass sql_file.close() # Extract this season's qualified players sql_file = open("./scripts/SQL/players2022_dbeaver.sql") df_output = pd.read_sql_query(sql_file.read(), connection) sql_file.close() # sql_as_string = sql_file.read() # cursor.executescript(sql_as_string) print(df_output) df_output.to_csv(f'{path}/stats_{date}.csv', index=False) print("SQL scripts complete.") def main(): data_path = pick_path() database_pipeline(data_path) if __name__ == '__main__': main()
import sqlite3 from os import listdir import pandas as pd from transfer_data import pick_path def database_pipeline(path): connection = sqlite3.connect("./baseData/allPlayerStats.db") cursor = connection.cursor() # See this for various ways to import CSV into sqlite using Python. Pandas used here because files are not prohibitively large. # https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python print("SQL scripts starting...") # Drop old tables, might not be necessary since we're dropping them sql_file = open("./scripts/SQL/drop_old_tables.sql") try: sql_as_string = sql_file.read() cursor.executescript(sql_as_string) sql_file.close() except Exception: pass # Decide whether to have user pick path or just set it automatically... for fileName in listdir(path): if fileName.endswith('.csv'): # Avoid any accidents df = pd.read_csv(f'{path}/{fileName}') df.to_sql( f'{fileName.replace(".csv","").split("_")[0]}', connection, if_exists='replace', index=False) try: date = f'{fileName.replace(".csv","").split("_")[1]}' except Exception: pass # Make changes to tables sql_file = open("./scripts/SQL/prep_tables_for_extraction.sql") try: sql_as_string = sql_file.read() cursor.executescript(sql_as_string) except Exception: pass sql_file.close() # Extract this season's qualified players sql_file = open("./scripts/SQL/players2022_dbeaver.sql") df_output = pd.read_sql_query(sql_file.read(), connection) sql_file.close() # sql_as_string = sql_file.read() # cursor.executescript(sql_as_string) print(df_output) df_output.to_csv(f'{path}/stats_{date}.csv', index=False) print("SQL scripts complete.") def main(): data_path = pick_path() database_pipeline(data_path) if __name__ == '__main__': main()
import re from io import StringIO from pathlib import Path import warnings from typing import TextIO, Optional def dump_parameters_text(PARAMETERS: dict, file: Optional[TextIO] = None): from .parameters import Parameter, SequenceParameter, PlaceholderParameter for path, param in PARAMETERS.items(): path: str param: Parameter is_list = isinstance(param, SequenceParameter) if len(param.types) == 1: type_str = param.types[0].__name__ if is_list: type_str = f"of {type_str}" else: type_str = ", ".join(t.__name__ for t in param.types) if is_list: type_str = f"of one of {type_str}" if is_list: length_str = " or ".join(str(l) for l in param.lengths) type_str = f"list of length {length_str} {type_str}" print(f"{path} (type: {type_str})", file=file) def dump_parameters_md(file: Optional[TextIO] = None): from .parameters import PARAMETERS, Parameter, SequenceParameter, PlaceholderParameter from .expression import EXPRESSION_ARGS for path, param in PARAMETERS.items(): path: str param: Parameter is_list = isinstance(param, SequenceParameter) is_section = isinstance(param, PlaceholderParameter) is_single_param = not any(filter( lambda p: p.startswith(path + "."), PARAMETERS.keys() )) and ( path.startswith("targets.transforms.") and len(path.split(".")) == 3 ) is_new_section = is_section and len(path.split(".")) <= 2 if is_new_section: print("\n\n---\n\n", file=file) if is_section: print(f"### `{path}`\n", file=file) if param.doc: print(prepare_doc_string(param.doc) + "\n", file=file) else: warnings.warn(f"No documentation of '{path}'") continue if is_single_param: print(f"### `{path}`\n", file=file) else: print(f"#### `{path}`\n", file=file) if len(param.types) == 1: type_str = param.types[0].__name__ if is_list: type_str = f"of {type_str}" else: type_str = ", ".join(t.__name__ for t in param.types) if is_list: type_str = f"of one of {type_str}" if is_list: length_str = " or ".join(str(l) for l in param.lengths) type_str = f"list of length {length_str} {type_str}" if param.default is None: default_str = "no default" else: default_str = f"default: **`{param.default}`**" print(f"`{type_str}` {default_str}\n", file=file) if param.expression_groups: group_names = [ EXPRESSION_ARGS[n]["name"] for n in sorted(set(param.expression_groups)) ] print("\nexpression variables: " + ", ".join( f"[{n}](expressions.md#{n.replace(" ", "-")}-variables)" for n in group_names ) + "\n", file=file) if param.doc: print(prepare_doc_string(param.doc) + "\n", file=file) else: warnings.warn(f"No documentation of '{path}'") def prepare_doc_string(doc: str, indent: int = 0) -> str: doc = strip_doc(doc) links = { "CLIPig": "https://github.com/defgsus/CLIPig/", "CLIP": "https://github.com/openai/CLIP/", "gaussian blur": "https://en.wikipedia.org/wiki/Gaussian_blur", } def _repl(m): key, suffix = m.groups() return f"[{key}]({links[key]}){suffix}" for key, href in links.items(): doc = re.sub(f"({key})([\s\-\.'])", _repl, doc) if indent: doc = "\n".join( " " * indent + line for line in doc.splitlines() ) return doc def strip_doc(doc: Optional[str]) -> Optional[str]: if not doc: return doc min_lstrip = min( len(line) - len(line.lstrip()) for line in doc.splitlines() if line.strip() ) doc = "\n".join( line[min_lstrip:] for line in doc.splitlines() ) return doc.strip() def render_markdown_documentation(template: str) -> str: template = prepare_doc_string(template) for key, render_func in ( ("transforms", dump_transforms), ("constraints", dump_constraints), ("variables", dump_expression_variables), ("reference", dump_parameters_md), ): file = StringIO() render_func(file=file) file.seek(0) text = file.read() template = template.replace("{{%s}}" % key, text) return template def dump_constraints(file: Optional[TextIO] = None): from .constraints import constraints for name in sorted(constraints): klass = constraints[name] text = klass.__doc__.strip() if "\n\n" in text: text = text[:text.index("\n\n")] print(f"- [{name}](reference.md#targetsconstraints{name}): {text}", file=file) def dump_transforms(file: Optional[TextIO] = None): from .transforms import transformations for name in sorted(transformations): klass = transformations[name] text = klass.__doc__.strip() if "\n\n" in text: text = text[:text.index("\n\n")] print(f"- [{name}](reference.md#targetstransforms{name}): {text}", file=file) def dump_expression_variables(file: Optional[TextIO] = None): from .expression import EXPRESSION_ARGS for group_id, group in EXPRESSION_ARGS.items(): print(f"### {group["name"]} variables\n", file=file) print(prepare_doc_string(group["doc"]) + "\n", file=file) for variable_name, variable in group["args"].items(): if not variable.get("doc"): continue print(f"#### `{variable_name}` variable\n", file=file) print(f"type: `{variable["type"]}`\n", file=file) print(prepare_doc_string(variable["doc"]), file=file)
import re from io import StringIO from pathlib import Path import warnings from typing import TextIO, Optional def dump_parameters_text(PARAMETERS: dict, file: Optional[TextIO] = None): from .parameters import Parameter, SequenceParameter, PlaceholderParameter for path, param in PARAMETERS.items(): path: str param: Parameter is_list = isinstance(param, SequenceParameter) if len(param.types) == 1: type_str = param.types[0].__name__ if is_list: type_str = f"of {type_str}" else: type_str = ", ".join(t.__name__ for t in param.types) if is_list: type_str = f"of one of {type_str}" if is_list: length_str = " or ".join(str(l) for l in param.lengths) type_str = f"list of length {length_str} {type_str}" print(f"{path} (type: {type_str})", file=file) def dump_parameters_md(file: Optional[TextIO] = None): from .parameters import PARAMETERS, Parameter, SequenceParameter, PlaceholderParameter from .expression import EXPRESSION_ARGS for path, param in PARAMETERS.items(): path: str param: Parameter is_list = isinstance(param, SequenceParameter) is_section = isinstance(param, PlaceholderParameter) is_single_param = not any(filter( lambda p: p.startswith(path + "."), PARAMETERS.keys() )) and ( path.startswith("targets.transforms.") and len(path.split(".")) == 3 ) is_new_section = is_section and len(path.split(".")) <= 2 if is_new_section: print("\n\n---\n\n", file=file) if is_section: print(f"### `{path}`\n", file=file) if param.doc: print(prepare_doc_string(param.doc) + "\n", file=file) else: warnings.warn(f"No documentation of '{path}'") continue if is_single_param: print(f"### `{path}`\n", file=file) else: print(f"#### `{path}`\n", file=file) if len(param.types) == 1: type_str = param.types[0].__name__ if is_list: type_str = f"of {type_str}" else: type_str = ", ".join(t.__name__ for t in param.types) if is_list: type_str = f"of one of {type_str}" if is_list: length_str = " or ".join(str(l) for l in param.lengths) type_str = f"list of length {length_str} {type_str}" if param.default is None: default_str = "no default" else: default_str = f"default: **`{param.default}`**" print(f"`{type_str}` {default_str}\n", file=file) if param.expression_groups: group_names = [ EXPRESSION_ARGS[n]["name"] for n in sorted(set(param.expression_groups)) ] print("\nexpression variables: " + ", ".join( f"[{n}](expressions.md#{n.replace(' ', '-')}-variables)" for n in group_names ) + "\n", file=file) if param.doc: print(prepare_doc_string(param.doc) + "\n", file=file) else: warnings.warn(f"No documentation of '{path}'") def prepare_doc_string(doc: str, indent: int = 0) -> str: doc = strip_doc(doc) links = { "CLIPig": "https://github.com/defgsus/CLIPig/", "CLIP": "https://github.com/openai/CLIP/", "gaussian blur": "https://en.wikipedia.org/wiki/Gaussian_blur", } def _repl(m): key, suffix = m.groups() return f"[{key}]({links[key]}){suffix}" for key, href in links.items(): doc = re.sub(f"({key})([\s\-\.'])", _repl, doc) if indent: doc = "\n".join( " " * indent + line for line in doc.splitlines() ) return doc def strip_doc(doc: Optional[str]) -> Optional[str]: if not doc: return doc min_lstrip = min( len(line) - len(line.lstrip()) for line in doc.splitlines() if line.strip() ) doc = "\n".join( line[min_lstrip:] for line in doc.splitlines() ) return doc.strip() def render_markdown_documentation(template: str) -> str: template = prepare_doc_string(template) for key, render_func in ( ("transforms", dump_transforms), ("constraints", dump_constraints), ("variables", dump_expression_variables), ("reference", dump_parameters_md), ): file = StringIO() render_func(file=file) file.seek(0) text = file.read() template = template.replace("{{%s}}" % key, text) return template def dump_constraints(file: Optional[TextIO] = None): from .constraints import constraints for name in sorted(constraints): klass = constraints[name] text = klass.__doc__.strip() if "\n\n" in text: text = text[:text.index("\n\n")] print(f"- [{name}](reference.md#targetsconstraints{name}): {text}", file=file) def dump_transforms(file: Optional[TextIO] = None): from .transforms import transformations for name in sorted(transformations): klass = transformations[name] text = klass.__doc__.strip() if "\n\n" in text: text = text[:text.index("\n\n")] print(f"- [{name}](reference.md#targetstransforms{name}): {text}", file=file) def dump_expression_variables(file: Optional[TextIO] = None): from .expression import EXPRESSION_ARGS for group_id, group in EXPRESSION_ARGS.items(): print(f"### {group['name']} variables\n", file=file) print(prepare_doc_string(group["doc"]) + "\n", file=file) for variable_name, variable in group["args"].items(): if not variable.get("doc"): continue print(f"#### `{variable_name}` variable\n", file=file) print(f"type: `{variable['type']}`\n", file=file) print(prepare_doc_string(variable["doc"]), file=file)
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 from neptune_load.sigv4_signer.sigv4_signer import SigV4Signer from neptune_load.bulk_loader.bulk_loader import BulkLoader import logging import os import sys logger = logging.getLogger("bulk_load") logger.setLevel(logging.INFO) def kill_all_active(loader: BulkLoader): loads = loader.get_active_loads() logger.info(f"Loading {loads}") for load in loads: loader._load_id = load try: loader.cancel_load() except Exception as e: logger.warn(f"Failed to cancel {load} {e}") loader._load_id = None return if __name__ == "__main__": # parse_input_and_query_neptune() host = f'{os.getenv('NEPTUNE_ENDPOINT')}:8182' source_bucket = os.getenv("S3_BUCKET") loader_role = os.getenv("NEPTUNE_LOADER_IAM_ROLE") region = os.getenv("SERVICE_REGION") file_name = os.getenv("TRIPLE_NAME") source_string = f"s3://{source_bucket}/{file_name}" signer = SigV4Signer() loader = BulkLoader( signer=signer, iam_role_arn=loader_role, region=region, source=source_string, neptune_endpoint=host, ) loads = loader.get_active_loads() logger.info(f"Loading {loads}") kill_all_active(loader) try: loader.wait_for_bulk_load_from_s3() except KeyboardInterrupt as ke: logger.info(f"Cancellation requested") loader.cancel_load() logger.info(f"Final status \n {loader.status.raw}") sys.exit() logger.info(f"Load complete") logger.info(f"Results {loader.status.raw}")
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 from neptune_load.sigv4_signer.sigv4_signer import SigV4Signer from neptune_load.bulk_loader.bulk_loader import BulkLoader import logging import os import sys logger = logging.getLogger("bulk_load") logger.setLevel(logging.INFO) def kill_all_active(loader: BulkLoader): loads = loader.get_active_loads() logger.info(f"Loading {loads}") for load in loads: loader._load_id = load try: loader.cancel_load() except Exception as e: logger.warn(f"Failed to cancel {load} {e}") loader._load_id = None return if __name__ == "__main__": # parse_input_and_query_neptune() host = f'{os.getenv("NEPTUNE_ENDPOINT")}:8182' source_bucket = os.getenv("S3_BUCKET") loader_role = os.getenv("NEPTUNE_LOADER_IAM_ROLE") region = os.getenv("SERVICE_REGION") file_name = os.getenv("TRIPLE_NAME") source_string = f"s3://{source_bucket}/{file_name}" signer = SigV4Signer() loader = BulkLoader( signer=signer, iam_role_arn=loader_role, region=region, source=source_string, neptune_endpoint=host, ) loads = loader.get_active_loads() logger.info(f"Loading {loads}") kill_all_active(loader) try: loader.wait_for_bulk_load_from_s3() except KeyboardInterrupt as ke: logger.info(f"Cancellation requested") loader.cancel_load() logger.info(f"Final status \n {loader.status.raw}") sys.exit() logger.info(f"Load complete") logger.info(f"Results {loader.status.raw}")
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ """ 对主机信息进行批量对账检查 """ import logging from collection.cmdb.datacheck.base import CMDBBaseCheckerMixin from collection.cmdb.set_info import CMDBSetInfoCollector from collection.conf.constants import BKDATA_BIZ_ID, CMDB_SET_TABLE_NAME logger = logging.getLogger(__name__) collect_cmdb_set_config = {"bk_biz_id": 591, "raw_data_name": "bkpub_cmdb_set"} class CMDBSetInfoChecker(CMDBSetInfoCollector, CMDBBaseCheckerMixin): key_name = "bk_set_id" def __init__(self, config=None, init_producer=False): super(CMDBSetInfoChecker, self).__init__(config, init_producer=init_producer) if "rt_id" in config: self.rt_id = config["rt_id"] else: self.rt_id = f"{config["bk_biz_id"]}_{config["raw_data_name"]}" def check_cmdb_set_info(params=None): if not params: params = {"bk_biz_id": BKDATA_BIZ_ID, "raw_data_name": CMDB_SET_TABLE_NAME} c = CMDBSetInfoChecker(config=params) c.check_all_biz() def check_cmdb_set_info_by_one(bk_biz_id): params = {"bk_biz_id": BKDATA_BIZ_ID, "raw_data_name": CMDB_SET_TABLE_NAME} c = CMDBSetInfoChecker(config=params) c.check_biz(bk_biz_id) if __name__ == "__main__": check_cmdb_set_info()
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ """ 对主机信息进行批量对账检查 """ import logging from collection.cmdb.datacheck.base import CMDBBaseCheckerMixin from collection.cmdb.set_info import CMDBSetInfoCollector from collection.conf.constants import BKDATA_BIZ_ID, CMDB_SET_TABLE_NAME logger = logging.getLogger(__name__) collect_cmdb_set_config = {"bk_biz_id": 591, "raw_data_name": "bkpub_cmdb_set"} class CMDBSetInfoChecker(CMDBSetInfoCollector, CMDBBaseCheckerMixin): key_name = "bk_set_id" def __init__(self, config=None, init_producer=False): super(CMDBSetInfoChecker, self).__init__(config, init_producer=init_producer) if "rt_id" in config: self.rt_id = config["rt_id"] else: self.rt_id = f"{config['bk_biz_id']}_{config['raw_data_name']}" def check_cmdb_set_info(params=None): if not params: params = {"bk_biz_id": BKDATA_BIZ_ID, "raw_data_name": CMDB_SET_TABLE_NAME} c = CMDBSetInfoChecker(config=params) c.check_all_biz() def check_cmdb_set_info_by_one(bk_biz_id): params = {"bk_biz_id": BKDATA_BIZ_ID, "raw_data_name": CMDB_SET_TABLE_NAME} c = CMDBSetInfoChecker(config=params) c.check_biz(bk_biz_id) if __name__ == "__main__": check_cmdb_set_info()
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. '''Dá para fazer em 2 linhas... for i in range(0, len(prod), 2): print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')''' produtos = ('caneta', 2, 'Relogio', 23, 'remedio', 12, 'mouse', 10, 'pão', 2, "mascara", 3, "gabinete", 245, "alcool", 11) print(f'{'Listagem de preços':^30}') # Centralizando o topo for i in range(0, len(produtos), 2): # FAZENDO O PRINT DAS INFORMAÇÕES COM FOR PULANDO DE 2 EM 2 PRA PEGAR A ORDEM CORRETA print(f'{str(produtos[i]).upper():.<24}', end='') # TRANSFORMADO EM STR, CENTRALIZADO A DIREITA COM PONTO ENCHENDO O ESPAÇO print(f'R${produtos[i+1]:>6.2f} ') # ADICIONADO 1 NO INDICE PRA COMEÇAR DO SEGUINTE E MSOTRAR TODOS OS PREÇOS.
# Crie um programa que tenha uma Tupla unica com nomes de produtos e seus respectivos preços na sequencia. # No final, mostre uma listagem de preços, organizando os dados em forma tabular. '''Dá para fazer em 2 linhas... for i in range(0, len(prod), 2): print(f'{prod[i]:.<30}R${prod[i + 1]:7.2f}')''' produtos = ('caneta', 2, 'Relogio', 23, 'remedio', 12, 'mouse', 10, 'pão', 2, "mascara", 3, "gabinete", 245, "alcool", 11) print(f'{"Listagem de preços":^30}') # Centralizando o topo for i in range(0, len(produtos), 2): # FAZENDO O PRINT DAS INFORMAÇÕES COM FOR PULANDO DE 2 EM 2 PRA PEGAR A ORDEM CORRETA print(f'{str(produtos[i]).upper():.<24}', end='') # TRANSFORMADO EM STR, CENTRALIZADO A DIREITA COM PONTO ENCHENDO O ESPAÇO print(f'R${produtos[i+1]:>6.2f} ') # ADICIONADO 1 NO INDICE PRA COMEÇAR DO SEGUINTE E MSOTRAR TODOS OS PREÇOS.
# Inspired in # https://github.com/grizzlypeaksoftware/Flask-Stock-Widget # https://github.com/rubenafo/yfMongo import sys, os import re import csv import json from datetime import datetime, date, time, timedelta from itertools import zip_longest import numpy as np import pytz import yfinance as yf import ast import copy from flask import jsonify from pymongo import * from pandas_datareader import data as pdr class mongoYfinance: mongoClient = None yfdb = None verbose = False # # Used to print messages only if the verbose flag was enabled # def sprint(self, msg): if self.verbose: print(msg) # # Generic function to check all user input dates # The format must be dd/mm/yyyy and cannot be a date in the future. # In case of error the execution of the application is stopped. # def __checkDate(self, date): try: inputDate = datetime.strptime(date, "%Y/%m/%d") currentTime = datetime.now() if (inputDate > currentTime): self.sprint("Error: provided date (" + date + ") is in the future") exit() except ValueError: self.sprint("Error: invalid provided date format (expected yyyy/mm/dd)") exit() # # Given a symbol document in the mongodb this returns the date it contains. # def __getFormattedDate(self, symbol): try: # print(symbol['Datetime']) # return datetime.date(symbol['Datetime'], "%Y-%m-%d") return symbol['_id']['Datetime'] except ValueError: self.sprint("Error: invalid provided date format (expected yyyy/mm/dd)") # # Initialises the ddbb # def __init__(self, user="admin", password="", hostname="localhost", database="yfmongo", verbose=True): userAndPass = "" if user and password: userAndPass = user + ":" + str(password) + "@" url = "mongodb+srv://" + userAndPass + hostname self.mongoClient = MongoClient(url) self.yfdb = self.mongoClient[database]; self.verbose = verbose # # Removes all content in the database (Caution!) # def clear(self, keepSymbols=False): if keepSymbols: self.sprint("Removing data ... done") self.yfdb.timeline.delete_many({}); else: self.sprint("Removing all collections [symbols and timeline] ... done") self.yfdb.timeline.delete_many({}); self.yfdb.symbols.delete_many({}); def add(self, symbol, startDate=None, endDate=None): exists = self.yfdb.symbols.count_documents({'_id.sym': symbol}) if not exists: quote = yf.Ticker(symbol) if "shortName" not in quote.info: return {'symbolExists': False, 'added': False, 'message': 'Symbol ' + symbol + ' not found in API'} self.yfdb.symbols.replace_one({'_id': {'sym': symbol}}, {'_id': {'sym': symbol}, 'shortName': quote.info['shortName']}, upsert=True) self.sprint("'" + symbol + "'" + " added to the database") oldestDate = datetime.today() - timedelta(days=6) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), symbol=symbol) result = {'symbolExists': True, 'added': True, 'message': 'Symbol ' + symbol + ' was successfully added', 'sym': symbol, 'shortName': quote.info['shortName']} else: symbols = self.yfdb.symbols.find({'_id.sym': symbol}) for s in symbols: result = {'symbolExists': True, 'added': False, 'message': 'Symbol ' + symbol + ' is already in database', 'sym': symbol, 'shortName': s['shortName']} if startDate != None: if endDate != None: self.fetchInterval(startDate, endDate, symbol) else: self.fetch(startDate, symbol) return result # # Removes a symbol from the ddbb, including all timeline entries # def remove(self, symbol): if not symbol: return {'removed': False, 'message': 'Missing symbol name'} exists = self.yfdb.symbols.count_documents({'_id.sym': symbol}) if not exists: self.sprint("Error: symbol'" + symbol + "' not in the database") return {'removed': False, 'message': 'Symbol ' + symbol + ' not found in database'} else: self.yfdb.symbols.delete_many({'_id.sym': symbol}) self.yfdb.timeline.delete_many({'_id.sym': symbol}) self.sprint("'" + symbol + "'" + " removed from the database") return {'removed': True, 'message': symbol + ' removed from the database'} # # Prints information regarding the admin info (start and end dates) # and the symbols contained in the database # def info(self): symbols = self.yfdb.symbols.find(); for symb in symbols: print(symb['sym']) print("Timeline size: " + str(self.yfdb.timeline.find().count())) print("Symbols: " + str(symbols.count())) dates = [] symbols = self.yfdb.timeline.find() for symb in symbols: date = self.__getFormattedDate(symb) dates.append(date) if dates: print("Oldest record: " + min(dates).strftime("%Y/%m/%d")) print("Most recent record: " + max(dates).strftime("%Y/%m/%d")) def listSymbols(self): symbols = self.yfdb.symbols.find() symList = {} count = 0 for s in symbols: print(s) symList[count] = {'sym': s['_id']['sym'], 'shortName': s['shortName']} count += 1 return symList # # Updates the database fetching data for all symbols since last # date in the data until today # def update(self): tickers = self.yfdb.symbols.find() for ticker in tickers: tickerTimeline = list(self.yfdb.timeline.find({'_id.sym': ticker["_id"]["sym"]})) if len(tickerTimeline) > 0: dateToday = datetime.today() oldestDate = max(map(lambda s: self.__getFormattedDate(s), tickerTimeline)) delta = dateToday - oldestDate endDate = oldestDate week_period = delta.days // 6 day_period = delta.days % 6 if week_period > 0: for i in range(1, week_period): if oldestDate is not None: endDate = endDate+timedelta(days=6) print("oldestDate:", oldestDate, "endDate:", endDate, "week_period:", week_period) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), endDate.strftime("%Y/%m/%d"), symbol=ticker["_id"]["sym"]) if week_period > 0 and day_period > 0: if oldestDate is not None: endDate = endDate + timedelta(days=day_period) print("oldestDate:", oldestDate, "endDate:", endDate, "day_period:", day_period) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), endDate.strftime("%Y/%m/%d"), symbol=ticker["_id"]["sym"]) # print(tickerTimeline) oldestDate = max(map(lambda s: self.__getFormattedDate(s), tickerTimeline)) print(oldestDate) if oldestDate is not None: self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), None, symbol=ticker["_id"]["sym"]) else: oldestDate = datetime.today() - timedelta(days=6) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), None, symbol=ticker["_id"]["sym"]) # Fetches symbol data for the interval between startDate and endDate # If the symbol is set None, all symbols found in the database are # updated. def fetchInterval(self, startDate, endDate=None, symbol=None, interval='1m'): timezone = pytz.timezone("UTC") if symbol is None: symbols = self.yfdb.symbols.find() else: symbols = self.yfdb.symbols.find(({'_id.sym': symbol})) for symbol in symbols: # download dataframe quote = yf.Ticker(symbol['_id']['sym']) # data = quote.history(start=startDate.replace("/", "-"), end=endDate.replace("/", "-"), interval=interval) if endDate is not None: data = quote.history(start=startDate.replace("/", "-"), end=endDate.replace("/", "-"), interval=interval) else: data = quote.history(start=startDate.replace("/", "-"), interval=interval) # set index to column in pandas DataFrame data.reset_index(inplace=True) data.dropna(inplace=True) self.sprint(data) if "Datetime" in data: lastTicker = self.getLastTicker(symbol['_id']['sym']) tickersNotRounded = data[data['Datetime'].dt.second > 0].index data.drop(tickersNotRounded, inplace=True) if len(data) > 0: # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") dictData = data.to_dict(orient='records') for data in dictData: data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} data.pop('Datetime', None) ids = [dt.pop("_id") for dt in dictData] operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in zip(ids, dictData)] self.yfdb.timeline.bulk_write(operations) if "Date" in data: if len(data) > 0: # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") dictData = data.to_dict(orient='records') for data in dictData: date = datetime.combine(data["Date"], datetime.min.time()) data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": date} data.pop('Date', None) self.sprint(data) ids = [dt.pop("_id") for dt in dictData] operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in zip(ids, dictData)] self.yfdb.timeline.bulk_write(operations) # update already exists in database # if lastTicker: # # storedData = timezone.localize(self.getLastTicker(symbol['sym'])) # # apiData = data["Datetime"].iat[-1].to_pydatetime().astimezone(timezone) # # print(apiData.timestamp() - storedData.timestamp()) # # if len(data) > 0 and apiData.timestamp() - storedData.timestamp() > 120: # # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # # + symbol['sym'] + "' (" + str(len(data)) + " entries)") # dictData = data.to_dict(orient='records') # # for data in dictData: # data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} # data.pop('Datetime', None) # # ids = [dt.pop("_id") for dt in dictData] # # operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in # zip(ids, dictData)] # # self.yfdb.timeline.bulk_write(operations) # # # insert new data # else: # if len(data) > 0: # # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") # dictData = data.to_dict(orient='records') # # for data in dictData: # data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} # data.pop('Datetime', None) # # ids = [dt.pop("_id") for dt in dictData] # # operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in # zip(ids, dictData)] # # self.yfdb.timeline.bulk_write(operations) def getTicker(self, symbol): # self.add(symbol) self.update() symbols = self.yfdb.timeline.find({'_id.sym': symbol}).sort('_id.Datetime', 1) volume = {} close = {} cleanSymbols = {} for s in symbols: datetimeStock = int(s['_id']['Datetime'].timestamp() * 1000) volume[datetimeStock] = s['Volume'] close[datetimeStock] = s['Close'] cleanSymbols["Close"] = close cleanSymbols["Volume"] = volume return cleanSymbols def getLastTicker(self, symbol): symbols = self.yfdb.timeline.find({'_id.sym': symbol}).sort('_id', -1).limit(1); symbolsList = list(symbols) if len(symbolsList) == 0: return None elif 'Datetime' in symbolsList[0]: return symbolsList[0]['_id']['Datetime'] else: return None def periodInterval(self, x): """ Return two variables with interval and period to be fetched from API Parameters: x - interval from each close Return: interval - interval in minutes to calculate the indicators days - period in days to fetch data from API """ match x: # case 'period': # return period in minutes, interval in days to be fetched case '1m': return 1, 6 case '5m': return 5, 59 case '15m': return 15, 59 case '30m': return 30, 59 case '1hr': return 60, 300 case '2hr': return 2 * 60, 300 case '4hr': return 4 * 60, 300 case '12hr': return 12 * 60, 300 case '1d': return 1 * 24 * 60, 300 case '5d': return 5 * 24 * 60, 1500 case '1wk': return 7 * 24 * 60, 2100 case '1mo': return 30 * 24 * 60, 9000 case _: return 5, 59 # 5, 59 is the default case if x is not found # https://www.mongodb.com/developer/article/time-series-macd-rsi/ def getIndicators(self, symbol, interval='5m'): intervalInMinutes, days = self.periodInterval(interval) self.sprint(intervalInMinutes) self.sprint(days) self.sprint(1000 * 60 * intervalInMinutes) date = datetime.today() - timedelta(days=days) self.fetchInterval(date.strftime("%Y/%m/%d"), None, symbol, interval) indicators = self.yfdb.timeline.aggregate([ { "$match": { "_id.sym": symbol, } }, { "$group": { "_id": { "sym": "$_id.sym", "Datetime": { "$subtract": [ {"$toLong": "$_id.Datetime"}, {"$mod": [{"$toLong": "$_id.Datetime"}, 1000 * 60 * intervalInMinutes]} ] } }, "close": {"$last": "$Close"}, "volume": {"$last": "$Volume"}, }, }, { "$sort": { "_id.Datetime": 1, }, }, { "$project": { "_id": 1, "price": "$close", "volume": "$volume" } }, { "$setWindowFields": { "partitionBy": "$id.sym", "sortBy": {"quantity": -1}, "output": { "count": { "$documentNumber": {} } } } }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "ema_10": { "$expMovingAvg": {"input": "$price", "N": 10}, }, "ema_20": { "$expMovingAvg": {"input": "$price", "N": 20}, }, "ema_50": { "$expMovingAvg": {"input": "$price", "N": 50}, }, "ema_100": { "$expMovingAvg": {"input": "$price", "N": 100}, }, "ema_200": { "$expMovingAvg": {"input": "$price", "N": 200}, }, "ema_12": { "$expMovingAvg": {"input": "$price", "N": 12}, }, "ema_26": { "$expMovingAvg": {"input": "$price", "N": 26}, }, }, }, }, {"$addFields": { "ema_10": { "$cond": { "if": {"$gte": ["$count", 10]}, "then": "$ema_10", "else": None } }, "ema_20": { "$cond": { "if": {"$gte": ["$count", 20]}, "then": "$ema_20", "else": None } }, "ema_12": { "$cond": { "if": {"$gte": ["$count", 12]}, "then": "$ema_12", "else": None } }, "ema_26": { "$cond": { "if": {"$gte": ["$count", 26]}, "then": "$ema_26", "else": None } }, "ema_50": { "$cond": { "if": {"$gte": ["$count", 50]}, "then": "$ema_50", "else": None } }, "ema_100": { "$cond": { "if": {"$gte": ["$count", 100]}, "then": "$ema_100", "else": None } }, "ema_200": { "$cond": { "if": {"$gte": ["$count", 200]}, "then": "$ema_200", "else": None } }, }}, {"$addFields": {"macdLine": {"$subtract": ["$ema_12", "$ema_26"]}}}, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "macdSignal": { "$expMovingAvg": {"input": "$macdLine", "N": 9}, }, }, }, }, { "$addFields": {"macdHistogram": {"$subtract": ["$macdLine", "$macdSignal"]}}, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousPrice": {"$shift": {"by": -1, "output": "$price"}}, }, }, }, # MACD Indicator # NOR, Safwan Mohd; WICKREMASINGHE, Guneratne. The profitability of # MACD and RSI trading rules in the Australian stock market. # Investment management and financial innovations, # n. 11, Iss. 4 (contin.), p. 196, 2014. { "$addFields": { "macd_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$macdLine", None]}, {"$eq": ["$macdSignal", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$gt": ["$macdLine", "$macdSignal"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$lt": ["$macdLine", "$macdSignal"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End MACD Indicator { "$addFields": { "diff": { "$subtract": ["$price", {"$ifNull": ["$previousPrice", "$price"]}], }, }, }, { "$addFields": { "gain": {"$cond": {"if": {"$gte": ["$diff", 0]}, "then": "$diff", "else": 0}}, "loss": { "$cond": { "if": {"$lte": ["$diff", 0]}, "then": {"$abs": "$diff"}, "else": 0 }, }, }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "avgGain": { "$avg": "$gain", "window": {"documents": [-14, 0]}, }, "avgLoss": { "$avg": "$loss", "window": {"documents": [-14, 0]}, }, }, }, }, { "$addFields": { "relativeStrength": { "$cond": { "if": { "$gt": ["$avgLoss", 0], }, "then": { "$cond": [ {"$eq": ["$avgLoss", -1]}, "$avgGain", {"$divide": ["$avgGain", "$avgLoss"]} ] }, "else": "$avgGain", }, }, }, }, { "$addFields": { "rsi": { "$cond": { "if": {"$gt": ["$count", 14]}, "then": { "$cond": [ # Avoid division by zero {"$eq": ["$relativeStrength", -1]}, None, { "$subtract": [ 100, {"$divide": [100, {"$add": [1, "$relativeStrength"]}]}, ] } ] }, "else": None, }, }, }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousRsi": {"$shift": {"by": -1, "output": "$rsi"}}, }, }, }, # Chande Momentum Oscillator # CHANDE, Tushar S.; KROLL, Stanley. # The new technical trader: boost your profit by plugging into the latest indicators. # John Wiley & Sons Incorporated, p. 100, 1994. { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "cmoUp": { "$sum": "$gain", "window": {"documents": [-9, 0]}, }, "cmoDown": { "$sum": "$loss", "window": {"documents": [-9, 0]}, }, }, }, }, { "$addFields": { "cmo_9": { "$cond": { "if": {"$gt": ["$count", 9]}, "then": { "$cond": [ # Avoid division by zero { "$eq": [ {"$add": ["$cmoUp", "$cmoDown"]}, 0 ] }, None, { "$multiply": [100, { "$divide": [ {"$subtract": ["$cmoUp", "$cmoDown"]}, {"$add": ["$cmoUp", "$cmoDown"]} ] }, ] } ] }, "else": None, }, }, }, }, { "$addFields": { "cmo_9_indicator": { "$switch": { "branches": [ { "case": { "$eq": ["$cmo_9", None] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$lt": ["$cmo_9", -70]}, {"$ifNull": ["$cmo_9", False]} ]}, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$and": [ {"$gt": ["$cmo_9", 70]}, {"$ifNull": ["$cmo_9", False]} ]}, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End Chande Momentum Oscillator # EMA's Indicators # DI LORENZO, Renato. Basic technical analysis of financial markets. # Milan, Italy: Springer, p. 58, 2013. { "$addFields": { "ema_10_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_20", None]}, {"$eq": ["$ema_10", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_20", "$ema_10"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_20", "$ema_10"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_20_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_50", None]}, {"$eq": ["$ema_20", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_50", "$ema_20"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_50", "$ema_20"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_50_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_100", None]}, {"$eq": ["$ema_50", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_100", "$ema_50"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_100", "$ema_50"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_100_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_200", None]}, {"$eq": ["$ema_100", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_200", "$ema_100"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_200", "$ema_100"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End EMA's Indicators # RSI Indicator # ANDERSON, Bing; LI, Shuyun. An investigation of the relative strength index. # Banks & bank systems, n. 10, Iss. 1, p. 92-96, 2015. # "Surprisingly, the trading simulation with RSI at 40 and # 60 being the buy/sell threshold performs the best # among all the parameter combinations we have tested # so far. The total profit is 5206 pips. There are 125 # trades in total. The trade with the biggest loss has a # loss of 1876 pips." { "$addFields": { "rsi_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$rsi", None]}, {"$eq": ["$previousRsi", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$gt": ["$rsi", 60]}, {"$gt": ["$previousRsi", "$rsi"]} ] }, "then": {"weight": -1, "recommendation": "Sell"}}, { "case": { "$and": [ {"$lt": ["$rsi", 40]}, {"$lt": ["$previousRsi", "$rsi"]} ] }, "then": {"weight": 1, "recommendation": "Buy"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, #End RSI Oscillator # Stochastic RSI Oscillator # CHANDE, Tushar S.; KROLL, Stanley. # The new technical trader: boost your profit by plugging into the latest indicators. # John Wiley & Sons Incorporated, p. 124, 1994. { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "rsi_stoch_low": { "$min": "$rsi", "window": {"documents": [-14, 0]}, }, "rsi_stoch_high": { "$max": "$rsi", "window": {"documents": [-14, 0]}, }, }, }, }, { "$addFields": { "rsi_stoch": { "$cond": { "if": { "$and": [ {"$gt": ["$count", 14]}, {"$gt": [{"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, 0]} ] }, "then": { "$cond": [ # Avoid division by zero { "$eq": [{"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, 0] }, None, { "$divide": [ {"$subtract": ["$rsi", "$rsi_stoch_low"]}, {"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, ] } ] }, "else": None, }, } }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousRsiStoch": {"$shift": {"by": -1, "output": "$rsi_stoch"}}, }, }, }, { "$addFields": { "rsi_stoch_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$rsi_stoch", None]}, {"$eq": ["$previousRsiStoch", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$gt": ["$rsi_stoch", 0.8]}, {"$gt": ["$previousRsiStoch", "$rsi_stoch"]}, {"$ifNull": ["$rsi_stoch", False]} ] }, "then": {"weight": -1, "recommendation": "Sell"}}, { "case": { "$and": [ {"$lt": ["$rsi_stoch", 0.2]}, {"$lt": ["$previousRsiStoch", "$rsi_stoch"]}, {"$ifNull": ["$rsi_stoch", False]} ] }, "then": {"weight": 1, "recommendation": "Buy"}}, ], "default": {"weight": 0, "recommendation": "Neutral"} } } }, }, # End Stochastic RSI Oscillator { "$addFields": { "indicators_tendency": { "$sum": [ "$macd_indicator.weight", "$cmo_9_indicator.weight", "$ema_10_indicator.weight", "$ema_20_indicator.weight", "$ema_50_indicator.weight", "$ema_100_indicator.weight", "$rsi_indicator.weight", "$rsi_stoch_indicator.weight", ] } }, }, { "$addFields": { "indicators_recommendation": { "$switch": { "branches": [ { "case": { "$gt": ["$indicators_tendency", 4] }, "then": "Strong Buy" }, { "case": { "$gt": ["$indicators_tendency", 0] }, "then": "Buy" }, { "case": { "$lt": ["$indicators_tendency", -4] }, "then": "Strong Sell" }, { "case": { "$lt": ["$indicators_tendency", 0] }, "then": "Sell" }, ], "default": "Neutral" } }, }, }, { "$addFields": { "indicators_up": { "$sum": [ { "$cond": { "if": { "$and": [ {"$gt": ["$macd_indicator.weight", 0]}, {"$ifNull": ["$macd_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$cmo_9_indicator.weight", 0]}, {"$ifNull": ["$cmo_9_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_10_indicator.weight", 0]}, {"$ifNull": ["$ema_10_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_20_indicator.weight", 0]}, {"$ifNull": ["$ema_20_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_50_indicator.weight", 0]}, {"$ifNull": ["$ema_50_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_100_indicator.weight", 0]}, {"$ifNull": ["$ema_100_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$rsi_indicator.weight", 0]}, {"$ifNull": ["$rsi_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$rsi_stoch_indicator.weight", 0]}, {"$ifNull": ["$rsi_stoch_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, ] }, "indicators_down": { "$sum": [ { "$cond": { "if": { "$and": [ {"$lt": ["$macd_indicator.weight", 0]}, {"$ifNull": ["$macd_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$cmo_9_indicator.weight", 0]}, {"$ifNull": ["$cmo_9_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_10_indicator.weight", 0]}, {"$ifNull": ["$ema_10_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_20_indicator.weight", 0]}, {"$ifNull": ["$ema_20_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_50_indicator.weight", 0]}, {"$ifNull": ["$ema_50_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_100_indicator.weight", 0]}, {"$ifNull": ["$ema_100_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$rsi_indicator.weight", 0]}, {"$ifNull": ["$rsi_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$rsi_stoch_indicator.weight", 0]}, {"$ifNull": ["$rsi_stoch_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, ] }, "indicators_neutral": { "$sum": [ { "$cond": { "if": { "$eq": ["$macd_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$cmo_9_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_10_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_20_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_50_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_100_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$rsi_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$rsi_stoch_indicator.weight", 0] }, "then": 1, "else": 0 } }, ] }, }, } ]) # self.sprint(list(indicators)) return list(indicators) # # -6 Strong Sell # # -3 Sell # # 0 Neutral # # + 3 Buy # # + 6 Strong Buy
# Inspired in # https://github.com/grizzlypeaksoftware/Flask-Stock-Widget # https://github.com/rubenafo/yfMongo import sys, os import re import csv import json from datetime import datetime, date, time, timedelta from itertools import zip_longest import numpy as np import pytz import yfinance as yf import ast import copy from flask import jsonify from pymongo import * from pandas_datareader import data as pdr class mongoYfinance: mongoClient = None yfdb = None verbose = False # # Used to print messages only if the verbose flag was enabled # def sprint(self, msg): if self.verbose: print(msg) # # Generic function to check all user input dates # The format must be dd/mm/yyyy and cannot be a date in the future. # In case of error the execution of the application is stopped. # def __checkDate(self, date): try: inputDate = datetime.strptime(date, "%Y/%m/%d") currentTime = datetime.now() if (inputDate > currentTime): self.sprint("Error: provided date (" + date + ") is in the future") exit() except ValueError: self.sprint("Error: invalid provided date format (expected yyyy/mm/dd)") exit() # # Given a symbol document in the mongodb this returns the date it contains. # def __getFormattedDate(self, symbol): try: # print(symbol['Datetime']) # return datetime.date(symbol['Datetime'], "%Y-%m-%d") return symbol['_id']['Datetime'] except ValueError: self.sprint("Error: invalid provided date format (expected yyyy/mm/dd)") # # Initialises the ddbb # def __init__(self, user="admin", password="", hostname="localhost", database="yfmongo", verbose=True): userAndPass = "" if user and password: userAndPass = user + ":" + str(password) + "@" url = "mongodb+srv://" + userAndPass + hostname self.mongoClient = MongoClient(url) self.yfdb = self.mongoClient[database]; self.verbose = verbose # # Removes all content in the database (Caution!) # def clear(self, keepSymbols=False): if keepSymbols: self.sprint("Removing data ... done") self.yfdb.timeline.delete_many({}); else: self.sprint("Removing all collections [symbols and timeline] ... done") self.yfdb.timeline.delete_many({}); self.yfdb.symbols.delete_many({}); def add(self, symbol, startDate=None, endDate=None): exists = self.yfdb.symbols.count_documents({'_id.sym': symbol}) if not exists: quote = yf.Ticker(symbol) if "shortName" not in quote.info: return {'symbolExists': False, 'added': False, 'message': 'Symbol ' + symbol + ' not found in API'} self.yfdb.symbols.replace_one({'_id': {'sym': symbol}}, {'_id': {'sym': symbol}, 'shortName': quote.info['shortName']}, upsert=True) self.sprint("'" + symbol + "'" + " added to the database") oldestDate = datetime.today() - timedelta(days=6) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), symbol=symbol) result = {'symbolExists': True, 'added': True, 'message': 'Symbol ' + symbol + ' was successfully added', 'sym': symbol, 'shortName': quote.info['shortName']} else: symbols = self.yfdb.symbols.find({'_id.sym': symbol}) for s in symbols: result = {'symbolExists': True, 'added': False, 'message': 'Symbol ' + symbol + ' is already in database', 'sym': symbol, 'shortName': s['shortName']} if startDate != None: if endDate != None: self.fetchInterval(startDate, endDate, symbol) else: self.fetch(startDate, symbol) return result # # Removes a symbol from the ddbb, including all timeline entries # def remove(self, symbol): if not symbol: return {'removed': False, 'message': 'Missing symbol name'} exists = self.yfdb.symbols.count_documents({'_id.sym': symbol}) if not exists: self.sprint("Error: symbol'" + symbol + "' not in the database") return {'removed': False, 'message': 'Symbol ' + symbol + ' not found in database'} else: self.yfdb.symbols.delete_many({'_id.sym': symbol}) self.yfdb.timeline.delete_many({'_id.sym': symbol}) self.sprint("'" + symbol + "'" + " removed from the database") return {'removed': True, 'message': symbol + ' removed from the database'} # # Prints information regarding the admin info (start and end dates) # and the symbols contained in the database # def info(self): symbols = self.yfdb.symbols.find(); for symb in symbols: print(symb['sym']) print("Timeline size: " + str(self.yfdb.timeline.find().count())) print("Symbols: " + str(symbols.count())) dates = [] symbols = self.yfdb.timeline.find() for symb in symbols: date = self.__getFormattedDate(symb) dates.append(date) if dates: print("Oldest record: " + min(dates).strftime("%Y/%m/%d")) print("Most recent record: " + max(dates).strftime("%Y/%m/%d")) def listSymbols(self): symbols = self.yfdb.symbols.find() symList = {} count = 0 for s in symbols: print(s) symList[count] = {'sym': s['_id']['sym'], 'shortName': s['shortName']} count += 1 return symList # # Updates the database fetching data for all symbols since last # date in the data until today # def update(self): tickers = self.yfdb.symbols.find() for ticker in tickers: tickerTimeline = list(self.yfdb.timeline.find({'_id.sym': ticker["_id"]["sym"]})) if len(tickerTimeline) > 0: dateToday = datetime.today() oldestDate = max(map(lambda s: self.__getFormattedDate(s), tickerTimeline)) delta = dateToday - oldestDate endDate = oldestDate week_period = delta.days // 6 day_period = delta.days % 6 if week_period > 0: for i in range(1, week_period): if oldestDate is not None: endDate = endDate+timedelta(days=6) print("oldestDate:", oldestDate, "endDate:", endDate, "week_period:", week_period) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), endDate.strftime("%Y/%m/%d"), symbol=ticker["_id"]["sym"]) if week_period > 0 and day_period > 0: if oldestDate is not None: endDate = endDate + timedelta(days=day_period) print("oldestDate:", oldestDate, "endDate:", endDate, "day_period:", day_period) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), endDate.strftime("%Y/%m/%d"), symbol=ticker["_id"]["sym"]) # print(tickerTimeline) oldestDate = max(map(lambda s: self.__getFormattedDate(s), tickerTimeline)) print(oldestDate) if oldestDate is not None: self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), None, symbol=ticker["_id"]["sym"]) else: oldestDate = datetime.today() - timedelta(days=6) self.fetchInterval(oldestDate.strftime("%Y/%m/%d"), None, symbol=ticker["_id"]["sym"]) # Fetches symbol data for the interval between startDate and endDate # If the symbol is set None, all symbols found in the database are # updated. def fetchInterval(self, startDate, endDate=None, symbol=None, interval='1m'): timezone = pytz.timezone("UTC") if symbol is None: symbols = self.yfdb.symbols.find() else: symbols = self.yfdb.symbols.find(({'_id.sym': symbol})) for symbol in symbols: # download dataframe quote = yf.Ticker(symbol['_id']['sym']) # data = quote.history(start=startDate.replace("/", "-"), end=endDate.replace("/", "-"), interval=interval) if endDate is not None: data = quote.history(start=startDate.replace("/", "-"), end=endDate.replace("/", "-"), interval=interval) else: data = quote.history(start=startDate.replace("/", "-"), interval=interval) # set index to column in pandas DataFrame data.reset_index(inplace=True) data.dropna(inplace=True) self.sprint(data) if "Datetime" in data: lastTicker = self.getLastTicker(symbol['_id']['sym']) tickersNotRounded = data[data['Datetime'].dt.second > 0].index data.drop(tickersNotRounded, inplace=True) if len(data) > 0: # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") dictData = data.to_dict(orient='records') for data in dictData: data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} data.pop('Datetime', None) ids = [dt.pop("_id") for dt in dictData] operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in zip(ids, dictData)] self.yfdb.timeline.bulk_write(operations) if "Date" in data: if len(data) > 0: # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") dictData = data.to_dict(orient='records') for data in dictData: date = datetime.combine(data["Date"], datetime.min.time()) data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": date} data.pop('Date', None) self.sprint(data) ids = [dt.pop("_id") for dt in dictData] operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in zip(ids, dictData)] self.yfdb.timeline.bulk_write(operations) # update already exists in database # if lastTicker: # # storedData = timezone.localize(self.getLastTicker(symbol['sym'])) # # apiData = data["Datetime"].iat[-1].to_pydatetime().astimezone(timezone) # # print(apiData.timestamp() - storedData.timestamp()) # # if len(data) > 0 and apiData.timestamp() - storedData.timestamp() > 120: # # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # # + symbol['sym'] + "' (" + str(len(data)) + " entries)") # dictData = data.to_dict(orient='records') # # for data in dictData: # data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} # data.pop('Datetime', None) # # ids = [dt.pop("_id") for dt in dictData] # # operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in # zip(ids, dictData)] # # self.yfdb.timeline.bulk_write(operations) # # # insert new data # else: # if len(data) > 0: # # self.sprint("Adding '[" + startDate + ", " + endDate + "]' data for symbol '" # # + symbol['_id']['sym'] + "' (" + str(len(data)) + " entries)") # dictData = data.to_dict(orient='records') # # for data in dictData: # data["_id"] = {"sym": symbol['_id']['sym'], "Datetime": data["Datetime"]} # data.pop('Datetime', None) # # ids = [dt.pop("_id") for dt in dictData] # # operations = [UpdateOne({"_id": idn}, {'$set': dt}, upsert=True) for idn, dt in # zip(ids, dictData)] # # self.yfdb.timeline.bulk_write(operations) def getTicker(self, symbol): # self.add(symbol) self.update() symbols = self.yfdb.timeline.find({'_id.sym': symbol}).sort('_id.Datetime', 1) volume = {} close = {} cleanSymbols = {} for s in symbols: datetimeStock = int(s['_id']['Datetime'].timestamp() * 1000) volume[datetimeStock] = s['Volume'] close[datetimeStock] = s['Close'] cleanSymbols["Close"] = close cleanSymbols["Volume"] = volume return cleanSymbols def getLastTicker(self, symbol): symbols = self.yfdb.timeline.find({'_id.sym': symbol}).sort('_id', -1).limit(1); symbolsList = list(symbols) if len(symbolsList) == 0: return None elif 'Datetime' in symbolsList[0]: return symbolsList[0]['_id']['Datetime'] else: return None def periodInterval(self, x): """ Return two variables with interval and period to be fetched from API Parameters: x - interval from each close Return: interval - interval in minutes to calculate the indicators days - period in days to fetch data from API """ match x: # case 'period': # return period in minutes, interval in days to be fetched case '1m': return 1, 6 case '5m': return 5, 59 case '15m': return 15, 59 case '30m': return 30, 59 case '1hr': return 60, 300 case '2hr': return 2 * 60, 300 case '4hr': return 4 * 60, 300 case '12hr': return 12 * 60, 300 case '1d': return 1 * 24 * 60, 300 case '5d': return 5 * 24 * 60, 1500 case '1wk': return 7 * 24 * 60, 2100 case '1mo': return 30 * 24 * 60, 9000 case _: return 5, 59 # 5, 59 is the default case if x is not found # https://www.mongodb.com/developer/article/time-series-macd-rsi/ def getIndicators(self, symbol, interval='5m'): intervalInMinutes, days = self.periodInterval(interval) self.sprint(intervalInMinutes) self.sprint(days) self.sprint(1000 * 60 * intervalInMinutes) date = datetime.today() - timedelta(days=days) self.fetchInterval(date.strftime("%Y/%m/%d"), None, symbol, interval) indicators = self.yfdb.timeline.aggregate([ { "$match": { "_id.sym": symbol, } }, { "$group": { "_id": { "sym": "$_id.sym", "Datetime": { "$subtract": [ {"$toLong": "$_id.Datetime"}, {"$mod": [{"$toLong": "$_id.Datetime"}, 1000 * 60 * intervalInMinutes]} ] } }, "close": {"$last": "$Close"}, "volume": {"$last": "$Volume"}, }, }, { "$sort": { "_id.Datetime": 1, }, }, { "$project": { "_id": 1, "price": "$close", "volume": "$volume" } }, { "$setWindowFields": { "partitionBy": "$id.sym", "sortBy": {"quantity": -1}, "output": { "count": { "$documentNumber": {} } } } }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "ema_10": { "$expMovingAvg": {"input": "$price", "N": 10}, }, "ema_20": { "$expMovingAvg": {"input": "$price", "N": 20}, }, "ema_50": { "$expMovingAvg": {"input": "$price", "N": 50}, }, "ema_100": { "$expMovingAvg": {"input": "$price", "N": 100}, }, "ema_200": { "$expMovingAvg": {"input": "$price", "N": 200}, }, "ema_12": { "$expMovingAvg": {"input": "$price", "N": 12}, }, "ema_26": { "$expMovingAvg": {"input": "$price", "N": 26}, }, }, }, }, {"$addFields": { "ema_10": { "$cond": { "if": {"$gte": ["$count", 10]}, "then": "$ema_10", "else": None } }, "ema_20": { "$cond": { "if": {"$gte": ["$count", 20]}, "then": "$ema_20", "else": None } }, "ema_12": { "$cond": { "if": {"$gte": ["$count", 12]}, "then": "$ema_12", "else": None } }, "ema_26": { "$cond": { "if": {"$gte": ["$count", 26]}, "then": "$ema_26", "else": None } }, "ema_50": { "$cond": { "if": {"$gte": ["$count", 50]}, "then": "$ema_50", "else": None } }, "ema_100": { "$cond": { "if": {"$gte": ["$count", 100]}, "then": "$ema_100", "else": None } }, "ema_200": { "$cond": { "if": {"$gte": ["$count", 200]}, "then": "$ema_200", "else": None } }, }}, {"$addFields": {"macdLine": {"$subtract": ["$ema_12", "$ema_26"]}}}, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "macdSignal": { "$expMovingAvg": {"input": "$macdLine", "N": 9}, }, }, }, }, { "$addFields": {"macdHistogram": {"$subtract": ["$macdLine", "$macdSignal"]}}, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousPrice": {"$shift": {"by": -1, "output": "$price"}}, }, }, }, # MACD Indicator # NOR, Safwan Mohd; WICKREMASINGHE, Guneratne. The profitability of # MACD and RSI trading rules in the Australian stock market. # Investment management and financial innovations, # n. 11, Iss. 4 (contin.), p. 196, 2014. { "$addFields": { "macd_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$macdLine", None]}, {"$eq": ["$macdSignal", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$gt": ["$macdLine", "$macdSignal"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$lt": ["$macdLine", "$macdSignal"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End MACD Indicator { "$addFields": { "diff": { "$subtract": ["$price", {"$ifNull": ["$previousPrice", "$price"]}], }, }, }, { "$addFields": { "gain": {"$cond": {"if": {"$gte": ["$diff", 0]}, "then": "$diff", "else": 0}}, "loss": { "$cond": { "if": {"$lte": ["$diff", 0]}, "then": {"$abs": "$diff"}, "else": 0 }, }, }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "avgGain": { "$avg": "$gain", "window": {"documents": [-14, 0]}, }, "avgLoss": { "$avg": "$loss", "window": {"documents": [-14, 0]}, }, }, }, }, { "$addFields": { "relativeStrength": { "$cond": { "if": { "$gt": ["$avgLoss", 0], }, "then": { "$cond": [ {"$eq": ["$avgLoss", -1]}, "$avgGain", {"$divide": ["$avgGain", "$avgLoss"]} ] }, "else": "$avgGain", }, }, }, }, { "$addFields": { "rsi": { "$cond": { "if": {"$gt": ["$count", 14]}, "then": { "$cond": [ # Avoid division by zero {"$eq": ["$relativeStrength", -1]}, None, { "$subtract": [ 100, {"$divide": [100, {"$add": [1, "$relativeStrength"]}]}, ] } ] }, "else": None, }, }, }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousRsi": {"$shift": {"by": -1, "output": "$rsi"}}, }, }, }, # Chande Momentum Oscillator # CHANDE, Tushar S.; KROLL, Stanley. # The new technical trader: boost your profit by plugging into the latest indicators. # John Wiley & Sons Incorporated, p. 100, 1994. { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "cmoUp": { "$sum": "$gain", "window": {"documents": [-9, 0]}, }, "cmoDown": { "$sum": "$loss", "window": {"documents": [-9, 0]}, }, }, }, }, { "$addFields": { "cmo_9": { "$cond": { "if": {"$gt": ["$count", 9]}, "then": { "$cond": [ # Avoid division by zero { "$eq": [ {"$add": ["$cmoUp", "$cmoDown"]}, 0 ] }, None, { "$multiply": [100, { "$divide": [ {"$subtract": ["$cmoUp", "$cmoDown"]}, {"$add": ["$cmoUp", "$cmoDown"]} ] }, ] } ] }, "else": None, }, }, }, }, { "$addFields": { "cmo_9_indicator": { "$switch": { "branches": [ { "case": { "$eq": ["$cmo_9", None] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$lt": ["$cmo_9", -70]}, {"$ifNull": ["$cmo_9", False]} ]}, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$and": [ {"$gt": ["$cmo_9", 70]}, {"$ifNull": ["$cmo_9", False]} ]}, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End Chande Momentum Oscillator # EMA's Indicators # DI LORENZO, Renato. Basic technical analysis of financial markets. # Milan, Italy: Springer, p. 58, 2013. { "$addFields": { "ema_10_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_20", None]}, {"$eq": ["$ema_10", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_20", "$ema_10"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_20", "$ema_10"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_20_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_50", None]}, {"$eq": ["$ema_20", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_50", "$ema_20"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_50", "$ema_20"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_50_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_100", None]}, {"$eq": ["$ema_50", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_100", "$ema_50"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_100", "$ema_50"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, "ema_100_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$ema_200", None]}, {"$eq": ["$ema_100", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$lt": ["$ema_200", "$ema_100"] }, "then": {"weight": 1, "recommendation": "Buy"} }, { "case": { "$gt": ["$ema_200", "$ema_100"] }, "then": {"weight": -1, "recommendation": "Sell"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, # End EMA's Indicators # RSI Indicator # ANDERSON, Bing; LI, Shuyun. An investigation of the relative strength index. # Banks & bank systems, n. 10, Iss. 1, p. 92-96, 2015. # "Surprisingly, the trading simulation with RSI at 40 and # 60 being the buy/sell threshold performs the best # among all the parameter combinations we have tested # so far. The total profit is 5206 pips. There are 125 # trades in total. The trade with the biggest loss has a # loss of 1876 pips." { "$addFields": { "rsi_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$rsi", None]}, {"$eq": ["$previousRsi", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$gt": ["$rsi", 60]}, {"$gt": ["$previousRsi", "$rsi"]} ] }, "then": {"weight": -1, "recommendation": "Sell"}}, { "case": { "$and": [ {"$lt": ["$rsi", 40]}, {"$lt": ["$previousRsi", "$rsi"]} ] }, "then": {"weight": 1, "recommendation": "Buy"} }, ], "default": {"weight": 0, "recommendation": "Neutral"} } }, }, }, #End RSI Oscillator # Stochastic RSI Oscillator # CHANDE, Tushar S.; KROLL, Stanley. # The new technical trader: boost your profit by plugging into the latest indicators. # John Wiley & Sons Incorporated, p. 124, 1994. { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "rsi_stoch_low": { "$min": "$rsi", "window": {"documents": [-14, 0]}, }, "rsi_stoch_high": { "$max": "$rsi", "window": {"documents": [-14, 0]}, }, }, }, }, { "$addFields": { "rsi_stoch": { "$cond": { "if": { "$and": [ {"$gt": ["$count", 14]}, {"$gt": [{"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, 0]} ] }, "then": { "$cond": [ # Avoid division by zero { "$eq": [{"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, 0] }, None, { "$divide": [ {"$subtract": ["$rsi", "$rsi_stoch_low"]}, {"$subtract": ["$rsi_stoch_high", "$rsi_stoch_low"]}, ] } ] }, "else": None, }, } }, }, { "$setWindowFields": { "partitionBy": "$_id.sym", "sortBy": {"_id.Datetime": 1}, "output": { "previousRsiStoch": {"$shift": {"by": -1, "output": "$rsi_stoch"}}, }, }, }, { "$addFields": { "rsi_stoch_indicator": { "$switch": { "branches": [ { "case": { "$or": [ {"$eq": ["$rsi_stoch", None]}, {"$eq": ["$previousRsiStoch", None]} ] }, "then": {"weight": None, "recommendation": None} }, { "case": { "$and": [ {"$gt": ["$rsi_stoch", 0.8]}, {"$gt": ["$previousRsiStoch", "$rsi_stoch"]}, {"$ifNull": ["$rsi_stoch", False]} ] }, "then": {"weight": -1, "recommendation": "Sell"}}, { "case": { "$and": [ {"$lt": ["$rsi_stoch", 0.2]}, {"$lt": ["$previousRsiStoch", "$rsi_stoch"]}, {"$ifNull": ["$rsi_stoch", False]} ] }, "then": {"weight": 1, "recommendation": "Buy"}}, ], "default": {"weight": 0, "recommendation": "Neutral"} } } }, }, # End Stochastic RSI Oscillator { "$addFields": { "indicators_tendency": { "$sum": [ "$macd_indicator.weight", "$cmo_9_indicator.weight", "$ema_10_indicator.weight", "$ema_20_indicator.weight", "$ema_50_indicator.weight", "$ema_100_indicator.weight", "$rsi_indicator.weight", "$rsi_stoch_indicator.weight", ] } }, }, { "$addFields": { "indicators_recommendation": { "$switch": { "branches": [ { "case": { "$gt": ["$indicators_tendency", 4] }, "then": "Strong Buy" }, { "case": { "$gt": ["$indicators_tendency", 0] }, "then": "Buy" }, { "case": { "$lt": ["$indicators_tendency", -4] }, "then": "Strong Sell" }, { "case": { "$lt": ["$indicators_tendency", 0] }, "then": "Sell" }, ], "default": "Neutral" } }, }, }, { "$addFields": { "indicators_up": { "$sum": [ { "$cond": { "if": { "$and": [ {"$gt": ["$macd_indicator.weight", 0]}, {"$ifNull": ["$macd_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$cmo_9_indicator.weight", 0]}, {"$ifNull": ["$cmo_9_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_10_indicator.weight", 0]}, {"$ifNull": ["$ema_10_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_20_indicator.weight", 0]}, {"$ifNull": ["$ema_20_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_50_indicator.weight", 0]}, {"$ifNull": ["$ema_50_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$ema_100_indicator.weight", 0]}, {"$ifNull": ["$ema_100_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$rsi_indicator.weight", 0]}, {"$ifNull": ["$rsi_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$gt": ["$rsi_stoch_indicator.weight", 0]}, {"$ifNull": ["$rsi_stoch_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, ] }, "indicators_down": { "$sum": [ { "$cond": { "if": { "$and": [ {"$lt": ["$macd_indicator.weight", 0]}, {"$ifNull": ["$macd_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$cmo_9_indicator.weight", 0]}, {"$ifNull": ["$cmo_9_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_10_indicator.weight", 0]}, {"$ifNull": ["$ema_10_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_20_indicator.weight", 0]}, {"$ifNull": ["$ema_20_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_50_indicator.weight", 0]}, {"$ifNull": ["$ema_50_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$ema_100_indicator.weight", 0]}, {"$ifNull": ["$ema_100_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$rsi_indicator.weight", 0]}, {"$ifNull": ["$rsi_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$and": [ {"$lt": ["$rsi_stoch_indicator.weight", 0]}, {"$ifNull": ["$rsi_stoch_indicator.weight", False]} ] }, "then": 1, "else": 0 } }, ] }, "indicators_neutral": { "$sum": [ { "$cond": { "if": { "$eq": ["$macd_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$cmo_9_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_10_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_20_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_50_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$ema_100_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$rsi_indicator.weight", 0] }, "then": 1, "else": 0 } }, { "$cond": { "if": { "$eq": ["$rsi_stoch_indicator.weight", 0] }, "then": 1, "else": 0 } }, ] }, }, } ]) # self.sprint(list(indicators)) return list(indicators) # # -6 Strong Sell # # -3 Sell # # 0 Neutral # # + 3 Buy # # + 6 Strong Buy
import logging import os from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.story_reader.story_reader import StoryReader from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) from rasa.shared.core.training_data.structures import StoryStep from rasa.shared.data import YAML_FILE_EXTENSIONS, MARKDOWN_FILE_EXTENSIONS logger = logging.getLogger(__name__) def _get_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if rasa.shared.data.is_likely_markdown_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) elif rasa.shared.data.is_likely_yaml_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) else: # This is a use case for uploading the story over REST API. # The source file has a random name. return _guess_reader(filename, domain, template_variables, use_e2e) def _guess_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if YAMLStoryReader.is_stories_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) elif MarkdownStoryReader.is_stories_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) raise ValueError( f"Failed to find a reader class for the story file `{filename}`. " f"Supported formats are " f"{", ".join(MARKDOWN_FILE_EXTENSIONS + YAML_FILE_EXTENSIONS)}." ) async def load_data_from_resource( resource: Union[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified folder. Args: resource: Folder/File with core training data files. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies if the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ if not os.path.exists(resource): raise ValueError(f"Resource '{resource}' does not exist.") return await load_data_from_files( rasa.shared.utils.io.list_files(resource), domain, template_variables, use_e2e, exclusion_percentage, ) async def load_data_from_files( story_files: List[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified files. Args: story_files: List of files with training data in it. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies whether the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ story_steps = [] for story_file in story_files: reader = _get_reader(story_file, domain, template_variables, use_e2e) steps = reader.read_from_file(story_file) story_steps.extend(steps) if exclusion_percentage and exclusion_percentage != 100: import random idx = int(round(exclusion_percentage / 100.0 * len(story_steps))) random.shuffle(story_steps) story_steps = story_steps[:-idx] return story_steps
import logging import os from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.story_reader.story_reader import StoryReader from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) from rasa.shared.core.training_data.structures import StoryStep from rasa.shared.data import YAML_FILE_EXTENSIONS, MARKDOWN_FILE_EXTENSIONS logger = logging.getLogger(__name__) def _get_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if rasa.shared.data.is_likely_markdown_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) elif rasa.shared.data.is_likely_yaml_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) else: # This is a use case for uploading the story over REST API. # The source file has a random name. return _guess_reader(filename, domain, template_variables, use_e2e) def _guess_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if YAMLStoryReader.is_stories_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) elif MarkdownStoryReader.is_stories_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) raise ValueError( f"Failed to find a reader class for the story file `{filename}`. " f"Supported formats are " f"{', '.join(MARKDOWN_FILE_EXTENSIONS + YAML_FILE_EXTENSIONS)}." ) async def load_data_from_resource( resource: Union[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified folder. Args: resource: Folder/File with core training data files. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies if the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ if not os.path.exists(resource): raise ValueError(f"Resource '{resource}' does not exist.") return await load_data_from_files( rasa.shared.utils.io.list_files(resource), domain, template_variables, use_e2e, exclusion_percentage, ) async def load_data_from_files( story_files: List[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified files. Args: story_files: List of files with training data in it. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies whether the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ story_steps = [] for story_file in story_files: reader = _get_reader(story_file, domain, template_variables, use_e2e) steps = reader.read_from_file(story_file) story_steps.extend(steps) if exclusion_percentage and exclusion_percentage != 100: import random idx = int(round(exclusion_percentage / 100.0 * len(story_steps))) random.shuffle(story_steps) story_steps = story_steps[:-idx] return story_steps
#!/usr/bin/env python3 from contextlib import contextmanager from os import path as osp import joblib import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.svm import SVC DEMO_DIR = osp.abspath(osp.dirname(__file__)) DATA_DIR = osp.join(DEMO_DIR, "data") MODELS_DIR = osp.join(DEMO_DIR, "models") @contextmanager def load_data(train=True): df = pd.read_csv(osp.join(DATA_DIR, f'iris_{'train' if train else 'test'}.csv'), header=None) df.columns = ["sepal length", "sepal width", "petal length", "petal width", "label"] X = df.drop(["label"], axis=1) y = pd.factorize(df["label"], sort=True)[0] yield X, y def main(): with load_data(train=True) as (X, y): model_a = SVC(gamma="scale") model_a.fit(X, y) model_b = AdaBoostClassifier() model_b.fit(X, y) print("train") print(f"├─ model A score: {model_a.score(X, y):.3f}") print(f"└─ model B score: {model_b.score(X, y):.3f}") with load_data(train=False) as (X, y): print("\ntest (debugging only. you wouldn't see these irl)") print(f"├─ model A score: {model_a.score(X, y):.3f}") print(f"└─ model B score: {model_b.score(X, y):.3f}") joblib.dump(model_a, osp.join(MODELS_DIR, "model_a.joblib")) joblib.dump(model_b, osp.join(MODELS_DIR, "model_b.joblib")) if __name__ == "__main__": main()
#!/usr/bin/env python3 from contextlib import contextmanager from os import path as osp import joblib import pandas as pd from sklearn.ensemble import AdaBoostClassifier from sklearn.svm import SVC DEMO_DIR = osp.abspath(osp.dirname(__file__)) DATA_DIR = osp.join(DEMO_DIR, "data") MODELS_DIR = osp.join(DEMO_DIR, "models") @contextmanager def load_data(train=True): df = pd.read_csv(osp.join(DATA_DIR, f'iris_{"train" if train else "test"}.csv'), header=None) df.columns = ["sepal length", "sepal width", "petal length", "petal width", "label"] X = df.drop(["label"], axis=1) y = pd.factorize(df["label"], sort=True)[0] yield X, y def main(): with load_data(train=True) as (X, y): model_a = SVC(gamma="scale") model_a.fit(X, y) model_b = AdaBoostClassifier() model_b.fit(X, y) print("train") print(f"├─ model A score: {model_a.score(X, y):.3f}") print(f"└─ model B score: {model_b.score(X, y):.3f}") with load_data(train=False) as (X, y): print("\ntest (debugging only. you wouldn't see these irl)") print(f"├─ model A score: {model_a.score(X, y):.3f}") print(f"└─ model B score: {model_b.score(X, y):.3f}") joblib.dump(model_a, osp.join(MODELS_DIR, "model_a.joblib")) joblib.dump(model_b, osp.join(MODELS_DIR, "model_b.joblib")) if __name__ == "__main__": main()
import pandas as pd estados = ['acre|ac', 'alagoas|al', 'amapá|ap', 'amazonas|am', 'bahia|ba', 'ceará|ce', 'espírito santo|es', 'goiás|go', 'maranhão|ma', 'mato grosso|mt', 'mato grosso do sul|ms', 'goiás|go', 'maranhão|ma', 'minas gerais|mg', 'pará|pa', 'paraíba|pb', 'paraná|pr', 'pernambuco|pe', 'piauí|pi', 'rio de janeiro|rj', 'rio grande do norte|rn', 'rio grande do sul|rs', 'rondônia|ro', 'roraima|rr', 'santa catarina|sc', 'são paulo|sp', 'sergipe|se', 'tocantins|to', 'distrito federal|df'] def contagem_palavras_especificas(arquivo, palavras): """Conta como mais de um caso os termos tenham sido mencionados no mesmo tweet. Além disso, Mato Grosso conta os dados de MS""" dados = {} df = pd.read_csv(arquivo) df = df[['date', 'tweet']] df['count'] = 1 df['tweet'] = df['tweet'].str.lower() for palavra in palavras: termo = df.loc[df['tweet'].str.contains(fr"\b({palavra})\b")].sum() termo['estado'] = palavra dados[f'{termo['estado']}'] = termo['count'] for i in sorted(dados, key= dados.get, reverse=True): print(i, dados[i]) #contagem.to_csv(novo_doc) print('Tarcisio') contagem_palavras_especificas('tarcisio.csv', estados) print('\n') print('onyx') contagem_palavras_especificas('onyx.csv', estados) print('\n') print('marinho') contagem_palavras_especificas('marinho.csv', estados) print('\n') print('TerezaCrisMS') contagem_palavras_especificas('tereza.csv', estados) print('\n') print('andersongtorres') contagem_palavras_especificas('torres.csv', estados) print('\n') print('João Roma') contagem_palavras_especificas('joao_roma.csv', estados) print('\n') print('fabiofaria') contagem_palavras_especificas('fabiofaria.csv', estados)
import pandas as pd estados = ['acre|ac', 'alagoas|al', 'amapá|ap', 'amazonas|am', 'bahia|ba', 'ceará|ce', 'espírito santo|es', 'goiás|go', 'maranhão|ma', 'mato grosso|mt', 'mato grosso do sul|ms', 'goiás|go', 'maranhão|ma', 'minas gerais|mg', 'pará|pa', 'paraíba|pb', 'paraná|pr', 'pernambuco|pe', 'piauí|pi', 'rio de janeiro|rj', 'rio grande do norte|rn', 'rio grande do sul|rs', 'rondônia|ro', 'roraima|rr', 'santa catarina|sc', 'são paulo|sp', 'sergipe|se', 'tocantins|to', 'distrito federal|df'] def contagem_palavras_especificas(arquivo, palavras): """Conta como mais de um caso os termos tenham sido mencionados no mesmo tweet. Além disso, Mato Grosso conta os dados de MS""" dados = {} df = pd.read_csv(arquivo) df = df[['date', 'tweet']] df['count'] = 1 df['tweet'] = df['tweet'].str.lower() for palavra in palavras: termo = df.loc[df['tweet'].str.contains(fr"\b({palavra})\b")].sum() termo['estado'] = palavra dados[f'{termo["estado"]}'] = termo['count'] for i in sorted(dados, key= dados.get, reverse=True): print(i, dados[i]) #contagem.to_csv(novo_doc) print('Tarcisio') contagem_palavras_especificas('tarcisio.csv', estados) print('\n') print('onyx') contagem_palavras_especificas('onyx.csv', estados) print('\n') print('marinho') contagem_palavras_especificas('marinho.csv', estados) print('\n') print('TerezaCrisMS') contagem_palavras_especificas('tereza.csv', estados) print('\n') print('andersongtorres') contagem_palavras_especificas('torres.csv', estados) print('\n') print('João Roma') contagem_palavras_especificas('joao_roma.csv', estados) print('\n') print('fabiofaria') contagem_palavras_especificas('fabiofaria.csv', estados)
from onelang_core import * import OneLang.Parsers.Common.Reader as read import OneLang.Parsers.Common.ExpressionParser as exprPars import OneLang.Parsers.Common.NodeManager as nodeMan import OneLang.Parsers.Common.IParser as iPars import OneLang.One.Ast.AstTypes as astTypes import OneLang.One.Ast.Expressions as exprs import OneLang.One.Ast.Statements as stats import OneLang.One.Ast.Types as types import OneLang.One.Ast.Interfaces as ints import re class TypeAndInit: def __init__(self, type, init): self.type = type self.init = init class MethodSignature: def __init__(self, params, fields, body, returns, super_call_args): self.params = params self.fields = fields self.body = body self.returns = returns self.super_call_args = super_call_args class TypeScriptParser2: def __init__(self, source, path = None): self.context = [] self.reader = None self.expression_parser = None self.node_manager = None self.export_scope = None self.missing_return_type_is_void = False self.allow_dollar_ids = False self.path = path self.reader = read.Reader(source) self.reader.hooks = self self.node_manager = nodeMan.NodeManager(self.reader) self.expression_parser = self.create_expression_parser(self.reader, self.node_manager) self.export_scope = types.ExportScopeRef(self.path.pkg.name, re.sub("\\.ts$", "", self.path.path) if self.path.path != None else None) if self.path != None else None def create_expression_parser(self, reader, node_manager = None): expression_parser = exprPars.ExpressionParser(reader, self, node_manager) expression_parser.string_literal_type = astTypes.UnresolvedType("TsString", []) expression_parser.numeric_literal_type = astTypes.UnresolvedType("TsNumber", []) return expression_parser def error_callback(self, error): raise Error(f'''[TypeScriptParser] {error.message} at {error.cursor.line}:{error.cursor.column} (context: {'/'.join(self.context)})\n{self.reader.line_preview(error.cursor)}''') def infix_prehook(self, left): if isinstance(left, exprs.PropertyAccessExpression) and self.reader.peek_regex("<[A-Za-z0-9_<>]*?>\\(") != None: type_args = self.parse_type_args() self.reader.expect_token("(") args = self.expression_parser.parse_call_arguments() return exprs.UnresolvedCallExpression(left, type_args, args) elif self.reader.read_token("instanceof"): type = self.parse_type() return exprs.InstanceOfExpression(left, type) elif isinstance(left, exprs.Identifier) and self.reader.read_token("=>"): block = self.parse_lambda_block() return types.Lambda([types.MethodParameter(left.text, None, None, None)], block) return None def parse_lambda_params(self): if not self.reader.read_token("("): return None params = [] if not self.reader.read_token(")"): while True: param_name = self.reader.expect_identifier() type = self.parse_type() if self.reader.read_token(":") else None params.append(types.MethodParameter(param_name, type, None, None)) if not (self.reader.read_token(",")): break self.reader.expect_token(")") return params def parse_type(self): if self.reader.read_token("{"): self.reader.expect_token("[") self.reader.read_identifier() self.reader.expect_token(":") self.reader.expect_token("string") self.reader.expect_token("]") self.reader.expect_token(":") map_value_type = self.parse_type() self.reader.read_token(";") self.reader.expect_token("}") return astTypes.UnresolvedType("TsMap", [map_value_type]) if self.reader.peek_token("("): params = self.parse_lambda_params() self.reader.expect_token("=>") return_type = self.parse_type() return astTypes.LambdaType(params, return_type) type_name = self.reader.expect_identifier() start_pos = self.reader.prev_token_offset if type_name == "string": type = astTypes.UnresolvedType("TsString", []) elif type_name == "boolean": type = astTypes.UnresolvedType("TsBoolean", []) elif type_name == "number": type = astTypes.UnresolvedType("TsNumber", []) elif type_name == "any": type = astTypes.AnyType.instance elif type_name == "void": type = astTypes.VoidType.instance else: type_arguments = self.parse_type_args() type = astTypes.UnresolvedType(type_name, type_arguments) self.node_manager.add_node(type, start_pos) while self.reader.read_token("[]"): type = astTypes.UnresolvedType("TsArray", [type]) self.node_manager.add_node(type, start_pos) return type def parse_expression(self): return self.expression_parser.parse() def unary_prehook(self): if self.reader.read_token("null"): return exprs.NullLiteral() elif self.reader.read_token("true"): return exprs.BooleanLiteral(True) elif self.reader.read_token("false"): return exprs.BooleanLiteral(False) elif self.reader.read_token("`"): parts = [] lit_part = "" while True: if self.reader.read_exactly("`"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" break elif self.reader.read_exactly("${"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" expr = self.parse_expression() parts.append(exprs.TemplateStringPart.expression(expr)) self.reader.expect_token("}") elif self.allow_dollar_ids and self.reader.read_exactly("$"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" id = self.reader.read_identifier() parts.append(exprs.TemplateStringPart.expression(exprs.Identifier(id))) elif self.reader.read_exactly("\\"): chr = self.reader.read_char() if chr == "n": lit_part += "\n" elif chr == "r": lit_part += "\r" elif chr == "t": lit_part += "\t" elif chr == "`": lit_part += "`" elif chr == "$": lit_part += "$" elif chr == "\\": lit_part += "\\" else: self.reader.fail("invalid escape", self.reader.offset - 1) else: chr = self.reader.read_char() chr_code = ord(chr[0]) if not (32 <= chr_code and chr_code <= 126) or chr == "`" or chr == "\\": self.reader.fail(f'''not allowed character (code={chr_code})''', self.reader.offset - 1) lit_part += chr return exprs.TemplateString(parts) elif self.reader.read_token("new"): type = self.parse_type() if isinstance(type, astTypes.UnresolvedType): self.reader.expect_token("(") args = self.expression_parser.parse_call_arguments() return exprs.UnresolvedNewExpression(type, args) else: raise Error(f'''[TypeScriptParser2] Expected UnresolvedType here!''') elif self.reader.read_token("<"): new_type = self.parse_type() self.reader.expect_token(">") expression = self.parse_expression() return exprs.CastExpression(new_type, expression) elif self.reader.read_token("/"): pattern = "" while True: chr = self.reader.read_char() if chr == "\\": chr2 = self.reader.read_char() pattern += "/" if chr2 == "/" else "\\" + chr2 elif chr == "/": break else: pattern += chr modifiers = self.reader.read_modifiers(["g", "i"]) return exprs.RegexLiteral(pattern, "i" in modifiers, "g" in modifiers) elif self.reader.read_token("typeof"): expr = self.expression_parser.parse(self.expression_parser.prefix_precedence) self.reader.expect_token("===") check = self.reader.expect_string() ts_type = None if check == "string": ts_type = "TsString" elif check == "boolean": ts_type = "TsBoolean" elif check == "object": ts_type = "Object" elif check == "function": # TODO: ??? ts_type = "Function" elif check == "undefined": # TODO: ??? ts_type = "Object" else: self.reader.fail("unexpected typeof comparison") return exprs.InstanceOfExpression(expr, astTypes.UnresolvedType(ts_type, [])) elif self.reader.peek_regex("\\([A-Za-z0-9_]+\\s*[:,]|\\(\\)") != None: params = self.parse_lambda_params() self.reader.expect_token("=>") block = self.parse_lambda_block() return types.Lambda(params, block) elif self.reader.read_token("await"): expression = self.parse_expression() return exprs.AwaitExpression(expression) map_literal = self.expression_parser.parse_map_literal() if map_literal != None: return map_literal array_literal = self.expression_parser.parse_array_literal() if array_literal != None: return array_literal return None def parse_lambda_block(self): block = self.parse_block() if block != None: return block return_expr = self.parse_expression() if isinstance(return_expr, exprs.ParenthesizedExpression): return_expr = return_expr.expression return stats.Block([stats.ReturnStatement(return_expr)]) def parse_type_and_init(self): type = self.parse_type() if self.reader.read_token(":") else None init = self.parse_expression() if self.reader.read_token("=") else None if type == None and init == None: self.reader.fail(f'''expected type declaration or initializer''') return TypeAndInit(type, init) def expect_block_or_statement(self): block = self.parse_block() if block != None: return block stmts = [] stmt = self.expect_statement() if stmt != None: stmts.append(stmt) return stats.Block(stmts) def expect_statement(self): statement = None leading_trivia = self.reader.read_leading_trivia() start_pos = self.reader.offset requires_closing = True var_decl_matches = self.reader.read_regex("(const|let|var)\\b") if var_decl_matches != None: name = self.reader.expect_identifier("expected variable name") type_and_init = self.parse_type_and_init() statement = stats.VariableDeclaration(name, type_and_init.type, type_and_init.init) elif self.reader.read_token("delete"): statement = stats.UnsetStatement(self.parse_expression()) elif self.reader.read_token("if"): requires_closing = False self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") then = self.expect_block_or_statement() else_ = self.expect_block_or_statement() if self.reader.read_token("else") else None statement = stats.IfStatement(condition, then, else_) elif self.reader.read_token("while"): requires_closing = False self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.WhileStatement(condition, body) elif self.reader.read_token("do"): requires_closing = False body = self.expect_block_or_statement() self.reader.expect_token("while") self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") statement = stats.DoStatement(condition, body) elif self.reader.read_token("for"): requires_closing = False self.reader.expect_token("(") var_decl_mod = self.reader.read_any_of(["const", "let", "var"]) item_var_name = None if var_decl_mod == None else self.reader.expect_identifier() if item_var_name != None and self.reader.read_token("of"): items = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.ForeachStatement(stats.ForeachVariable(item_var_name), items, body) else: for_var = None if item_var_name != None: type_and_init = self.parse_type_and_init() for_var = stats.ForVariable(item_var_name, type_and_init.type, type_and_init.init) self.reader.expect_token(";") condition = self.parse_expression() self.reader.expect_token(";") incrementor = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.ForStatement(for_var, condition, incrementor, body) elif self.reader.read_token("try"): block = self.expect_block("try body is missing") catch_var = None catch_body = None if self.reader.read_token("catch"): self.reader.expect_token("(") catch_var = stats.CatchVariable(self.reader.expect_identifier(), None) self.reader.expect_token(")") catch_body = self.expect_block("catch body is missing") finally_body = self.expect_block() if self.reader.read_token("finally") else None return stats.TryStatement(block, catch_var, catch_body, finally_body) elif self.reader.read_token("return"): expr = None if self.reader.peek_token(";") else self.parse_expression() statement = stats.ReturnStatement(expr) elif self.reader.read_token("throw"): expr = self.parse_expression() statement = stats.ThrowStatement(expr) elif self.reader.read_token("break"): statement = stats.BreakStatement() elif self.reader.read_token("continue"): statement = stats.ContinueStatement() elif self.reader.read_token("debugger;"): return None else: expr = self.parse_expression() statement = stats.ExpressionStatement(expr) is_binary_set = isinstance(expr, exprs.BinaryExpression) and expr.operator in ["=", "+=", "-="] is_unary_set = isinstance(expr, exprs.UnaryExpression) and expr.operator in ["++", "--"] if not (isinstance(expr, exprs.UnresolvedCallExpression) or is_binary_set or is_unary_set or isinstance(expr, exprs.AwaitExpression)): self.reader.fail("this expression is not allowed as statement") if statement == None: self.reader.fail("unknown statement") statement.leading_trivia = leading_trivia self.node_manager.add_node(statement, start_pos) statement_last_line = self.reader.ws_line_counter if not self.reader.read_token(";") and requires_closing and self.reader.ws_line_counter == statement_last_line: self.reader.fail("statement is not closed", self.reader.ws_offset) return statement def parse_block(self): if not self.reader.read_token("{"): return None start_pos = self.reader.prev_token_offset statements = [] if not self.reader.read_token("}"): while True: statement = self.expect_statement() if statement != None: statements.append(statement) if not (not self.reader.read_token("}")): break block = stats.Block(statements) self.node_manager.add_node(block, start_pos) return block def expect_block(self, error_msg = None): block = self.parse_block() if block == None: self.reader.fail(error_msg or "expected block here") return block def parse_type_args(self): type_arguments = [] if self.reader.read_token("<"): while True: generics = self.parse_type() type_arguments.append(generics) if not (self.reader.read_token(",")): break self.reader.expect_token(">") return type_arguments def parse_generics_args(self): type_arguments = [] if self.reader.read_token("<"): while True: generics = self.reader.expect_identifier() type_arguments.append(generics) if not (self.reader.read_token(",")): break self.reader.expect_token(">") return type_arguments def parse_expr_stmt_from_string(self, expression): expr = self.create_expression_parser(read.Reader(expression)).parse() return stats.ExpressionStatement(expr) def parse_method_signature(self, is_constructor, declaration_only): params = [] fields = [] if not self.reader.read_token(")"): while True: leading_trivia = self.reader.read_leading_trivia() param_start = self.reader.offset is_public = self.reader.read_token("public") if is_public and not is_constructor: self.reader.fail("public modifier is only allowed in constructor definition") param_name = self.reader.expect_identifier() self.context.append(f'''arg:{param_name}''') type_and_init = self.parse_type_and_init() param = types.MethodParameter(param_name, type_and_init.type, type_and_init.init, leading_trivia) params.append(param) # init should be used as only the constructor's method parameter, but not again as a field initializer too # (otherwise it would called twice if cloned or cause AST error is just referenced from two separate places) if is_public: field = types.Field(param_name, type_and_init.type, None, types.VISIBILITY.PUBLIC, False, param, param.leading_trivia) fields.append(field) param.field_decl = field self.node_manager.add_node(param, param_start) self.context.pop() if not (self.reader.read_token(",")): break self.reader.expect_token(")") returns = None if not is_constructor: # in case of constructor, "returns" won't be used returns = self.parse_type() if self.reader.read_token(":") else astTypes.VoidType.instance if self.missing_return_type_is_void else None body = None super_call_args = None if declaration_only: self.reader.expect_token(";") else: body = self.expect_block("method body is missing") first_stmt = body.statements[0] if len(body.statements) > 0 else None if isinstance(first_stmt, stats.ExpressionStatement) and isinstance(first_stmt.expression, exprs.UnresolvedCallExpression) and isinstance(first_stmt.expression.func, exprs.Identifier) and first_stmt.expression.func.text == "super": super_call_args = first_stmt.expression.args body.statements.pop(0) return MethodSignature(params, fields, body, returns, super_call_args) def parse_identifier_or_string(self): return self.reader.read_string() or self.reader.expect_identifier() def parse_interface(self, leading_trivia, is_exported): if not self.reader.read_token("interface"): return None intf_start = self.reader.prev_token_offset intf_name = self.reader.expect_identifier("expected identifier after 'interface' keyword") self.context.append(f'''I:{intf_name}''') intf_type_args = self.parse_generics_args() base_interfaces = [] if self.reader.read_token("extends"): while True: base_interfaces.append(self.parse_type()) if not (self.reader.read_token(",")): break methods = [] fields = [] self.reader.expect_token("{") while not self.reader.read_token("}"): member_leading_trivia = self.reader.read_leading_trivia() member_start = self.reader.offset member_name = self.parse_identifier_or_string() if self.reader.read_token(":"): self.context.append(f'''F:{member_name}''') field_type = self.parse_type() self.reader.expect_token(";") field = types.Field(member_name, field_type, None, types.VISIBILITY.PUBLIC, False, None, member_leading_trivia) fields.append(field) self.node_manager.add_node(field, member_start) self.context.pop() else: self.context.append(f'''M:{member_name}''') method_type_args = self.parse_generics_args() self.reader.expect_token("(") # method sig = self.parse_method_signature(False, True) method = types.Method(member_name, method_type_args, sig.params, sig.body, types.VISIBILITY.PUBLIC, False, sig.returns, False, member_leading_trivia) methods.append(method) self.node_manager.add_node(method, member_start) self.context.pop() intf = types.Interface(intf_name, intf_type_args, base_interfaces, fields, methods, is_exported, leading_trivia) self.node_manager.add_node(intf, intf_start) self.context.pop() return intf def parse_specified_type(self): type_name = self.reader.read_identifier() type_args = self.parse_type_args() return astTypes.UnresolvedType(type_name, type_args) def parse_class(self, leading_trivia, is_exported, declaration_only): cls_modifiers = self.reader.read_modifiers(["abstract"]) if not self.reader.read_token("class"): return None cls_start = self.reader.prev_token_offset cls_name = self.reader.expect_identifier("expected identifier after 'class' keyword") self.context.append(f'''C:{cls_name}''') type_args = self.parse_generics_args() base_class = self.parse_specified_type() if self.reader.read_token("extends") else None base_interfaces = [] if self.reader.read_token("implements"): while True: base_interfaces.append(self.parse_specified_type()) if not (self.reader.read_token(",")): break constructor = None fields = [] methods = [] properties = [] self.reader.expect_token("{") while not self.reader.read_token("}"): member_leading_trivia = self.reader.read_leading_trivia() member_start = self.reader.offset modifiers = self.reader.read_modifiers(["static", "public", "protected", "private", "readonly", "async", "abstract"]) is_static = "static" in modifiers is_async = "async" in modifiers is_abstract = "abstract" in modifiers visibility = types.VISIBILITY.PRIVATE if "private" in modifiers else types.VISIBILITY.PROTECTED if "protected" in modifiers else types.VISIBILITY.PUBLIC member_name = self.parse_identifier_or_string() method_type_args = self.parse_generics_args() if self.reader.read_token("("): # method is_constructor = member_name == "constructor" sig = self.parse_method_signature(is_constructor, declaration_only or is_abstract) if is_constructor: member = constructor = types.Constructor(sig.params, sig.body, sig.super_call_args, member_leading_trivia) for field in sig.fields: fields.append(field) else: method = types.Method(member_name, method_type_args, sig.params, sig.body, visibility, is_static, sig.returns, is_async, member_leading_trivia) methods.append(method) member = method self.node_manager.add_node(member, member_start) elif member_name == "get" or member_name == "set": # property prop_name = self.reader.expect_identifier() prop = next(filter(lambda x: x.name == prop_name, properties), None) prop_type = None getter = None setter = None if member_name == "get": # get propName(): propType { return ... } self.context.append(f'''P[G]:{prop_name}''') self.reader.expect_token("()", "expected '()' after property getter name") prop_type = self.parse_type() if self.reader.read_token(":") else None if declaration_only: if prop_type == None: self.reader.fail("Type is missing for property in declare class") self.reader.expect_token(";") else: getter = self.expect_block("property getter body is missing") if prop != None: prop.getter = getter elif member_name == "set": # set propName(value: propType) { ... } self.context.append(f'''P[S]:{prop_name}''') self.reader.expect_token("(", "expected '(' after property setter name") self.reader.expect_identifier() prop_type = self.parse_type() if self.reader.read_token(":") else None self.reader.expect_token(")") if declaration_only: if prop_type == None: self.reader.fail("Type is missing for property in declare class") self.reader.expect_token(";") else: setter = self.expect_block("property setter body is missing") if prop != None: prop.setter = setter if prop == None: prop = types.Property(prop_name, prop_type, getter, setter, visibility, is_static, member_leading_trivia) properties.append(prop) self.node_manager.add_node(prop, member_start) self.context.pop() else: self.context.append(f'''F:{member_name}''') type_and_init = self.parse_type_and_init() self.reader.expect_token(";") field = types.Field(member_name, type_and_init.type, type_and_init.init, visibility, is_static, None, member_leading_trivia) fields.append(field) self.node_manager.add_node(field, member_start) self.context.pop() cls_ = types.Class(cls_name, type_args, base_class, base_interfaces, fields, properties, constructor, methods, is_exported, leading_trivia) self.node_manager.add_node(cls_, cls_start) self.context.pop() return cls_ def parse_enum(self, leading_trivia, is_exported): if not self.reader.read_token("enum"): return None enum_start = self.reader.prev_token_offset name = self.reader.expect_identifier("expected identifier after 'enum' keyword") self.context.append(f'''E:{name}''') members = [] self.reader.expect_token("{") if not self.reader.read_token("}"): while True: if self.reader.peek_token("}"): break # eg. "enum { A, B, }" (but multiline) enum_member = types.EnumMember(self.reader.expect_identifier()) members.append(enum_member) self.node_manager.add_node(enum_member, self.reader.prev_token_offset) # TODO: generated code compatibility self.reader.read_token(f'''= "{enum_member.name}"''') if not (self.reader.read_token(",")): break self.reader.expect_token("}") enum_obj = types.Enum(name, members, is_exported, leading_trivia) self.node_manager.add_node(enum_obj, enum_start) self.context.pop() return enum_obj @classmethod def calculate_relative_path(cls, curr_file, rel_path): if not rel_path.startswith("."): raise Error(f'''relPath must start with \'.\', but got \'{rel_path}\'''') curr = re.split("/", curr_file) curr.pop() # filename does not matter for part in re.split("/", rel_path): if part == "": raise Error(f'''relPath should not contain multiple \'/\' next to each other (relPath=\'{rel_path}\')''') if part == ".": # "./" == stay in current directory continue elif part == "..": # "../" == parent directory if len(curr) == 0: raise Error(f'''relPath goes out of root (curr=\'{curr_file}\', relPath=\'{rel_path}\')''') curr.pop() else: curr.append(part) return "/".join(curr) @classmethod def calculate_import_scope(cls, curr_scope, import_file): if import_file.startswith("."): # relative return types.ExportScopeRef(curr_scope.package_name, TypeScriptParser2.calculate_relative_path(curr_scope.scope_name, import_file)) else: path = re.split("/", import_file) pkg_name = path.pop(0) return types.ExportScopeRef(pkg_name, types.Package.index if len(path) == 0 else "/".join(path)) def read_identifier(self): raw_id = self.reader.read_identifier() return re.sub("_+$", "", raw_id) def parse_import(self, leading_trivia): if not self.reader.read_token("import"): return None import_start = self.reader.prev_token_offset import_all_alias = None import_parts = [] if self.reader.read_token("*"): self.reader.expect_token("as") import_all_alias = self.reader.expect_identifier() else: self.reader.expect_token("{") while True: if self.reader.peek_token("}"): break imp = self.reader.expect_identifier() if self.reader.read_token("as"): self.reader.fail("This is not yet supported") import_parts.append(types.UnresolvedImport(imp)) self.node_manager.add_node(imp, self.reader.prev_token_offset) if not (self.reader.read_token(",")): break self.reader.expect_token("}") self.reader.expect_token("from") module_name = self.reader.expect_string() self.reader.expect_token(";") import_scope = TypeScriptParser2.calculate_import_scope(self.export_scope, module_name) if self.export_scope != None else None imports = [] if len(import_parts) > 0: imports.append(types.Import(import_scope, False, import_parts, None, leading_trivia)) if import_all_alias != None: imports.append(types.Import(import_scope, True, None, import_all_alias, leading_trivia)) #this.nodeManager.addNode(imports, importStart); return imports def parse_source_file(self): imports = [] enums = [] intfs = [] classes = [] funcs = [] while True: leading_trivia = self.reader.read_leading_trivia() if self.reader.get_eof(): break imps = self.parse_import(leading_trivia) if imps != None: for imp in imps: imports.append(imp) continue modifiers = self.reader.read_modifiers(["export", "declare"]) is_exported = "export" in modifiers is_declaration = "declare" in modifiers cls_ = self.parse_class(leading_trivia, is_exported, is_declaration) if cls_ != None: classes.append(cls_) continue enum_obj = self.parse_enum(leading_trivia, is_exported) if enum_obj != None: enums.append(enum_obj) continue intf = self.parse_interface(leading_trivia, is_exported) if intf != None: intfs.append(intf) continue if self.reader.read_token("function"): func_name = self.read_identifier() self.reader.expect_token("(") sig = self.parse_method_signature(False, is_declaration) funcs.append(types.GlobalFunction(func_name, sig.params, sig.body, sig.returns, is_exported, leading_trivia)) continue break self.reader.skip_whitespace() stmts = [] while True: leading_trivia = self.reader.read_leading_trivia() if self.reader.get_eof(): break stmt = self.expect_statement() if stmt == None: continue stmt.leading_trivia = leading_trivia stmts.append(stmt) return types.SourceFile(imports, intfs, classes, enums, funcs, stats.Block(stmts), self.path, self.export_scope) def parse(self): return self.parse_source_file() @classmethod def parse_file(cls, source, path = None): return TypeScriptParser2(source, path).parse_source_file()
from onelang_core import * import OneLang.Parsers.Common.Reader as read import OneLang.Parsers.Common.ExpressionParser as exprPars import OneLang.Parsers.Common.NodeManager as nodeMan import OneLang.Parsers.Common.IParser as iPars import OneLang.One.Ast.AstTypes as astTypes import OneLang.One.Ast.Expressions as exprs import OneLang.One.Ast.Statements as stats import OneLang.One.Ast.Types as types import OneLang.One.Ast.Interfaces as ints import re class TypeAndInit: def __init__(self, type, init): self.type = type self.init = init class MethodSignature: def __init__(self, params, fields, body, returns, super_call_args): self.params = params self.fields = fields self.body = body self.returns = returns self.super_call_args = super_call_args class TypeScriptParser2: def __init__(self, source, path = None): self.context = [] self.reader = None self.expression_parser = None self.node_manager = None self.export_scope = None self.missing_return_type_is_void = False self.allow_dollar_ids = False self.path = path self.reader = read.Reader(source) self.reader.hooks = self self.node_manager = nodeMan.NodeManager(self.reader) self.expression_parser = self.create_expression_parser(self.reader, self.node_manager) self.export_scope = types.ExportScopeRef(self.path.pkg.name, re.sub("\\.ts$", "", self.path.path) if self.path.path != None else None) if self.path != None else None def create_expression_parser(self, reader, node_manager = None): expression_parser = exprPars.ExpressionParser(reader, self, node_manager) expression_parser.string_literal_type = astTypes.UnresolvedType("TsString", []) expression_parser.numeric_literal_type = astTypes.UnresolvedType("TsNumber", []) return expression_parser def error_callback(self, error): raise Error(f'''[TypeScriptParser] {error.message} at {error.cursor.line}:{error.cursor.column} (context: {"/".join(self.context)})\n{self.reader.line_preview(error.cursor)}''') def infix_prehook(self, left): if isinstance(left, exprs.PropertyAccessExpression) and self.reader.peek_regex("<[A-Za-z0-9_<>]*?>\\(") != None: type_args = self.parse_type_args() self.reader.expect_token("(") args = self.expression_parser.parse_call_arguments() return exprs.UnresolvedCallExpression(left, type_args, args) elif self.reader.read_token("instanceof"): type = self.parse_type() return exprs.InstanceOfExpression(left, type) elif isinstance(left, exprs.Identifier) and self.reader.read_token("=>"): block = self.parse_lambda_block() return types.Lambda([types.MethodParameter(left.text, None, None, None)], block) return None def parse_lambda_params(self): if not self.reader.read_token("("): return None params = [] if not self.reader.read_token(")"): while True: param_name = self.reader.expect_identifier() type = self.parse_type() if self.reader.read_token(":") else None params.append(types.MethodParameter(param_name, type, None, None)) if not (self.reader.read_token(",")): break self.reader.expect_token(")") return params def parse_type(self): if self.reader.read_token("{"): self.reader.expect_token("[") self.reader.read_identifier() self.reader.expect_token(":") self.reader.expect_token("string") self.reader.expect_token("]") self.reader.expect_token(":") map_value_type = self.parse_type() self.reader.read_token(";") self.reader.expect_token("}") return astTypes.UnresolvedType("TsMap", [map_value_type]) if self.reader.peek_token("("): params = self.parse_lambda_params() self.reader.expect_token("=>") return_type = self.parse_type() return astTypes.LambdaType(params, return_type) type_name = self.reader.expect_identifier() start_pos = self.reader.prev_token_offset if type_name == "string": type = astTypes.UnresolvedType("TsString", []) elif type_name == "boolean": type = astTypes.UnresolvedType("TsBoolean", []) elif type_name == "number": type = astTypes.UnresolvedType("TsNumber", []) elif type_name == "any": type = astTypes.AnyType.instance elif type_name == "void": type = astTypes.VoidType.instance else: type_arguments = self.parse_type_args() type = astTypes.UnresolvedType(type_name, type_arguments) self.node_manager.add_node(type, start_pos) while self.reader.read_token("[]"): type = astTypes.UnresolvedType("TsArray", [type]) self.node_manager.add_node(type, start_pos) return type def parse_expression(self): return self.expression_parser.parse() def unary_prehook(self): if self.reader.read_token("null"): return exprs.NullLiteral() elif self.reader.read_token("true"): return exprs.BooleanLiteral(True) elif self.reader.read_token("false"): return exprs.BooleanLiteral(False) elif self.reader.read_token("`"): parts = [] lit_part = "" while True: if self.reader.read_exactly("`"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" break elif self.reader.read_exactly("${"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" expr = self.parse_expression() parts.append(exprs.TemplateStringPart.expression(expr)) self.reader.expect_token("}") elif self.allow_dollar_ids and self.reader.read_exactly("$"): if lit_part != "": parts.append(exprs.TemplateStringPart.literal(lit_part)) lit_part = "" id = self.reader.read_identifier() parts.append(exprs.TemplateStringPart.expression(exprs.Identifier(id))) elif self.reader.read_exactly("\\"): chr = self.reader.read_char() if chr == "n": lit_part += "\n" elif chr == "r": lit_part += "\r" elif chr == "t": lit_part += "\t" elif chr == "`": lit_part += "`" elif chr == "$": lit_part += "$" elif chr == "\\": lit_part += "\\" else: self.reader.fail("invalid escape", self.reader.offset - 1) else: chr = self.reader.read_char() chr_code = ord(chr[0]) if not (32 <= chr_code and chr_code <= 126) or chr == "`" or chr == "\\": self.reader.fail(f'''not allowed character (code={chr_code})''', self.reader.offset - 1) lit_part += chr return exprs.TemplateString(parts) elif self.reader.read_token("new"): type = self.parse_type() if isinstance(type, astTypes.UnresolvedType): self.reader.expect_token("(") args = self.expression_parser.parse_call_arguments() return exprs.UnresolvedNewExpression(type, args) else: raise Error(f'''[TypeScriptParser2] Expected UnresolvedType here!''') elif self.reader.read_token("<"): new_type = self.parse_type() self.reader.expect_token(">") expression = self.parse_expression() return exprs.CastExpression(new_type, expression) elif self.reader.read_token("/"): pattern = "" while True: chr = self.reader.read_char() if chr == "\\": chr2 = self.reader.read_char() pattern += "/" if chr2 == "/" else "\\" + chr2 elif chr == "/": break else: pattern += chr modifiers = self.reader.read_modifiers(["g", "i"]) return exprs.RegexLiteral(pattern, "i" in modifiers, "g" in modifiers) elif self.reader.read_token("typeof"): expr = self.expression_parser.parse(self.expression_parser.prefix_precedence) self.reader.expect_token("===") check = self.reader.expect_string() ts_type = None if check == "string": ts_type = "TsString" elif check == "boolean": ts_type = "TsBoolean" elif check == "object": ts_type = "Object" elif check == "function": # TODO: ??? ts_type = "Function" elif check == "undefined": # TODO: ??? ts_type = "Object" else: self.reader.fail("unexpected typeof comparison") return exprs.InstanceOfExpression(expr, astTypes.UnresolvedType(ts_type, [])) elif self.reader.peek_regex("\\([A-Za-z0-9_]+\\s*[:,]|\\(\\)") != None: params = self.parse_lambda_params() self.reader.expect_token("=>") block = self.parse_lambda_block() return types.Lambda(params, block) elif self.reader.read_token("await"): expression = self.parse_expression() return exprs.AwaitExpression(expression) map_literal = self.expression_parser.parse_map_literal() if map_literal != None: return map_literal array_literal = self.expression_parser.parse_array_literal() if array_literal != None: return array_literal return None def parse_lambda_block(self): block = self.parse_block() if block != None: return block return_expr = self.parse_expression() if isinstance(return_expr, exprs.ParenthesizedExpression): return_expr = return_expr.expression return stats.Block([stats.ReturnStatement(return_expr)]) def parse_type_and_init(self): type = self.parse_type() if self.reader.read_token(":") else None init = self.parse_expression() if self.reader.read_token("=") else None if type == None and init == None: self.reader.fail(f'''expected type declaration or initializer''') return TypeAndInit(type, init) def expect_block_or_statement(self): block = self.parse_block() if block != None: return block stmts = [] stmt = self.expect_statement() if stmt != None: stmts.append(stmt) return stats.Block(stmts) def expect_statement(self): statement = None leading_trivia = self.reader.read_leading_trivia() start_pos = self.reader.offset requires_closing = True var_decl_matches = self.reader.read_regex("(const|let|var)\\b") if var_decl_matches != None: name = self.reader.expect_identifier("expected variable name") type_and_init = self.parse_type_and_init() statement = stats.VariableDeclaration(name, type_and_init.type, type_and_init.init) elif self.reader.read_token("delete"): statement = stats.UnsetStatement(self.parse_expression()) elif self.reader.read_token("if"): requires_closing = False self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") then = self.expect_block_or_statement() else_ = self.expect_block_or_statement() if self.reader.read_token("else") else None statement = stats.IfStatement(condition, then, else_) elif self.reader.read_token("while"): requires_closing = False self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.WhileStatement(condition, body) elif self.reader.read_token("do"): requires_closing = False body = self.expect_block_or_statement() self.reader.expect_token("while") self.reader.expect_token("(") condition = self.parse_expression() self.reader.expect_token(")") statement = stats.DoStatement(condition, body) elif self.reader.read_token("for"): requires_closing = False self.reader.expect_token("(") var_decl_mod = self.reader.read_any_of(["const", "let", "var"]) item_var_name = None if var_decl_mod == None else self.reader.expect_identifier() if item_var_name != None and self.reader.read_token("of"): items = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.ForeachStatement(stats.ForeachVariable(item_var_name), items, body) else: for_var = None if item_var_name != None: type_and_init = self.parse_type_and_init() for_var = stats.ForVariable(item_var_name, type_and_init.type, type_and_init.init) self.reader.expect_token(";") condition = self.parse_expression() self.reader.expect_token(";") incrementor = self.parse_expression() self.reader.expect_token(")") body = self.expect_block_or_statement() statement = stats.ForStatement(for_var, condition, incrementor, body) elif self.reader.read_token("try"): block = self.expect_block("try body is missing") catch_var = None catch_body = None if self.reader.read_token("catch"): self.reader.expect_token("(") catch_var = stats.CatchVariable(self.reader.expect_identifier(), None) self.reader.expect_token(")") catch_body = self.expect_block("catch body is missing") finally_body = self.expect_block() if self.reader.read_token("finally") else None return stats.TryStatement(block, catch_var, catch_body, finally_body) elif self.reader.read_token("return"): expr = None if self.reader.peek_token(";") else self.parse_expression() statement = stats.ReturnStatement(expr) elif self.reader.read_token("throw"): expr = self.parse_expression() statement = stats.ThrowStatement(expr) elif self.reader.read_token("break"): statement = stats.BreakStatement() elif self.reader.read_token("continue"): statement = stats.ContinueStatement() elif self.reader.read_token("debugger;"): return None else: expr = self.parse_expression() statement = stats.ExpressionStatement(expr) is_binary_set = isinstance(expr, exprs.BinaryExpression) and expr.operator in ["=", "+=", "-="] is_unary_set = isinstance(expr, exprs.UnaryExpression) and expr.operator in ["++", "--"] if not (isinstance(expr, exprs.UnresolvedCallExpression) or is_binary_set or is_unary_set or isinstance(expr, exprs.AwaitExpression)): self.reader.fail("this expression is not allowed as statement") if statement == None: self.reader.fail("unknown statement") statement.leading_trivia = leading_trivia self.node_manager.add_node(statement, start_pos) statement_last_line = self.reader.ws_line_counter if not self.reader.read_token(";") and requires_closing and self.reader.ws_line_counter == statement_last_line: self.reader.fail("statement is not closed", self.reader.ws_offset) return statement def parse_block(self): if not self.reader.read_token("{"): return None start_pos = self.reader.prev_token_offset statements = [] if not self.reader.read_token("}"): while True: statement = self.expect_statement() if statement != None: statements.append(statement) if not (not self.reader.read_token("}")): break block = stats.Block(statements) self.node_manager.add_node(block, start_pos) return block def expect_block(self, error_msg = None): block = self.parse_block() if block == None: self.reader.fail(error_msg or "expected block here") return block def parse_type_args(self): type_arguments = [] if self.reader.read_token("<"): while True: generics = self.parse_type() type_arguments.append(generics) if not (self.reader.read_token(",")): break self.reader.expect_token(">") return type_arguments def parse_generics_args(self): type_arguments = [] if self.reader.read_token("<"): while True: generics = self.reader.expect_identifier() type_arguments.append(generics) if not (self.reader.read_token(",")): break self.reader.expect_token(">") return type_arguments def parse_expr_stmt_from_string(self, expression): expr = self.create_expression_parser(read.Reader(expression)).parse() return stats.ExpressionStatement(expr) def parse_method_signature(self, is_constructor, declaration_only): params = [] fields = [] if not self.reader.read_token(")"): while True: leading_trivia = self.reader.read_leading_trivia() param_start = self.reader.offset is_public = self.reader.read_token("public") if is_public and not is_constructor: self.reader.fail("public modifier is only allowed in constructor definition") param_name = self.reader.expect_identifier() self.context.append(f'''arg:{param_name}''') type_and_init = self.parse_type_and_init() param = types.MethodParameter(param_name, type_and_init.type, type_and_init.init, leading_trivia) params.append(param) # init should be used as only the constructor's method parameter, but not again as a field initializer too # (otherwise it would called twice if cloned or cause AST error is just referenced from two separate places) if is_public: field = types.Field(param_name, type_and_init.type, None, types.VISIBILITY.PUBLIC, False, param, param.leading_trivia) fields.append(field) param.field_decl = field self.node_manager.add_node(param, param_start) self.context.pop() if not (self.reader.read_token(",")): break self.reader.expect_token(")") returns = None if not is_constructor: # in case of constructor, "returns" won't be used returns = self.parse_type() if self.reader.read_token(":") else astTypes.VoidType.instance if self.missing_return_type_is_void else None body = None super_call_args = None if declaration_only: self.reader.expect_token(";") else: body = self.expect_block("method body is missing") first_stmt = body.statements[0] if len(body.statements) > 0 else None if isinstance(first_stmt, stats.ExpressionStatement) and isinstance(first_stmt.expression, exprs.UnresolvedCallExpression) and isinstance(first_stmt.expression.func, exprs.Identifier) and first_stmt.expression.func.text == "super": super_call_args = first_stmt.expression.args body.statements.pop(0) return MethodSignature(params, fields, body, returns, super_call_args) def parse_identifier_or_string(self): return self.reader.read_string() or self.reader.expect_identifier() def parse_interface(self, leading_trivia, is_exported): if not self.reader.read_token("interface"): return None intf_start = self.reader.prev_token_offset intf_name = self.reader.expect_identifier("expected identifier after 'interface' keyword") self.context.append(f'''I:{intf_name}''') intf_type_args = self.parse_generics_args() base_interfaces = [] if self.reader.read_token("extends"): while True: base_interfaces.append(self.parse_type()) if not (self.reader.read_token(",")): break methods = [] fields = [] self.reader.expect_token("{") while not self.reader.read_token("}"): member_leading_trivia = self.reader.read_leading_trivia() member_start = self.reader.offset member_name = self.parse_identifier_or_string() if self.reader.read_token(":"): self.context.append(f'''F:{member_name}''') field_type = self.parse_type() self.reader.expect_token(";") field = types.Field(member_name, field_type, None, types.VISIBILITY.PUBLIC, False, None, member_leading_trivia) fields.append(field) self.node_manager.add_node(field, member_start) self.context.pop() else: self.context.append(f'''M:{member_name}''') method_type_args = self.parse_generics_args() self.reader.expect_token("(") # method sig = self.parse_method_signature(False, True) method = types.Method(member_name, method_type_args, sig.params, sig.body, types.VISIBILITY.PUBLIC, False, sig.returns, False, member_leading_trivia) methods.append(method) self.node_manager.add_node(method, member_start) self.context.pop() intf = types.Interface(intf_name, intf_type_args, base_interfaces, fields, methods, is_exported, leading_trivia) self.node_manager.add_node(intf, intf_start) self.context.pop() return intf def parse_specified_type(self): type_name = self.reader.read_identifier() type_args = self.parse_type_args() return astTypes.UnresolvedType(type_name, type_args) def parse_class(self, leading_trivia, is_exported, declaration_only): cls_modifiers = self.reader.read_modifiers(["abstract"]) if not self.reader.read_token("class"): return None cls_start = self.reader.prev_token_offset cls_name = self.reader.expect_identifier("expected identifier after 'class' keyword") self.context.append(f'''C:{cls_name}''') type_args = self.parse_generics_args() base_class = self.parse_specified_type() if self.reader.read_token("extends") else None base_interfaces = [] if self.reader.read_token("implements"): while True: base_interfaces.append(self.parse_specified_type()) if not (self.reader.read_token(",")): break constructor = None fields = [] methods = [] properties = [] self.reader.expect_token("{") while not self.reader.read_token("}"): member_leading_trivia = self.reader.read_leading_trivia() member_start = self.reader.offset modifiers = self.reader.read_modifiers(["static", "public", "protected", "private", "readonly", "async", "abstract"]) is_static = "static" in modifiers is_async = "async" in modifiers is_abstract = "abstract" in modifiers visibility = types.VISIBILITY.PRIVATE if "private" in modifiers else types.VISIBILITY.PROTECTED if "protected" in modifiers else types.VISIBILITY.PUBLIC member_name = self.parse_identifier_or_string() method_type_args = self.parse_generics_args() if self.reader.read_token("("): # method is_constructor = member_name == "constructor" sig = self.parse_method_signature(is_constructor, declaration_only or is_abstract) if is_constructor: member = constructor = types.Constructor(sig.params, sig.body, sig.super_call_args, member_leading_trivia) for field in sig.fields: fields.append(field) else: method = types.Method(member_name, method_type_args, sig.params, sig.body, visibility, is_static, sig.returns, is_async, member_leading_trivia) methods.append(method) member = method self.node_manager.add_node(member, member_start) elif member_name == "get" or member_name == "set": # property prop_name = self.reader.expect_identifier() prop = next(filter(lambda x: x.name == prop_name, properties), None) prop_type = None getter = None setter = None if member_name == "get": # get propName(): propType { return ... } self.context.append(f'''P[G]:{prop_name}''') self.reader.expect_token("()", "expected '()' after property getter name") prop_type = self.parse_type() if self.reader.read_token(":") else None if declaration_only: if prop_type == None: self.reader.fail("Type is missing for property in declare class") self.reader.expect_token(";") else: getter = self.expect_block("property getter body is missing") if prop != None: prop.getter = getter elif member_name == "set": # set propName(value: propType) { ... } self.context.append(f'''P[S]:{prop_name}''') self.reader.expect_token("(", "expected '(' after property setter name") self.reader.expect_identifier() prop_type = self.parse_type() if self.reader.read_token(":") else None self.reader.expect_token(")") if declaration_only: if prop_type == None: self.reader.fail("Type is missing for property in declare class") self.reader.expect_token(";") else: setter = self.expect_block("property setter body is missing") if prop != None: prop.setter = setter if prop == None: prop = types.Property(prop_name, prop_type, getter, setter, visibility, is_static, member_leading_trivia) properties.append(prop) self.node_manager.add_node(prop, member_start) self.context.pop() else: self.context.append(f'''F:{member_name}''') type_and_init = self.parse_type_and_init() self.reader.expect_token(";") field = types.Field(member_name, type_and_init.type, type_and_init.init, visibility, is_static, None, member_leading_trivia) fields.append(field) self.node_manager.add_node(field, member_start) self.context.pop() cls_ = types.Class(cls_name, type_args, base_class, base_interfaces, fields, properties, constructor, methods, is_exported, leading_trivia) self.node_manager.add_node(cls_, cls_start) self.context.pop() return cls_ def parse_enum(self, leading_trivia, is_exported): if not self.reader.read_token("enum"): return None enum_start = self.reader.prev_token_offset name = self.reader.expect_identifier("expected identifier after 'enum' keyword") self.context.append(f'''E:{name}''') members = [] self.reader.expect_token("{") if not self.reader.read_token("}"): while True: if self.reader.peek_token("}"): break # eg. "enum { A, B, }" (but multiline) enum_member = types.EnumMember(self.reader.expect_identifier()) members.append(enum_member) self.node_manager.add_node(enum_member, self.reader.prev_token_offset) # TODO: generated code compatibility self.reader.read_token(f'''= "{enum_member.name}"''') if not (self.reader.read_token(",")): break self.reader.expect_token("}") enum_obj = types.Enum(name, members, is_exported, leading_trivia) self.node_manager.add_node(enum_obj, enum_start) self.context.pop() return enum_obj @classmethod def calculate_relative_path(cls, curr_file, rel_path): if not rel_path.startswith("."): raise Error(f'''relPath must start with \'.\', but got \'{rel_path}\'''') curr = re.split("/", curr_file) curr.pop() # filename does not matter for part in re.split("/", rel_path): if part == "": raise Error(f'''relPath should not contain multiple \'/\' next to each other (relPath=\'{rel_path}\')''') if part == ".": # "./" == stay in current directory continue elif part == "..": # "../" == parent directory if len(curr) == 0: raise Error(f'''relPath goes out of root (curr=\'{curr_file}\', relPath=\'{rel_path}\')''') curr.pop() else: curr.append(part) return "/".join(curr) @classmethod def calculate_import_scope(cls, curr_scope, import_file): if import_file.startswith("."): # relative return types.ExportScopeRef(curr_scope.package_name, TypeScriptParser2.calculate_relative_path(curr_scope.scope_name, import_file)) else: path = re.split("/", import_file) pkg_name = path.pop(0) return types.ExportScopeRef(pkg_name, types.Package.index if len(path) == 0 else "/".join(path)) def read_identifier(self): raw_id = self.reader.read_identifier() return re.sub("_+$", "", raw_id) def parse_import(self, leading_trivia): if not self.reader.read_token("import"): return None import_start = self.reader.prev_token_offset import_all_alias = None import_parts = [] if self.reader.read_token("*"): self.reader.expect_token("as") import_all_alias = self.reader.expect_identifier() else: self.reader.expect_token("{") while True: if self.reader.peek_token("}"): break imp = self.reader.expect_identifier() if self.reader.read_token("as"): self.reader.fail("This is not yet supported") import_parts.append(types.UnresolvedImport(imp)) self.node_manager.add_node(imp, self.reader.prev_token_offset) if not (self.reader.read_token(",")): break self.reader.expect_token("}") self.reader.expect_token("from") module_name = self.reader.expect_string() self.reader.expect_token(";") import_scope = TypeScriptParser2.calculate_import_scope(self.export_scope, module_name) if self.export_scope != None else None imports = [] if len(import_parts) > 0: imports.append(types.Import(import_scope, False, import_parts, None, leading_trivia)) if import_all_alias != None: imports.append(types.Import(import_scope, True, None, import_all_alias, leading_trivia)) #this.nodeManager.addNode(imports, importStart); return imports def parse_source_file(self): imports = [] enums = [] intfs = [] classes = [] funcs = [] while True: leading_trivia = self.reader.read_leading_trivia() if self.reader.get_eof(): break imps = self.parse_import(leading_trivia) if imps != None: for imp in imps: imports.append(imp) continue modifiers = self.reader.read_modifiers(["export", "declare"]) is_exported = "export" in modifiers is_declaration = "declare" in modifiers cls_ = self.parse_class(leading_trivia, is_exported, is_declaration) if cls_ != None: classes.append(cls_) continue enum_obj = self.parse_enum(leading_trivia, is_exported) if enum_obj != None: enums.append(enum_obj) continue intf = self.parse_interface(leading_trivia, is_exported) if intf != None: intfs.append(intf) continue if self.reader.read_token("function"): func_name = self.read_identifier() self.reader.expect_token("(") sig = self.parse_method_signature(False, is_declaration) funcs.append(types.GlobalFunction(func_name, sig.params, sig.body, sig.returns, is_exported, leading_trivia)) continue break self.reader.skip_whitespace() stmts = [] while True: leading_trivia = self.reader.read_leading_trivia() if self.reader.get_eof(): break stmt = self.expect_statement() if stmt == None: continue stmt.leading_trivia = leading_trivia stmts.append(stmt) return types.SourceFile(imports, intfs, classes, enums, funcs, stats.Block(stmts), self.path, self.export_scope) def parse(self): return self.parse_source_file() @classmethod def parse_file(cls, source, path = None): return TypeScriptParser2(source, path).parse_source_file()
#!/usr/bin/env python3 import json import logging import argparse from project.default import get_homedir def validate_generic_config_file(): sample_config = get_homedir() / 'config' / 'generic.json.sample' with sample_config.open() as f: generic_config_sample = json.load(f) # Check documentation for key in generic_config_sample.keys(): if key == '_notes': continue if key not in generic_config_sample['_notes']: raise Exception(f'###### - Documentation missing for {key}') user_config = get_homedir() / 'config' / 'generic.json' if not user_config.exists(): # The config file was never created, copy the sample. with user_config.open('w') as _fw: json.dump(generic_config_sample, _fw) with user_config.open() as f: generic_config = json.load(f) # Check all entries in the sample files are in the user file, and they have the same type for key in generic_config_sample.keys(): if key == '_notes': continue if generic_config.get(key) is None: logger.warning(f'Entry missing in user config file: {key}. Will default to: {generic_config_sample[key]}') continue if not isinstance(generic_config[key], type(generic_config_sample[key])): raise Exception(f'Invalid type for {key}. Got: {type(generic_config[key])} ({generic_config[key]}), expected: {type(generic_config_sample[key])} ({generic_config_sample[key]})') if isinstance(generic_config[key], dict): # Check entries for sub_key in generic_config_sample[key].keys(): if sub_key not in generic_config[key]: raise Exception(f'{sub_key} is missing in generic_config[key]. Default from sample file: {generic_config_sample[key][sub_key]}') if not isinstance(generic_config[key][sub_key], type(generic_config_sample[key][sub_key])): raise Exception(f'Invalid type for {sub_key} in {key}. Got: {type(generic_config[key][sub_key])} ({generic_config[key][sub_key]}), expected: {type(generic_config_sample[key][sub_key])} ({generic_config_sample[key][sub_key]})') # Make sure the user config file doesn't have entries missing in the sample config for key in generic_config.keys(): if key not in generic_config_sample: raise Exception(f'{key} is missing in the sample config file. You need to compare {user_config} with {sample_config}.') return True def update_user_configs(): for file_name in ['generic']: with (get_homedir() / 'config' / f'{file_name}.json').open() as f: try: generic_config = json.load(f) except Exception: generic_config = {} with (get_homedir() / 'config' / f'{file_name}.json.sample').open() as f: generic_config_sample = json.load(f) has_new_entry = False for key in generic_config_sample.keys(): if key == '_notes': continue if generic_config.get(key) is None: print(f'{key} was missing in {file_name}, adding it.') print(f"Description: {generic_config_sample["_notes"][key]}") generic_config[key] = generic_config_sample[key] has_new_entry = True elif isinstance(generic_config[key], dict): for sub_key in generic_config_sample[key].keys(): if sub_key not in generic_config[key]: print(f'{sub_key} was missing in {key} from {file_name}, adding it.') generic_config[key][sub_key] = generic_config_sample[key][sub_key] has_new_entry = True if has_new_entry: with (get_homedir() / 'config' / f'{file_name}.json').open('w') as fw: json.dump(generic_config, fw, indent=2, sort_keys=True) return has_new_entry if __name__ == '__main__': logger = logging.getLogger('Config validator') parser = argparse.ArgumentParser(description='Check the config files.') parser.add_argument('--check', default=False, action='store_true', help='Check if the sample config and the user config are in-line') parser.add_argument('--update', default=False, action='store_true', help='Update the user config with the entries from the sample config if entries are missing') args = parser.parse_args() if args.check: if validate_generic_config_file(): print(f"The entries in {get_homedir() / "config" / "generic.json"} are valid.") if args.update: if not update_user_configs(): print(f"No updates needed in {get_homedir() / "config" / "generic.json"}.")
#!/usr/bin/env python3 import json import logging import argparse from project.default import get_homedir def validate_generic_config_file(): sample_config = get_homedir() / 'config' / 'generic.json.sample' with sample_config.open() as f: generic_config_sample = json.load(f) # Check documentation for key in generic_config_sample.keys(): if key == '_notes': continue if key not in generic_config_sample['_notes']: raise Exception(f'###### - Documentation missing for {key}') user_config = get_homedir() / 'config' / 'generic.json' if not user_config.exists(): # The config file was never created, copy the sample. with user_config.open('w') as _fw: json.dump(generic_config_sample, _fw) with user_config.open() as f: generic_config = json.load(f) # Check all entries in the sample files are in the user file, and they have the same type for key in generic_config_sample.keys(): if key == '_notes': continue if generic_config.get(key) is None: logger.warning(f'Entry missing in user config file: {key}. Will default to: {generic_config_sample[key]}') continue if not isinstance(generic_config[key], type(generic_config_sample[key])): raise Exception(f'Invalid type for {key}. Got: {type(generic_config[key])} ({generic_config[key]}), expected: {type(generic_config_sample[key])} ({generic_config_sample[key]})') if isinstance(generic_config[key], dict): # Check entries for sub_key in generic_config_sample[key].keys(): if sub_key not in generic_config[key]: raise Exception(f'{sub_key} is missing in generic_config[key]. Default from sample file: {generic_config_sample[key][sub_key]}') if not isinstance(generic_config[key][sub_key], type(generic_config_sample[key][sub_key])): raise Exception(f'Invalid type for {sub_key} in {key}. Got: {type(generic_config[key][sub_key])} ({generic_config[key][sub_key]}), expected: {type(generic_config_sample[key][sub_key])} ({generic_config_sample[key][sub_key]})') # Make sure the user config file doesn't have entries missing in the sample config for key in generic_config.keys(): if key not in generic_config_sample: raise Exception(f'{key} is missing in the sample config file. You need to compare {user_config} with {sample_config}.') return True def update_user_configs(): for file_name in ['generic']: with (get_homedir() / 'config' / f'{file_name}.json').open() as f: try: generic_config = json.load(f) except Exception: generic_config = {} with (get_homedir() / 'config' / f'{file_name}.json.sample').open() as f: generic_config_sample = json.load(f) has_new_entry = False for key in generic_config_sample.keys(): if key == '_notes': continue if generic_config.get(key) is None: print(f'{key} was missing in {file_name}, adding it.') print(f"Description: {generic_config_sample['_notes'][key]}") generic_config[key] = generic_config_sample[key] has_new_entry = True elif isinstance(generic_config[key], dict): for sub_key in generic_config_sample[key].keys(): if sub_key not in generic_config[key]: print(f'{sub_key} was missing in {key} from {file_name}, adding it.') generic_config[key][sub_key] = generic_config_sample[key][sub_key] has_new_entry = True if has_new_entry: with (get_homedir() / 'config' / f'{file_name}.json').open('w') as fw: json.dump(generic_config, fw, indent=2, sort_keys=True) return has_new_entry if __name__ == '__main__': logger = logging.getLogger('Config validator') parser = argparse.ArgumentParser(description='Check the config files.') parser.add_argument('--check', default=False, action='store_true', help='Check if the sample config and the user config are in-line') parser.add_argument('--update', default=False, action='store_true', help='Update the user config with the entries from the sample config if entries are missing') args = parser.parse_args() if args.check: if validate_generic_config_file(): print(f"The entries in {get_homedir() / 'config' / 'generic.json'} are valid.") if args.update: if not update_user_configs(): print(f"No updates needed in {get_homedir() / 'config' / 'generic.json'}.")
import datetime import logging import tornado.escape import tornado.web from icubam.backoffice.handlers import base, home, icus, users from icubam.db import store from icubam.messaging import client class ListMessagesHandler(base.AdminHandler): ROUTE = "list_messages" def initialize(self): super().initialize() self.client = client.MessageServerClient(self.config) def prepare_for_table(self, msg): result = [ { 'key': 'user', 'value': msg['user_name'], 'link': f'{users.UserHandler.ROUTE}?id={msg['user_id']}' }, { 'key': 'ICU', 'value': msg["icu_name"], 'link': f'{icus.ICUHandler.ROUTE}?id={msg['icu_id']}' }, ] msg_dict = {} msg_dict['telephone'] = msg['phone'] msg_dict['scheduled'] = '{0:%Y/%m/%d at %H:%M:%S}'.format( datetime.datetime.fromtimestamp(msg['when']) ) msg_dict['attempts'] = msg['attempts'] msg_dict['first sent'] = 'not yet' if msg['first_sent'] is not None: msg_dict['first sent'] = '{0:%Y/%m/%d at %H:%M:%S}'.format( datetime.datetime.fromtimestamp(msg['first_sent']) ) result.extend(self.format_list_item(msg_dict)) result.append({'key': 'url', 'value': 'link', 'link': msg['url']}) return result @tornado.web.authenticated async def get(self): try: messages = await self.client.get_scheduled_messages(self.user.user_id) except Exception as e: logging.error(f'Cannot contact message server: {e}') return self.redirect(self.root_path) data = [self.prepare_for_table(msg) for msg in messages] self.render_list( data=data, objtype='Scheduled Messages', create_handler=None )
import datetime import logging import tornado.escape import tornado.web from icubam.backoffice.handlers import base, home, icus, users from icubam.db import store from icubam.messaging import client class ListMessagesHandler(base.AdminHandler): ROUTE = "list_messages" def initialize(self): super().initialize() self.client = client.MessageServerClient(self.config) def prepare_for_table(self, msg): result = [ { 'key': 'user', 'value': msg['user_name'], 'link': f'{users.UserHandler.ROUTE}?id={msg["user_id"]}' }, { 'key': 'ICU', 'value': msg["icu_name"], 'link': f'{icus.ICUHandler.ROUTE}?id={msg["icu_id"]}' }, ] msg_dict = {} msg_dict['telephone'] = msg['phone'] msg_dict['scheduled'] = '{0:%Y/%m/%d at %H:%M:%S}'.format( datetime.datetime.fromtimestamp(msg['when']) ) msg_dict['attempts'] = msg['attempts'] msg_dict['first sent'] = 'not yet' if msg['first_sent'] is not None: msg_dict['first sent'] = '{0:%Y/%m/%d at %H:%M:%S}'.format( datetime.datetime.fromtimestamp(msg['first_sent']) ) result.extend(self.format_list_item(msg_dict)) result.append({'key': 'url', 'value': 'link', 'link': msg['url']}) return result @tornado.web.authenticated async def get(self): try: messages = await self.client.get_scheduled_messages(self.user.user_id) except Exception as e: logging.error(f'Cannot contact message server: {e}') return self.redirect(self.root_path) data = [self.prepare_for_table(msg) for msg in messages] self.render_list( data=data, objtype='Scheduled Messages', create_handler=None )
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module implements a friendly (well, friendlier) interface between the raw JSON responses from Jira and the Resource/dict abstractions provided by this library. Users will construct a JIRA object as described below. Full API documentation can be found at: https://jira.readthedocs.io/en/latest/ """ import calendar import copy import datetime import hashlib import imghdr import json import logging as _logging import mimetypes import os import re import sys import time import warnings from collections import OrderedDict from collections.abc import Iterable from functools import lru_cache, wraps from io import BufferedReader from numbers import Number from typing import ( Any, Callable, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, cast, no_type_check, ) from urllib.parse import urlparse import requests from pkg_resources import parse_version from requests import Response from requests.auth import AuthBase from requests.utils import get_netrc_auth from jira import __version__ # GreenHopper specific resources from jira.exceptions import JIRAError from jira.resilientsession import ResilientSession, raise_on_error # Jira-specific resources from jira.resources import ( Attachment, Board, Comment, Component, Customer, CustomFieldOption, Dashboard, Filter, GreenHopperResource, Group, Issue, IssueLink, IssueLinkType, IssueType, Priority, Project, RemoteLink, RequestType, Resolution, Resource, Role, SecurityLevel, ServiceDesk, Sprint, Status, StatusCategory, User, Version, Votes, Watchers, Worklog, ) from jira.utils import CaseInsensitiveDict, json_loads, threaded_requests try: # noinspection PyUnresolvedReferences from requests_toolbelt import MultipartEncoder except ImportError: pass try: from requests_jwt import JWTAuth except ImportError: pass LOG = _logging.getLogger("jira") LOG.addHandler(_logging.NullHandler()) def translate_resource_args(func: Callable): """Decorator that converts Issue and Project resources to their keys when used as arguments.""" @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: arg_list = [] for arg in args: if isinstance(arg, (Issue, Project)): arg_list.append(arg.key) else: arg_list.append(arg) result = func(*arg_list, **kwargs) return result return wrapper def _field_worker( fields: Dict[str, Any] = None, **fieldargs: Any ) -> Union[Dict[str, Dict[str, Any]], Dict[str, Dict[str, str]]]: if fields is not None: return {"fields": fields} return {"fields": fieldargs} ResourceType = TypeVar("ResourceType", contravariant=True, bound=Resource) class ResultList(list, Generic[ResourceType]): def __init__( self, iterable: Iterable = None, _startAt: int = 0, _maxResults: int = 0, _total: Optional[int] = None, _isLast: Optional[bool] = None, ) -> None: """ Args: iterable (Iterable): [description]. Defaults to None. _startAt (int): Start page. Defaults to 0. _maxResults (int): Max results per page. Defaults to 0. _total (Optional[int]): Total results from query. Defaults to 0. _isLast (Optional[bool]): Last Page? Defaults to None. """ if iterable is not None: list.__init__(self, iterable) else: list.__init__(self) self.startAt = _startAt self.maxResults = _maxResults # Optional parameters: self.isLast = _isLast self.total = _total if _total is not None else len(self) self.iterable: List = list(iterable) if iterable else [] self.current = self.startAt def __next__(self) -> Type[ResourceType]: self.current += 1 if self.current > self.total: raise StopIteration else: return self.iterable[self.current - 1] class QshGenerator(object): def __init__(self, context_path): self.context_path = context_path def __call__(self, req): parse_result = urlparse(req.url) path = ( parse_result.path[len(self.context_path) :] if len(self.context_path) > 1 else parse_result.path ) # Per Atlassian docs, use %20 for whitespace when generating qsh for URL # https://developer.atlassian.com/cloud/jira/platform/understanding-jwt/#qsh query = "&".join(sorted(parse_result.query.split("&"))).replace("+", "%20") qsh = f"{req.method.upper()}&{path}&{query}" return hashlib.sha256(qsh.encode("utf-8")).hexdigest() class JiraCookieAuth(AuthBase): """Jira Cookie Authentication Allows using cookie authentication as described by https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-cookie-based-authentication """ def __init__( self, session: ResilientSession, _get_session: Callable, auth: Tuple[str, str] ): """Cookie Based Authentication Args: session (ResilientSession): The Session object to communicate with the API. _get_session (Callable): The function that returns a :py_class:``User`` auth (Tuple[str, str]): The username, password tuple """ self._session = session self._get_session = _get_session self.__auth = auth def handle_401(self, response, **kwargs): if response.status_code != 401: return response self.init_session() response = self.process_original_request(response.request.copy()) return response def process_original_request(self, original_request): self.update_cookies(original_request) return self.send_request(original_request) def update_cookies(self, original_request): # Cookie header needs first to be deleted for the header to be updated using # the prepare_cookies method. See request.PrepareRequest.prepare_cookies if "Cookie" in original_request.headers: del original_request.headers["Cookie"] original_request.prepare_cookies(self.cookies) def init_session(self): self.start_session() def __call__(self, request): request.register_hook("response", self.handle_401) return request def send_request(self, request): return self._session.send(request) @property def cookies(self): return self._session.cookies def start_session(self): self._get_session(self.__auth) class JIRA(object): """User interface to Jira. Clients interact with Jira by constructing an instance of this object and calling its methods. For addressable resources in Jira -- those with "self" links -- an appropriate subclass of :py:class:`jira.resources.Resource` will be returned with customized ``update()`` and ``delete()`` methods, along with attribute access to fields. This means that calls of the form ``issue.fields.summary`` will be resolved into the proper lookups to return the JSON value at that mapping. Methods that do not return resources will return a dict constructed from the JSON response or a scalar value; see each method's documentation for details on what that method returns. Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``, or ``atlas-run-standalone`` commands. By default, this instance runs at ``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use. Authentication is handled with the ``basic_auth`` argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests. For quick command line access to a server, see the ``jirashell`` script included with this distribution. The easiest way to instantiate is using ``j = JIRA("https://jira.atlassian.com")`` """ DEFAULT_OPTIONS = { "server": "http://localhost:2990/jira", "auth_url": "/rest/auth/1/session", "context_path": "/", "rest_path": "api", "rest_api_version": "2", "agile_rest_path": GreenHopperResource.GREENHOPPER_REST_PATH, "agile_rest_api_version": "1.0", "verify": True, "resilient": True, "async": False, "async_workers": 5, "client_cert": None, "check_update": False, # amount of seconds to wait for loading a resource after updating it # used to avoid server side caching issues, used to be 4 seconds. "delay_reload": 0, "headers": { "Cache-Control": "no-cache", # 'Accept': 'application/json;charset=UTF-8', # default for REST "Content-Type": "application/json", # ;charset=UTF-8', # 'Accept': 'application/json', # default for REST # 'Pragma': 'no-cache', # 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT' "X-Atlassian-Token": "no-check", }, } checked_version = False # TODO(ssbarnea): remove these two variables and use the ones defined in resources JIRA_BASE_URL = Resource.JIRA_BASE_URL AGILE_BASE_URL = GreenHopperResource.AGILE_BASE_URL def __init__( self, server: str = None, options: Dict[str, Union[str, bool, Any]] = None, basic_auth: Union[None, Tuple[str, str]] = None, oauth: Dict[str, Any] = None, jwt: Dict[str, Any] = None, kerberos=False, kerberos_options: Dict[str, Any] = None, validate=False, get_server_info: bool = True, async_: bool = False, async_workers: int = 5, logging: bool = True, max_retries: int = 3, proxies: Any = None, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, auth: Tuple[str, str] = None, ): """Construct a Jira client instance. Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``, or ``atlas-run-standalone`` commands. By default, this instance runs at ``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use. Authentication is handled with the ``basic_auth`` argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests. For quick command line access to a server, see the ``jirashell`` script included with this distribution. The easiest way to instantiate is using ``j = JIRA("https://jira.atlasian.com")`` Args: server (Optional[str]): The server address and context path to use. Defaults to ``http://localhost:2990/jira``. options (Optional[Dict[str, Any]]): Specify the server and properties this client will use. Use a dict with any of the following properties: * server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``. * rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live. * rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``. * agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``greenhopper`` (old, private API). Check :py:class:`jira.resources.GreenHopperResource` for other supported values. * verify -- Verify SSL certs. Defaults to ``True``. * client_cert -- a tuple of (cert,key) for the requests library for client side SSL * check_update -- Check whether using the newest python-jira library version. basic_auth (Union[None, Tuple[str, str]]): A tuple of username and password to use when establishing a session via HTTP BASIC authentication. oauth (Optional[Any]): A dict of properties for OAuth authentication. The following properties are required: * access_token -- OAuth access token for the user * access_token_secret -- OAuth access token secret to sign with the key * consumer_key -- key of the OAuth application link defined in Jira * key_cert -- private key file to sign requests with (should be the pair of the public key supplied to Jira in the OAuth application link) kerberos (bool): If true it will enable Kerberos authentication. kerberos_options (Optional[Dict[str,str]]): A dict of properties for Kerberos authentication. The following properties are possible: * mutual_authentication -- string DISABLED or OPTIONAL. Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}`` jwt (Optional[Any]): A dict of properties for JWT authentication supported by Atlassian Connect. The following properties are required: * secret -- shared secret as delivered during 'installed' lifecycle event (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details) * payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss' Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}`` validate (bool): If true it will validate your credentials first. Remember that if you are accessing Jira as anonymous it will fail to instantiate. get_server_info (bool): If true it will fetch server version info first to determine if some API calls are available. async_ (bool): To enable async requests for those actions where we implemented it, like issue update() or delete(). async_workers (int): Set the number of worker threads for async operations. timeout (Optional[Union[Union[float, int], Tuple[float, float]]]): Set a read/connect timeout for the underlying calls to Jira (default: None). Obviously this means that you cannot rely on the return code when this is enabled. max_retries (int): Sets the amount Retries for the HTTP sessions initiated by the client. (Default: 3) proxies (Optional[Any]): Sets the proxies for the HTTP session. auth (Optional[Tuple[str,str]]): Set a cookie auth token if this is required. logging (bool): Determine whether or not logging should be enabled. (Default: True) """ # force a copy of the tuple to be used in __del__() because # sys.version_info could have already been deleted in __del__() self.sys_version_info = tuple([i for i in sys.version_info]) if options is None: options = {} if server and isinstance(server, dict): warnings.warn( "Old API usage, use JIRA(url) or JIRA(options={'server': url}, when using dictionary always use named parameters.", DeprecationWarning, ) options = server server = "" if server: options["server"] = server if async_: options["async"] = async_ options["async_workers"] = async_workers LOG.setLevel(_logging.INFO if logging else _logging.CRITICAL) self.log = LOG self._options: Dict[str, Any] = copy.copy(JIRA.DEFAULT_OPTIONS) self._options.update(options) self._rank = None # Rip off trailing slash since all urls depend on that assert isinstance(self._options["server"], str) # to help mypy if self._options["server"].endswith("/"): self._options["server"] = self._options["server"][:-1] context_path = urlparse(self.server_url).path if len(context_path) > 0: self._options["context_path"] = context_path self._try_magic() assert isinstance(self._options["headers"], dict) # for mypy benefit self._session: ResilientSession # for mypy benefit if oauth: self._create_oauth_session(oauth, timeout) elif basic_auth: self._create_http_basic_session(*basic_auth, timeout=timeout) self._session.headers.update(self._options["headers"]) elif jwt: self._create_jwt_session(jwt, timeout) elif kerberos: self._create_kerberos_session(timeout, kerberos_options=kerberos_options) elif auth: self._create_cookie_auth(auth, timeout) # always log in for cookie based auth, as we need a first request to be logged in validate = True else: verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.headers.update(self._options["headers"]) if "cookies" in self._options: self._session.cookies.update(self._options["cookies"]) self._session.max_retries = max_retries if proxies: self._session.proxies = proxies self.auth = auth if validate: # This will raise an Exception if you are not allowed to login. # It's better to fail faster than later. user = self.session() if user.raw is None: auth_method = ( oauth or basic_auth or jwt or kerberos or auth or "anonymous" ) raise JIRAError(f"Can not log in with {str(auth_method)}") self.deploymentType = None if get_server_info: # We need version in order to know what API calls are available or not si = self.server_info() try: self._version = tuple(si["versionNumbers"]) except Exception as e: self.log.error("invalid server_info: %s", si) raise e self.deploymentType = si.get("deploymentType") else: self._version = (0, 0, 0) if self._options["check_update"] and not JIRA.checked_version: self._check_update_() JIRA.checked_version = True self._fields = {} for f in self.fields(): if "clauseNames" in f: for name in f["clauseNames"]: self._fields[name] = f["id"] @property def server_url(self) -> str: """Return the server url""" return str(self._options["server"]) def _create_cookie_auth( self, auth: Tuple[str, str], timeout: Optional[Union[Union[float, int], Tuple[float, float]]], ): self._session = ResilientSession(timeout=timeout) self._session.auth = JiraCookieAuth(self._session, self.session, auth) self._session.verify = bool(self._options["verify"]) client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy self._session.cert = client_cert def _check_update_(self): """Check if the current version of the library is outdated.""" try: data = requests.get( "https://pypi.python.org/pypi/jira/json", timeout=2.001 ).json() released_version = data["info"]["version"] if parse_version(released_version) > parse_version(__version__): warnings.warn( "You are running an outdated version of Jira Python %s. Current version is %s. Do not file any bugs against older versions." % (__version__, released_version) ) except requests.RequestException: pass except Exception as e: self.log.warning(e) def __del__(self): """Destructor for JIRA instance.""" self.close() def close(self): session = getattr(self, "_session", None) if session is not None: try: session.close() except TypeError: # TypeError: "'NoneType' object is not callable" # Could still happen here because other references are also # in the process to be torn down, see warning section in # https://docs.python.org/2/reference/datamodel.html#object.__del__ pass self._session = None def _check_for_html_error(self, content: str): # Jira has the bad habit of returning errors in pages with 200 and # embedding the error in a huge webpage. if "<!-- SecurityTokenMissing -->" in content: self.log.warning("Got SecurityTokenMissing") raise JIRAError(f"SecurityTokenMissing: {content}") return False return True def _get_sprint_field_id(self): sprint_field_name = "Sprint" sprint_field_id = [ f["schema"]["customId"] for f in self.fields() if f["name"] == sprint_field_name ][0] return sprint_field_id def _fetch_pages( self, item_type: Type[ResourceType], items_key: Optional[str], request_path: str, startAt: int = 0, maxResults: int = 50, params: Dict[str, Any] = None, base: str = JIRA_BASE_URL, ) -> ResultList[ResourceType]: """Fetch from a paginated end point. Args: item_type (Type[Resource]): Type of single item. ResultList of such items will be returned. items_key (Optional[str]): Path to the items in JSON returned from server. Set it to None, if response is an array, and not a JSON object. request_path (str): path in request URL startAt (int): index of the first record to be fetched. (Default: 0) maxResults (int): Maximum number of items to return. If maxResults evaluates as False, it will try to get all items in batches. (Default:50) params (Dict[str, Any]): Params to be used in all requests. Should not contain startAt and maxResults, as they will be added for each request created from this function. base (str): base URL to use for the requests. Returns: ResultList """ async_workers = None async_class = None if self._options["async"]: try: from requests_futures.sessions import FuturesSession async_class = FuturesSession except ImportError: pass async_workers = self._options.get("async_workers") page_params = params.copy() if params else {} if startAt: page_params["startAt"] = startAt if maxResults: page_params["maxResults"] = maxResults resource = self._get_json(request_path, params=page_params, base=base) next_items_page = self._get_items_from_page(item_type, items_key, resource) items = next_items_page if True: # isinstance(resource, dict): if isinstance(resource, dict): total = resource.get("total") total = int(total) if total is not None else total # 'isLast' is the optional key added to responses in Jira Agile 6.7.6. So far not used in basic Jira API. is_last = resource.get("isLast", False) start_at_from_response = resource.get("startAt", 0) max_results_from_response = resource.get("maxResults", 1) else: # if is a list total = 1 is_last = True start_at_from_response = 0 max_results_from_response = 1 # If maxResults evaluates as False, get all items in batches if not maxResults: page_size = max_results_from_response or len(items) page_start = (startAt or start_at_from_response or 0) + page_size if ( async_class is not None and not is_last and (total is not None and len(items) < total) ): async_fetches = [] future_session = async_class( session=self._session, max_workers=async_workers ) for start_index in range(page_start, total, page_size): page_params = params.copy() if params else {} page_params["startAt"] = start_index page_params["maxResults"] = page_size url = self._get_url(request_path) r = future_session.get(url, params=page_params) async_fetches.append(r) for future in async_fetches: response = future.result() resource = json_loads(response) if resource: next_items_page = self._get_items_from_page( item_type, items_key, resource ) items.extend(next_items_page) while ( async_class is None and not is_last and (total is None or page_start < total) and len(next_items_page) == page_size ): page_params["startAt"] = page_start page_params["maxResults"] = page_size resource = self._get_json( request_path, params=page_params, base=base ) if resource: next_items_page = self._get_items_from_page( item_type, items_key, resource ) items.extend(next_items_page) page_start += page_size else: # if resource is an empty dictionary we assume no-results break return ResultList( items, start_at_from_response, max_results_from_response, total, is_last ) else: # TODO: unreachable # it seems that search_users can return a list() containing a single user! return ResultList( [item_type(self._options, self._session, resource)], 0, 1, 1, True ) def _get_items_from_page( self, item_type: Type[ResourceType], items_key: Optional[str], resource: Dict[str, Any], ) -> List[ResourceType]: try: return [ # We need to ignore the type here, as 'Resource' is an option item_type(self._options, self._session, raw_issue_json) # type: ignore for raw_issue_json in (resource[items_key] if items_key else resource) ] except KeyError as e: # improving the error text so we know why it happened raise KeyError(str(e) + " : " + json.dumps(resource)) # Information about this client def client_info(self) -> str: """Get the server this client is connected to.""" return self.server_url # Universal resource loading def find( self, resource_format: str, ids: Union[Tuple[str, str], int, str] = "" ) -> Resource: """Find Resource object for any addressable resource on the server. This method is a universal resource locator for any REST-ful resource in Jira. The argument ``resource_format`` is a string of the form ``resource``, ``resource/{0}``, ``resource/{0}/sub``, ``resource/{0}/sub/{1}``, etc. The format placeholders will be populated from the ``ids`` argument if present. The existing authentication session will be used. The return value is an untyped Resource object, which will not support specialized :py:meth:`.Resource.update` or :py:meth:`.Resource.delete` behavior. Moreover, it will not know to return an issue Resource if the client uses the resource issue path. For this reason, it is intended to support resources that are not included in the standard Atlassian REST API. Args: resource_format (str): the subpath to the resource string ids (Optional[Tuple]): values to substitute in the ``resource_format`` string Returns: Resource """ resource = Resource(resource_format, self._options, self._session) resource.find(ids) return resource @no_type_check # FIXME: This function fails type checking, probably a bug or two def async_do(self, size: int = 10): """Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads. Args: size (int): number of threads to run on. """ if hasattr(self._session, "_async_jobs"): self.log.info( "Executing asynchronous %s jobs found in queue by using %s threads..." % (len(self._session._async_jobs), size) ) threaded_requests.map(self._session._async_jobs, size=size) # Application properties # non-resource def application_properties( self, key: str = None ) -> Union[Dict[str, str], List[Dict[str, str]]]: """Return the mutable server application properties. Args: key (Optional[str]): the single property to return a value for Returns: Union[Dict[str, str], List[Dict[str, str]]] """ params = {} if key is not None: params["key"] = key return self._get_json("application-properties", params=params) def set_application_property(self, key: str, value: str): """Set the application property. Args: key (str): key of the property to set value (str): value to assign to the property """ url = self._get_latest_url("application-properties/" + key) payload = {"id": key, "value": value} return self._session.put(url, data=json.dumps(payload)) def applicationlinks(self, cached: bool = True) -> List: """List of application links. Returns: List[Dict]: json, or empty list """ self._applicationlinks: List[Dict] # for mypy benefit # if cached, return the last result if cached and hasattr(self, "_applicationlinks"): return self._applicationlinks # url = self._options['server'] + '/rest/applinks/latest/applicationlink' url = self.server_url + "/rest/applinks/latest/listApplicationlinks" r = self._session.get(url) o = json_loads(r) if "list" in o and isinstance(o, dict): self._applicationlinks = o["list"] else: self._applicationlinks = [] return self._applicationlinks # Attachments def attachment(self, id: str) -> Attachment: """Get an attachment Resource from the server for the specified ID. Args: id (str): The Attachment ID Returns: Attachment """ return self._find_for_resource(Attachment, id) # non-resource def attachment_meta(self) -> Dict[str, int]: """Get the attachment metadata. Return: Dict[str, int] """ return self._get_json("attachment/meta") @translate_resource_args def add_attachment( self, issue: str, attachment: Union[str, BufferedReader], filename: str = None ) -> Attachment: """Attach an attachment to an issue and returns a Resource for it. The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.) Args: issue (str): the issue to attach the attachment to attachment (Union[str,BufferedReader]): file-like object to attach to the issue, also works if it is a string with the filename. filename (str): optional name for the attached file. If omitted, the file object's ``name`` attribute is used. If you acquired the file-like object by any other method than ``open()``, make sure that a name is specified in one way or the other. Returns: Attachment """ close_attachment = False if isinstance(attachment, str): attachment: BufferedReader = open(attachment, "rb") # type: ignore attachment = cast(BufferedReader, attachment) close_attachment = True elif isinstance(attachment, BufferedReader) and attachment.mode != "rb": self.log.warning( "%s was not opened in 'rb' mode, attaching file may fail." % attachment.name ) url = self._get_url("issue/" + str(issue) + "/attachments") fname = filename if not fname and isinstance(attachment, BufferedReader): fname = os.path.basename(attachment.name) if "MultipartEncoder" not in globals(): method = "old" try: r = self._session.post( url, files={"file": (fname, attachment, "application/octet-stream")}, headers=CaseInsensitiveDict( {"content-type": None, "X-Atlassian-Token": "no-check"} ), ) finally: if close_attachment: attachment.close() else: method = "MultipartEncoder" def file_stream() -> MultipartEncoder: """Returns files stream of attachment.""" return MultipartEncoder( fields={"file": (fname, attachment, "application/octet-stream")} ) m = file_stream() try: r = self._session.post( url, data=m, headers=CaseInsensitiveDict( { "content-type": m.content_type, "X-Atlassian-Token": "no-check", } ), retry_data=file_stream, ) finally: if close_attachment: attachment.close() js: Union[Dict[str, Any], List[Dict[str, Any]]] = json_loads(r) if not js or not isinstance(js, Iterable): raise JIRAError(f"Unable to parse JSON: {js}") jira_attachment = Attachment( self._options, self._session, js[0] if isinstance(js, List) else js ) if jira_attachment.size == 0: raise JIRAError( "Added empty attachment via %s method?!: r: %s\nattachment: %s" % (method, r, jira_attachment) ) return jira_attachment def delete_attachment(self, id: str) -> Response: """Delete attachment by id. Args: id (str): ID of the attachment to delete Returns: Response """ url = self._get_url("attachment/" + str(id)) return self._session.delete(url) # Components def component(self, id: str): """Get a component Resource from the server. Args: id (str): ID of the component to get """ return self._find_for_resource(Component, id) @translate_resource_args def create_component( self, name: str, project: str, description=None, leadUserName=None, assigneeType=None, isAssigneeTypeValid=False, ) -> Component: """Create a component inside a project and return a Resource for it. Args: name (str): name of the component project (str): key of the project to create the component in description (str): a description of the component leadUserName (Optional[str]): the username of the user responsible for this component assigneeType (Optional[str]): see the ComponentBean.AssigneeType class for valid values isAssigneeTypeValid (bool): boolean specifying whether the assignee type is acceptable (Default: False) Returns: Component """ data = { "name": name, "project": project, "isAssigneeTypeValid": isAssigneeTypeValid, } if description is not None: data["description"] = description if leadUserName is not None: data["leadUserName"] = leadUserName if assigneeType is not None: data["assigneeType"] = assigneeType url = self._get_url("component") r = self._session.post(url, data=json.dumps(data)) component = Component(self._options, self._session, raw=json_loads(r)) return component def component_count_related_issues(self, id: str): """Get the count of related issues for a component. Args: id (str): ID of the component to use """ data: Dict[str, Any] = self._get_json( "component/" + str(id) + "/relatedIssueCounts" ) return data["issueCount"] def delete_component(self, id: str) -> Response: """Delete component by id. Args: id (str): ID of the component to use Returns: Response """ url = self._get_url("component/" + str(id)) return self._session.delete(url) # Custom field options def custom_field_option(self, id: str) -> CustomFieldOption: """Get a custom field option Resource from the server. Args: id (str): ID of the custom field to use Returns: CustomFieldOption """ return self._find_for_resource(CustomFieldOption, id) # Dashboards def dashboards( self, filter=None, startAt=0, maxResults=20 ) -> ResultList[Dashboard]: """Return a ResultList of Dashboard resources and a ``total`` count. Args: filter (Optional[str]): either "favourite" or "my", the type of dashboards to return startAt (int): index of the first dashboard to return (Default: 0) maxResults (int): maximum number of dashboards to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 20) Returns: ResultList """ params = {} if filter is not None: params["filter"] = filter return self._fetch_pages( Dashboard, "dashboards", "dashboard", startAt, maxResults, params ) def dashboard(self, id: str) -> Dashboard: """Get a dashboard Resource from the server. Args: id (str): ID of the dashboard to get. Returns: Dashboard """ return self._find_for_resource(Dashboard, id) # Fields # non-resource def fields(self) -> List[Dict[str, Any]]: """Return a list of all issue fields. Returns: List[Dict[str, Any]] """ return self._get_json("field") # Filters def filter(self, id: str) -> Filter: """Get a filter Resource from the server. Args: id (str): ID of the filter to get. Returns: Filter """ return self._find_for_resource(Filter, id) def favourite_filters(self) -> List[Filter]: """Get a list of filter Resources which are the favourites of the currently authenticated user. Returns: List[Filter] """ r_json: List[Dict[str, Any]] = self._get_json("filter/favourite") filters = [ Filter(self._options, self._session, raw_filter_json) for raw_filter_json in r_json ] return filters def create_filter( self, name: str = None, description: str = None, jql: str = None, favourite: bool = None, ): """Create a new filter and return a filter Resource for it. Args: name (str): name of the new filter description (str): useful human readable description of the new filter jql (str): query string that defines the filter favourite (bool): whether to add this filter to the current user's favorites Returns: Filter """ data: Dict[str, Any] = {} if name is not None: data["name"] = name if description is not None: data["description"] = description if jql is not None: data["jql"] = jql if favourite is not None: data["favourite"] = favourite url = self._get_url("filter") r = self._session.post(url, data=json.dumps(data)) raw_filter_json: Dict[str, Any] = json_loads(r) return Filter(self._options, self._session, raw=raw_filter_json) def update_filter( self, filter_id, name: str = None, description: str = None, jql: str = None, favourite: bool = None, ): """Update a filter and return a filter Resource for it. Args: name (Optional[str]): name of the new filter description (Optional[str]): useful human readable description of the new filter jql (Optional[str]): query string that defines the filter favourite (Optional[bool]): whether to add this filter to the current user's favorites """ filter = self.filter(filter_id) data = {} data["name"] = name or filter.name data["description"] = description or filter.description data["jql"] = jql or filter.jql data["favourite"] = favourite or filter.favourite url = self._get_url(f"filter/{filter_id}") r = self._session.put( url, headers={"content-type": "application/json"}, data=json.dumps(data) ) raw_filter_json = json.loads(r.text) return Filter(self._options, self._session, raw=raw_filter_json) # Groups def group(self, id: str, expand: Any = None) -> Group: """Get a group Resource from the server. Args: id (str): ID of the group to get expand (Optional[Any]): Extra information to fetch inside each resource Returns: Group """ group = Group(self._options, self._session) params = {} if expand is not None: params["expand"] = expand group.find(id, params=params) return group # non-resource def groups( self, query: Optional[str] = None, exclude: Optional[Any] = None, maxResults: int = 9999, ) -> List[str]: """Return a list of groups matching the specified criteria. Args: query (Optional[str]): filter groups by name with this string exclude (Optional[Any]): filter out groups by name with this string maxResults (int): maximum results to return. (Default: 9999) Returns: List[str] """ params: Dict[str, Any] = {} groups = [] if query is not None: params["query"] = query if exclude is not None: params["exclude"] = exclude if maxResults is not None: params["maxResults"] = maxResults for group in self._get_json("groups/picker", params=params)["groups"]: groups.append(group["name"]) return sorted(groups) def group_members(self, group: str) -> OrderedDict: """Return a hash or users with their information. Requires Jira 6.0 or will raise NotImplemented. Args: group (str): Name of the group. """ if self._version < (6, 0, 0): raise NotImplementedError( "Group members is not implemented in Jira before version 6.0, upgrade the instance, if possible." ) params = {"groupname": group, "expand": "users"} r = self._get_json("group", params=params) size = r["users"]["size"] end_index = r["users"]["end-index"] while end_index < size - 1: params = { "groupname": group, "expand": f"users[{end_index + 1}:{end_index + 50}]", } r2 = self._get_json("group", params=params) for user in r2["users"]["items"]: r["users"]["items"].append(user) end_index = r2["users"]["end-index"] size = r["users"]["size"] result = {} for user in r["users"]["items"]: result[user["id"]] = { "name": user.get("name"), "id": user.get("id"), "accountId": user.get("accountId"), "fullname": user.get("displayName"), "email": user.get("emailAddress", "hidden"), "active": user.get("active"), "timezone": user.get("timezone"), } return OrderedDict(sorted(result.items(), key=lambda t: t[0])) def add_group(self, groupname: str) -> bool: """Create a new group in Jira. Args: groupname (str): The name of the group you wish to create. Returns: bool: True if successful. """ url = self._get_latest_url("group") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 x = OrderedDict() x["name"] = groupname payload = json.dumps(x) self._session.post(url, data=payload) return True def remove_group(self, groupname: str) -> bool: """Delete a group from the Jira instance. Args: groupname (str): The group to be deleted from the Jira instance. Returns: bool: Returns True on success. """ # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 url = self._get_latest_url("group") x = {"groupname": groupname} self._session.delete(url, params=x) return True # Issues def issue( self, id: Union[Issue, str], fields: Optional[str] = None, expand: Optional[str] = None, ) -> Issue: """Get an issue Resource from the server. Args: id (Union[Issue, str]): ID or key of the issue to get fields (Optional[str]): comma-separated string of issue fields to include in the results expand (Optional[str]): extra information to fetch inside each resource Returns: Issue """ # this allows us to pass Issue objects to issue() if isinstance(id, Issue): return id issue = Issue(self._options, self._session) params = {} if fields is not None: params["fields"] = fields if expand is not None: params["expand"] = expand issue.find(id, params=params) return issue def create_issue( self, fields: Optional[Dict[str, Any]] = None, prefetch: bool = True, **fieldargs, ) -> Issue: """Create a new issue and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. By default, the client will immediately reload the issue Resource created by this method in order to return a complete Issue object to the caller; this behavior can be controlled through the 'prefetch' argument. Jira projects may contain many different issue types. Some issue screens have different requirements for fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue Args: fields (Optional[Dict[str, Any]]): a dict containing field names and the values to use. If present, all other keyword arguments will be ignored prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value returned from this method Returns: Issue """ data: Dict[str, Any] = _field_worker(fields, **fieldargs) p = data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): data["fields"]["project"] = {"id": self.project(str(p)).id} p = data["fields"]["issuetype"] if isinstance(p, int): data["fields"]["issuetype"] = {"id": p} if isinstance(p, str) or isinstance(p, int): data["fields"]["issuetype"] = {"id": self.issue_type_by_name(str(p)).id} url = self._get_url("issue") r = self._session.post(url, data=json.dumps(data)) raw_issue_json = json_loads(r) if "key" not in raw_issue_json: raise JIRAError( status_code=r.status_code, response=r, url=url, text=json.dumps(data) ) if prefetch: return self.issue(raw_issue_json["key"]) else: return Issue(self._options, self._session, raw=raw_issue_json) def create_issues( self, field_list: List[Dict[str, Any]], prefetch: bool = True ) -> List[Dict[str, Any]]: """Bulk create new issues and return an issue Resource for each successfully created issue. See `create_issue` documentation for field information. Args: field_list (List[Dict[str, Any]]): a list of dicts each containing field names and the values to use. Each dict is an individual issue to create and is subject to its minimum requirements. prefetch (bool): whether to reload the created issue Resource for each created issue so that all of its data is present in the value returned from this method. Returns: List[Dict[str, Any]] """ data: Dict[str, List] = {"issueUpdates": []} for field_dict in field_list: issue_data: Dict[str, Any] = _field_worker(field_dict) p = issue_data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): issue_data["fields"]["project"] = {"id": self.project(str(p)).id} p = issue_data["fields"]["issuetype"] if isinstance(p, int): issue_data["fields"]["issuetype"] = {"id": p} if isinstance(p, str): issue_data["fields"]["issuetype"] = { "id": self.issue_type_by_name(str(p)).id } data["issueUpdates"].append(issue_data) url = self._get_url("issue/bulk") try: r = self._session.post(url, data=json.dumps(data)) raw_issue_json = json_loads(r) # Catching case where none of the issues has been created. See https://github.com/pycontribs/jira/issues/350 except JIRAError as je: if je.status_code == 400 and je.response: raw_issue_json = json.loads(je.response.text) else: raise issue_list = [] errors = {} for error in raw_issue_json["errors"]: errors[error["failedElementNumber"]] = error["elementErrors"]["errors"] for index, fields in enumerate(field_list): if index in errors: issue_list.append( { "status": "Error", "error": errors[index], "issue": None, "input_fields": fields, } ) else: issue = raw_issue_json["issues"].pop(0) if prefetch: issue = self.issue(issue["key"]) else: issue = Issue(self._options, self._session, raw=issue) issue_list.append( { "status": "Success", "issue": issue, "error": None, "input_fields": fields, } ) return issue_list def supports_service_desk(self): """Returns whether or not the Jira instance supports service desk. Returns: bool """ url = self.server_url + "/rest/servicedeskapi/info" headers = {"X-ExperimentalApi": "opt-in"} try: r = self._session.get(url, headers=headers) return r.status_code == 200 except JIRAError: return False def create_customer(self, email: str, displayName: str) -> Customer: """Create a new customer and return an issue Resource for it. Args: email (str): Customer Email displayName (str): Customer display name Returns: Customer """ url = self.server_url + "/rest/servicedeskapi/customer" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post( url, headers=headers, data=json.dumps({"email": email, "displayName": displayName}), ) raw_customer_json = json_loads(r) if r.status_code != 201: raise JIRAError(status_code=r.status_code, request=r) return Customer(self._options, self._session, raw=raw_customer_json) def service_desks(self) -> List[ServiceDesk]: """Get a list of ServiceDesk Resources from the server visible to the current authenticated user. Returns: List[ServiceDesk] """ url = self.server_url + "/rest/servicedeskapi/servicedesk" headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) print(r_json) projects = [ ServiceDesk(self._options, self._session, raw_project_json) for raw_project_json in r_json["values"] ] return projects def service_desk(self, id: str) -> ServiceDesk: """Get a Service Desk Resource from the server. Args: id (str): ID or key of the Service Desk to get Returns: ServiceDesk """ return self._find_for_resource(ServiceDesk, id) @no_type_check # FIXME: This function does not do what it wants to with fieldargs def create_customer_request( self, fields: Dict[str, Any] = None, prefetch: bool = True, **fieldargs ) -> Issue: """Create a new customer request and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. By default, the client will immediately reload the issue Resource created by this method in order to return a complete Issue object to the caller; this behavior can be controlled through the 'prefetch' argument. Jira projects may contain many different issue types. Some issue screens have different requirements for fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue Args: fields (Dict[str, Any]): a dict containing field names and the values to use. If present, all other keyword arguments will be ignored prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value returned from this method Returns: Issue """ data = fields p = data["serviceDeskId"] service_desk = None if isinstance(p, str) or isinstance(p, int): service_desk = self.service_desk(p) elif isinstance(p, ServiceDesk): service_desk = p data["serviceDeskId"] = service_desk.id p = data["requestTypeId"] if isinstance(p, int): data["requestTypeId"] = p elif isinstance(p, str): data["requestTypeId"] = self.request_type_by_name(service_desk, p).id url = self.server_url + "/rest/servicedeskapi/request" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post(url, headers=headers, data=json.dumps(data)) raw_issue_json = json_loads(r) if "issueKey" not in raw_issue_json: raise JIRAError(status_code=r.status_code, request=r) if prefetch: return self.issue(raw_issue_json["issueKey"]) else: return Issue(self._options, self._session, raw=raw_issue_json) def createmeta( self, projectKeys: Optional[Union[Tuple[str, str], str]] = None, projectIds: Union[List, Tuple[str, str]] = [], issuetypeIds: Optional[List[str]] = None, issuetypeNames: Optional[str] = None, expand: Optional[str] = None, ) -> Dict[str, Any]: """Get the metadata required to create issues, optionally filtered by projects and issue types. Args: projectKeys (Optional[Union[Tuple[str, str], str]]): keys of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectIds. projectIds (Union[List, Tuple[str, str]]): IDs of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectKeys. issuetypeIds (Optional[List[str]]): IDs of the issue types to filter the results with. Can be a single value or a comma-delimited string. May be combined with issuetypeNames. issuetypeNames (Optional[str]): Names of the issue types to filter the results with. Can be a single value or a comma-delimited string. May be combined with issuetypeIds. expand (Optional[str]): extra information to fetch inside each resource. Returns: Dict[str, Any] """ params: Dict[str, Any] = {} if projectKeys is not None: params["projectKeys"] = projectKeys if projectIds is not None: if isinstance(projectIds, str): projectIds = projectIds.split(",") params["projectIds"] = projectIds if issuetypeIds is not None: params["issuetypeIds"] = issuetypeIds if issuetypeNames is not None: params["issuetypeNames"] = issuetypeNames if expand is not None: params["expand"] = expand return self._get_json("issue/createmeta", params) def _get_user_key(self, user: str) -> str: """Internal method for translating an user (str) to an key.""" try: key = self.search_users(user, maxResults=1)[0].key except Exception as e: raise JIRAError(str(e)) return key # non-resource @translate_resource_args def assign_issue(self, issue: Union[int, str], assignee: str) -> bool: """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. Args: issue (Union[int,str]): the issue ID or key to assign assignee (str): the user to assign the issue to Returns: bool """ url = self._get_latest_url("issue/{}/assignee".format(str(issue))) payload = {"name": self._get_user_key(assignee)} # 'key' and 'name' are deprecated in favor of accountId r = self._session.put(url, data=json.dumps(payload)) raise_on_error(r) return True @translate_resource_args def comments(self, issue: str, expand: Optional[str] = None) -> List[Comment]: """Get a list of comment Resources. :param issue: the issue to get comments from :type issue: str :param expand: extra information to fetch for each comment such as renderedBody and properties. :type expand: str :rtype: List[Comment] """ params = {} if expand is not None: params["expand"] = expand r_json = self._get_json("issue/{}/comment".format(str(issue)), params=params) comments = [ Comment(self._options, self._session, raw_comment_json) for raw_comment_json in r_json["comments"] ] return comments @translate_resource_args def comment( self, issue: str, comment: str, expand: Optional[str] = None ) -> Comment: """Get a comment Resource from the server for the specified ID. :param issue: ID or key of the issue to get the comment from :param comment: ID of the comment to get :param expand: extra information to fetch for comment such as renderedBody and properties. """ return self._find_for_resource(Comment, (issue, comment), expand=expand) @translate_resource_args def add_comment( self, issue: str, body: str, visibility: Optional[Dict[str, str]] = None, is_internal: bool = False, ) -> Comment: """Add a comment from the current authenticated user on the specified issue and return a Resource for it. The issue identifier and comment body are required. Args: issue (str): ID or key of the issue to add the comment to body (str): Text of the comment to add visibility (Optional[Dict[str, str]]): a dict containing two entries: "type" and "value". "type" is 'role' (or 'group' if the Jira server has configured comment visibility for groups) and 'value' is the name of the role (or group) to which viewing of this comment will be restricted. is_internal (bool): Defines whether a comment has to be marked as 'Internal' in Jira Service Desk (Default: False) Returns: Comment: the created comment """ data: Dict[str, Any] = {"body": body} if is_internal: data.update( { "properties": [ {"key": "sd.public.comment", "value": {"internal": is_internal}} ] } ) if visibility is not None: data["visibility"] = visibility url = self._get_url("issue/" + str(issue) + "/comment") r = self._session.post(url, data=json.dumps(data)) comment = Comment(self._options, self._session, raw=json_loads(r)) return comment # non-resource @translate_resource_args def editmeta(self, issue: Union[str, int]): """Get the edit metadata for an issue. Args: issue (str): the issue to get metadata for Returns: Dict[str, Dict[str, Dict[str, Any]]] """ return self._get_json("issue/" + str(issue) + "/editmeta") @translate_resource_args def remote_links(self, issue: Union[str, int]) -> List[RemoteLink]: """Get a list of remote link Resources from an issue. Args: issue (str): the issue to get remote links from """ r_json = self._get_json("issue/" + str(issue) + "/remotelink") remote_links = [ RemoteLink(self._options, self._session, raw_remotelink_json) for raw_remotelink_json in r_json ] return remote_links @translate_resource_args def remote_link(self, issue: str, id: str) -> RemoteLink: """Get a remote link Resource from the server. Args: issue (str): the issue holding the remote link id (str): ID of the remote link """ return self._find_for_resource(RemoteLink, (issue, id)) # removed the @translate_resource_args because it prevents us from finding # information for building a proper link def add_remote_link( self, issue: str, destination: Union[Issue, Dict[str, Any]], globalId: Optional[str] = None, application: Optional[Dict[str, Any]] = None, relationship: Optional[str] = None, ) -> RemoteLink: """Add a remote link from an issue to an external application and returns a remote link Resource for it. ``destination`` should be a dict containing at least ``url`` to the linked external URL and ``title`` to display for the link inside Jira. For definitions of the allowable fields for ``object`` and the keyword arguments ``globalId``, ``application`` and ``relationship``, see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. Args: issue (str): the issue to add the remote link to destination (Union[Issue, Dict[str, Any]]): the link details to add (see the above link for details) globalId (Optional[str]): unique ID for the link (see the above link for details) application (Optional[Dict[str,Any]]): application information for the link (see the above link for details) relationship (Optional[str]): relationship description for the link (see the above link for details) Returns: RemoteLink: the added remote lint """ try: applicationlinks: List[Dict] = self.applicationlinks() except JIRAError as e: applicationlinks = [] # In many (if not most) configurations, non-admin users are # not allowed to list applicationlinks; if we aren't allowed, # let's let people try to add remote links anyway, we just # won't be able to be quite as helpful. warnings.warn( "Unable to gather applicationlinks; you will not be able " "to add links to remote issues: (%s) %s" % (e.status_code, e.text), Warning, ) data: Dict[str, Any] = {} if isinstance(destination, Issue) and destination.raw: data["object"] = {"title": str(destination), "url": destination.permalink()} for x in applicationlinks: if x["application"]["displayUrl"] == destination._options["server"]: data["globalId"] = "appId=%s&issueId=%s" % ( x["application"]["id"], destination.raw["id"], ) data["application"] = { "name": x["application"]["name"], "type": "com.atlassian.jira", } break if "globalId" not in data: raise NotImplementedError("Unable to identify the issue to link to.") else: if globalId is not None: data["globalId"] = globalId if application is not None: data["application"] = application data["object"] = destination if relationship is not None: data["relationship"] = relationship # check if the link comes from one of the configured application links if isinstance(destination, Issue) and destination.raw: for x in applicationlinks: if x["application"]["displayUrl"] == self.server_url: data["globalId"] = "appId=%s&issueId=%s" % ( x["application"]["id"], destination.raw["id"], # .raw only present on Issue ) data["application"] = { "name": x["application"]["name"], "type": "com.atlassian.jira", } break url = self._get_url("issue/" + str(issue) + "/remotelink") r = self._session.post(url, data=json.dumps(data)) remote_link = RemoteLink(self._options, self._session, raw=json_loads(r)) return remote_link def add_simple_link(self, issue: str, object: Dict[str, Any]): """Add a simple remote link from an issue to web resource. This avoids the admin access problems from add_remote_link by just using a simple object and presuming all fields are correct and not requiring more complex ``application`` data. ``object`` should be a dict containing at least ``url`` to the linked external URL and ``title`` to display for the link inside Jira. For definitions of the allowable fields for ``object`` , see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. Args: issue (str): the issue to add the remote link to object (Dict[str,Any]): the dictionary used to create remotelink data Returns: RemoteLint """ data = {"object": object} url = self._get_url("issue/" + str(issue) + "/remotelink") r = self._session.post(url, data=json.dumps(data)) simple_link = RemoteLink(self._options, self._session, raw=json_loads(r)) return simple_link # non-resource @translate_resource_args def transitions(self, issue: str, id: Optional[str] = None, expand=None): """Get a list of the transitions available on the specified issue to the current user. Args: issue (str): ID or key of the issue to get the transitions from id (Optional[str]): if present, get only the transition matching this ID expand (Optional): extra information to fetch inside each transition Returns: Any: json of response """ params = {} if id is not None: params["transitionId"] = id if expand is not None: params["expand"] = expand return self._get_json("issue/" + str(issue) + "/transitions", params=params)[ "transitions" ] def find_transitionid_by_name( self, issue: str, transition_name: str ) -> Optional[int]: """Get a transitionid available on the specified issue to the current user. Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference Args: issue (str): ID or key of the issue to get the transitions from trans_name (str): iname of transition we are looking for """ transitions_json = self.transitions(issue) id: Optional[int] = None for transition in transitions_json: if transition["name"].lower() == transition_name.lower(): id = transition["id"] break return id @translate_resource_args def transition_issue( self, issue: str, transition: str, fields: Optional[Dict[str, Any]] = None, comment: Optional[str] = None, worklog: Optional[str] = None, **fieldargs, ): """Perform a transition on an issue. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. Field values will be set on the issue as part of the transition process. Args: issue (str): ID or key of the issue to perform the transition on transition (str): ID or name of the transition to perform fields (Optional[Dict[str,Any]]): a dict containing field names and the values to use. comment (Optional[str]): String to add as comment to the issue when performing the transition. workload (Optional[str]): String to add as time spent on the issue when performing the transition. **fieldargs: If present, all other keyword arguments will be ignored """ transitionId: Optional[int] = None try: transitionId = int(transition) except Exception: # cannot cast to int, so try to find transitionId by name transitionId = self.find_transitionid_by_name(issue, transition) if transitionId is None: raise JIRAError(f"Invalid transition name. {transition}") data: Dict[str, Any] = {"transition": {"id": transitionId}} if comment: data["update"] = {"comment": [{"add": {"body": comment}}]} if worklog: data["update"] = {"worklog": [{"add": {"timeSpent": worklog}}]} if fields is not None: data["fields"] = fields else: fields_dict = {} for field in fieldargs: fields_dict[field] = fieldargs[field] data["fields"] = fields_dict url = self._get_url("issue/" + str(issue) + "/transitions") r = self._session.post(url, data=json.dumps(data)) try: r_json = json_loads(r) except ValueError as e: self.log.error(f"{e}\n{r.text}") raise e return r_json @translate_resource_args def votes(self, issue: str) -> Votes: """Get a votes Resource from the server. Args: issue (str): ID or key of the issue to get the votes for Returns: Votes """ return self._find_for_resource(Votes, issue) @translate_resource_args def add_vote(self, issue: str) -> Response: """Register a vote for the current authenticated user on an issue. Args: issue (str): ID or key of the issue to vote on Returns: Response """ url = self._get_url("issue/" + str(issue) + "/votes") return self._session.post(url) @translate_resource_args def remove_vote(self, issue: str): """Remove the current authenticated user's vote from an issue. Args: issue (str): ID or key of the issue to remove vote on """ url = self._get_url("issue/" + str(issue) + "/votes") self._session.delete(url) @translate_resource_args def watchers(self, issue: str) -> Watchers: """Get a watchers Resource from the server for an issue. Args: issue (str): ID or key of the issue to get the watchers for Returns: Watchers """ return self._find_for_resource(Watchers, issue) @translate_resource_args def add_watcher(self, issue: str, watcher: str) -> Response: """Add a user to an issue's watchers list. Args: issue (str): ID or key of the issue affected watcher (str): key of the user to add to the watchers list """ url = self._get_url("issue/" + str(issue) + "/watchers") return self._session.post(url, data=json.dumps(watcher)) @translate_resource_args def remove_watcher(self, issue: str, watcher: str) -> Response: """Remove a user from an issue's watch list. Args: issue (str): ID or key of the issue affected watcher (str): key of the user to remove from the watchers list Returns: Response """ url = self._get_url("issue/" + str(issue) + "/watchers") # https://docs.atlassian.com/software/jira/docs/api/REST/8.13.6/#api/2/issue-removeWatcher params = {"username": watcher} result = self._session.delete(url, params=params) return result @translate_resource_args def worklogs(self, issue: str) -> List[Worklog]: """Get a list of worklog Resources from the server for an issue. Args: issue (str): ID or key of the issue to get worklogs from Returns: List[Worklog] """ r_json = self._get_json("issue/" + str(issue) + "/worklog") worklogs = [ Worklog(self._options, self._session, raw_worklog_json) for raw_worklog_json in r_json["worklogs"] ] return worklogs @translate_resource_args def worklog(self, issue: str, id: str) -> Worklog: """Get a specific worklog Resource from the server. Args: issue (str): ID or key of the issue to get the worklog from id (str): ID of the worklog to get Returns: Worklog """ return self._find_for_resource(Worklog, (issue, id)) @translate_resource_args def add_worklog( self, issue, timeSpent: (Optional[str]) = None, timeSpentSeconds: (Optional[str]) = None, adjustEstimate: (Optional[str]) = None, newEstimate: (Optional[str]) = None, reduceBy: (Optional[str]) = None, comment: (Optional[str]) = None, started: (Optional[datetime.datetime]) = None, user: (Optional[str]) = None, ) -> Worklog: """Add a new worklog entry on an issue and return a Resource for it. Args: issue (str): the issue to add the worklog to timeSpent (Optional[str]): a worklog entry with this amount of time spent, e.g. "2d" timeSpentSeconds (Optional[str]): a worklog entry with this amount of time spent in seconds adjustEstimate (Optional[str]): allows the user to provide specific instructions to update the remaining time estimate of the issue. The value can either be ``new``, ``leave``, ``manual`` or ``auto`` (default). newEstimate (Optional[str]): the new value for the remaining estimate field. e.g. "2d" reduceBy (Optional[str]): the amount to reduce the remaining estimate by e.g. "2d" comment (Optional[str]): optional worklog comment started (Optional[datetime.datetime]): Moment when the work is logged, if not specified will default to now user (Optional[str]): the user ID or name to use for this worklog Returns: Worklog """ params = {} if adjustEstimate is not None: params["adjustEstimate"] = adjustEstimate if newEstimate is not None: params["newEstimate"] = newEstimate if reduceBy is not None: params["reduceBy"] = reduceBy data: Dict[str, Any] = {} if timeSpent is not None: data["timeSpent"] = timeSpent if timeSpentSeconds is not None: data["timeSpentSeconds"] = timeSpentSeconds if comment is not None: data["comment"] = comment elif user: # we log user inside comment as it doesn't always work data["comment"] = user if started is not None: # based on REST Browser it needs: "2014-06-03T08:21:01.273+0000" if started.tzinfo is None: data["started"] = started.strftime("%Y-%m-%dT%H:%M:%S.000+0000") else: data["started"] = started.strftime("%Y-%m-%dT%H:%M:%S.000%z") if user is not None: data["author"] = { "name": user, "self": self.JIRA_BASE_URL + "/rest/api/latest/user?username=" + user, "displayName": user, "active": False, } data["updateAuthor"] = data["author"] # report bug to Atlassian: author and updateAuthor parameters are # ignored. url = self._get_url(f"issue/{issue}/worklog") r = self._session.post(url, params=params, data=json.dumps(data)) return Worklog(self._options, self._session, json_loads(r)) # Issue links @translate_resource_args def create_issue_link( self, type: Union[str, IssueLinkType], inwardIssue: str, outwardIssue: str, comment: Optional[Dict[str, Any]] = None, ) -> Response: """Create a link between two issues. Args: type (Union[str,IssueLinkType]): the type of link to create inwardIssue: the issue to link from outwardIssue: the issue to link to comment (Optional[Dict[str, Any]]): a comment to add to the issues with the link. Should be a dict containing ``body`` and ``visibility`` fields: ``body`` being the text of the comment and ``visibility`` being a dict containing two entries: ``type`` and ``value``. ``type`` is ``role`` (or ``group`` if the Jira server has configured comment visibility for groups) and ``value`` is the name of the role (or group) to which viewing of this comment will be restricted. Returns: Response """ # let's see if we have the right issue link 'type' and fix it if needed issue_link_types = self.issue_link_types() if type not in issue_link_types: for lt in issue_link_types: if lt.outward == type: # we are smart to figure it out what he meant type = lt.name break elif lt.inward == type: # so that's the reverse, so we fix the request type = lt.name inwardIssue, outwardIssue = outwardIssue, inwardIssue break data = { "type": {"name": type}, "inwardIssue": {"key": inwardIssue}, "outwardIssue": {"key": outwardIssue}, "comment": comment, } url = self._get_url("issueLink") return self._session.post(url, data=json.dumps(data)) def delete_issue_link(self, id: str): """Delete a link between two issues. Args: id (str): ID of the issue link to delete """ url = self._get_url("issueLink") + "/" + id return self._session.delete(url) def issue_link(self, id: str): """Get an issue link Resource from the server. Args: id (str): ID of the issue link to get """ return self._find_for_resource(IssueLink, id) # Issue link types def issue_link_types(self, force: bool = False) -> List[IssueLinkType]: """Get a list of issue link type Resources from the server. Returns: List[IssueLinkType] """ if not hasattr(self, "self._cached_issue_link_types") or force: r_json = self._get_json("issueLinkType") self._cached_issue_link_types = [ IssueLinkType(self._options, self._session, raw_link_json) for raw_link_json in r_json["issueLinkTypes"] ] return self._cached_issue_link_types def issue_link_type(self, id: str) -> IssueLinkType: """Get an issue link type Resource from the server. Args: id (str): ID of the issue link type to get Returns: IssueLinkType """ return self._find_for_resource(IssueLinkType, id) # Issue types def issue_types(self) -> List[IssueType]: """Get a list of issue type Resources from the server. Returns: List[IssueType] """ r_json = self._get_json("issuetype") issue_types = [ IssueType(self._options, self._session, raw_type_json) for raw_type_json in r_json ] return issue_types def issue_type(self, id: str) -> IssueType: """Get an issue type Resource from the server. Args: id (str): ID of the issue type to get Returns: IssueType """ return self._find_for_resource(IssueType, id) def issue_type_by_name(self, name: str) -> IssueType: """ Args: name (str): Name of the issue type Returns: IssueType """ matching_issue_types = [it for it in self.issue_types() if it.name == name] if len(matching_issue_types) == 1: return matching_issue_types[0] elif len(matching_issue_types) == 0: raise KeyError(f"Issue type '{name}' is unknown.") else: raise KeyError(f"Issue type '{name}' appears more than once.") def request_types(self, service_desk: ServiceDesk) -> List[RequestType]: """Returns request types supported by a service desk instance. Args: service_desk (ServiceDesk): The service desk instance. Returns: List[RequestType] """ if hasattr(service_desk, "id"): service_desk = service_desk.id url = ( self.server_url + f"/rest/servicedeskapi/servicedesk/{service_desk}/requesttype" ) headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) request_types = [ RequestType(self._options, self._session, raw_type_json) for raw_type_json in r_json["values"] ] return request_types def request_type_by_name(self, service_desk: ServiceDesk, name: str): request_types = self.request_types(service_desk) try: request_type = [rt for rt in request_types if rt.name == name][0] except IndexError: raise KeyError(f"Request type '{name}' is unknown.") return request_type # User permissions # non-resource def my_permissions( self, projectKey: Optional[str] = None, projectId: Optional[str] = None, issueKey: Optional[str] = None, issueId: Optional[str] = None, ) -> Dict[str, Dict[str, Dict[str, str]]]: """Get a dict of all available permissions on the server. Args: projectKey (Optional[str]): limit returned permissions to the specified project projectId (Optional[str]): limit returned permissions to the specified project issueKey (Optional[str]): limit returned permissions to the specified issue issueId (Optional[str]): limit returned permissions to the specified issue Returns: Dict[str, Dict[str, Dict[str, str]]] """ params = {} if projectKey is not None: params["projectKey"] = projectKey if projectId is not None: params["projectId"] = projectId if issueKey is not None: params["issueKey"] = issueKey if issueId is not None: params["issueId"] = issueId return self._get_json("mypermissions", params=params) # Priorities def priorities(self): """Get a list of priority Resources from the server. Returns: List[Priority] """ r_json = self._get_json("priority") priorities = [ Priority(self._options, self._session, raw_priority_json) for raw_priority_json in r_json ] return priorities def priority(self, id: str) -> Priority: """Get a priority Resource from the server. Args: id (str): ID of the priority to get Returns: Priority """ return self._find_for_resource(Priority, id) # Projects def projects(self) -> List[Project]: """Get a list of project Resources from the server visible to the current authenticated user. Returns: List[Project] """ r_json = self._get_json("project") projects = [ Project(self._options, self._session, raw_project_json) for raw_project_json in r_json ] return projects def project(self, id: str) -> Project: """Get a project Resource from the server. Args: id (str): ID or key of the project to get Returns: Project """ return self._find_for_resource(Project, id) # non-resource @translate_resource_args def project_avatars(self, project: str): """Get a dict of all avatars for a project visible to the current authenticated user. Args: project (str): ID or key of the project to get avatars for """ return self._get_json("project/" + project + "/avatars") @translate_resource_args def create_temp_project_avatar( self, project: str, filename: str, size: int, avatar_img: bytes, contentType: str = None, auto_confirm: bool = False, ): """Register an image file as a project avatar. The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, size, and file object. By default, the client will attempt to autodetect the picture's content type: this mechanism relies on libmagic and will not work out of the box on Windows systems (see https://filemagic.readthedocs.io/en/latest/guide.html for details on how to install support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) This method returns a dict of properties that can be used to crop a subarea of a larger image for use. This dict should be saved and passed to :py:meth:`confirm_project_avatar` to finish the avatar creation process. If you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the 'auto_confirm' argument with a truthy value and :py:meth:`confirm_project_avatar` will be called for you before this method returns. Args: project (str): ID or key of the project to create the avatar in filename (str): name of the avatar file size (int): size of the avatar file avatar_img (bytes): file-like object holding the avatar contentType (str): explicit specification for the avatar image's content-type auto_confirm (bool): whether to automatically confirm the temporary avatar by calling :py:meth:`confirm_project_avatar` with the return value of this method. (Default: False) """ size_from_file = os.path.getsize(filename) if size != size_from_file: size = size_from_file params = {"filename": filename, "size": size} headers: Dict[str, Any] = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType else: # try to detect content-type, this may return None headers["content-type"] = self._get_mime_type(avatar_img) url = self._get_url("project/" + project + "/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_project_avatar(project, cropping_properties) else: return cropping_properties @translate_resource_args def confirm_project_avatar(self, project: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar for use. The final avatar can be a subarea of the uploaded image, which is customized with the ``cropping_properties``: the return value of :py:meth:`create_temp_project_avatar` should be used for this argument. Args: project (str): ID or key of the project to confirm the avatar in cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_project_avatar` """ data = cropping_properties url = self._get_url("project/" + project + "/avatar") r = self._session.post(url, data=json.dumps(data)) return json_loads(r) @translate_resource_args def set_project_avatar(self, project: str, avatar: str): """Set a project's avatar. Args: project (str): ID or key of the project to set the avatar on avatar (str): ID of the avatar to set """ self._set_avatar(None, self._get_url("project/" + project + "/avatar"), avatar) @translate_resource_args def delete_project_avatar(self, project: str, avatar: str) -> Response: """Delete a project's avatar. Args: project (str): ID or key of the project to delete the avatar from avatar (str): ID of the avatar to delete """ url = self._get_url("project/" + project + "/avatar/" + avatar) return self._session.delete(url) @translate_resource_args def project_components(self, project: str) -> List[Component]: """Get a list of component Resources present on a project. Args: project (str): ID or key of the project to get components from Returns: List[Component] """ r_json = self._get_json("project/" + project + "/components") components = [ Component(self._options, self._session, raw_comp_json) for raw_comp_json in r_json ] return components @translate_resource_args def project_versions(self, project: str) -> List[Version]: """Get a list of version Resources present on a project. Args: project (str): ID or key of the project to get versions from Returns: List[Version] """ r_json = self._get_json("project/" + project + "/versions") versions = [ Version(self._options, self._session, raw_ver_json) for raw_ver_json in r_json ] return versions @translate_resource_args def get_project_version_by_name( self, project: str, version_name: str ) -> Optional[Version]: """Get a version Resource by its name present on a project. Args: project (str): ID or key of the project to get versions from version_name (str): name of the version to search for Returns: Optional[Version] """ versions: List[Version] = self.project_versions(project) for version in versions: if version.name == version_name: return version return None @translate_resource_args def rename_version(self, project: str, old_name: str, new_name: str) -> None: """Rename a version Resource on a project. Args: project (str): ID or key of the project to get versions from old_name (str): old name of the version to rename new_name (str): new name of the version to rename Returns: None """ version = self.get_project_version_by_name(project, old_name) if version: version.update(name=new_name) # non-resource @translate_resource_args def project_roles(self, project: str) -> Dict[str, Dict[str, str]]: """Get a dict of role names to resource locations for a project. Args: project (str): ID or key of the project to get roles from """ path = "project/" + project + "/role" _rolesdict: Dict[str, str] = self._get_json(path) rolesdict: Dict[str, Dict[str, str]] = {} for k, v in _rolesdict.items(): tmp: Dict[str, str] = {} tmp["id"] = v.split("/")[-1] tmp["url"] = v rolesdict[k] = tmp return rolesdict # TODO(ssbarnea): return a list of Roles() @translate_resource_args def project_role(self, project: str, id: str) -> Role: """Get a role Resource. Args: project (str): ID or key of the project to get the role from id (str): ID of the role to get """ if isinstance(id, Number): id = f"{id}" return self._find_for_resource(Role, (project, id)) # Resolutions def resolutions(self) -> List[Resolution]: """Get a list of resolution Resources from the server. Returns: List[Resolution] """ r_json = self._get_json("resolution") resolutions = [ Resolution(self._options, self._session, raw_res_json) for raw_res_json in r_json ] return resolutions def resolution(self, id: str) -> Resolution: """Get a resolution Resource from the server. Args: id (str): ID of the resolution to get Returns: Resolution """ return self._find_for_resource(Resolution, id) # Search def search_issues( self, jql_str: str, startAt: int = 0, maxResults: int = 50, validate_query: bool = True, fields: Optional[Union[str, List[str]]] = None, expand: Optional[str] = None, json_result: bool = False, ) -> Union[List[Dict[str, Any]], ResultList[Issue]]: """Get a :class:`~jira.client.ResultList` of issue Resources matching a JQL search string. Args: jql_str (str): The JQL search string. startAt (int): Index of the first issue to return. (Default: 0) maxResults (int): Maximum number of issues to return. Total number of results is available in the ``total`` attribute of the returned :class:`~jira.client.ResultList`. If maxResults evaluates as False, it will try to get all issues in batches. (Default: 50) validate_query (bool): Whether or not the query should be validated. (Default: True) fields (Optional[Union[str, List[str]]]): comma-separated string or list of issue fields to include in the results. Default is to include all fields. expand (Optional[str]): extra information to fetch inside each resource json_result (bool): JSON response will be returned when this parameter is set to True. Otherwise, :class:`~jira.client.ResultList` will be returned. Returns: Union[Dict,ResultList]: Dict if ``json_result=True`` """ if isinstance(fields, str): fields = fields.split(",") else: fields = list(fields or []) # this will translate JQL field names to REST API Name # most people do know the JQL names so this will help them use the API easier untranslate = {} # use to add friendly aliases when we get the results back if self._fields: for i, field in enumerate(fields): if field in self._fields: untranslate[self._fields[field]] = fields[i] fields[i] = self._fields[field] search_params = { "jql": jql_str, "startAt": startAt, "validateQuery": validate_query, "fields": fields, "expand": expand, } if json_result: search_params["maxResults"] = maxResults if not maxResults: warnings.warn( "All issues cannot be fetched at once, when json_result parameter is set", Warning, ) r_json: List[Dict[str, Any]] = self._get_json( "search", params=search_params ) return r_json issues = self._fetch_pages( Issue, "issues", "search", startAt, maxResults, search_params ) if untranslate: iss: Issue for iss in issues: for k, v in untranslate.items(): if iss.raw: if k in iss.raw.get("fields", {}): iss.raw["fields"][v] = iss.raw["fields"][k] return issues # Security levels def security_level(self, id: str) -> SecurityLevel: """Get a security level Resource. Args: id (str): ID of the security level to get """ return self._find_for_resource(SecurityLevel, id) # Server info # non-resource def server_info(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance. Returns: Dict[str, Any] """ retry = 0 j = self._get_json("serverInfo") while not j and retry < 3: self.log.warning( "Bug https://jira.atlassian.com/browse/JRA-59676 trying again..." ) retry += 1 j = self._get_json("serverInfo") return j def myself(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance.""" return self._get_json("myself") # Status def statuses(self) -> List[Status]: """Get a list of status Resources from the server. Returns: List[Status] """ r_json = self._get_json("status") statuses = [ Status(self._options, self._session, raw_stat_json) for raw_stat_json in r_json ] return statuses def status(self, id: str) -> Status: """Get a status Resource from the server. Args: id (str): ID of the status resource to get Returns: Status """ return self._find_for_resource(Status, id) # Category def statuscategories(self) -> List[StatusCategory]: """Get a list of status category Resources from the server. Returns: List[StatusCategory] """ r_json = self._get_json("statuscategory") statuscategories = [ StatusCategory(self._options, self._session, raw_stat_json) for raw_stat_json in r_json ] return statuscategories def statuscategory(self, id: int) -> StatusCategory: """Get a status category Resource from the server. Args: id (int): ID of the status category resource to get Returns: StatusCategory """ return self._find_for_resource(StatusCategory, id) # Users def user(self, id: str, expand: Optional[Any] = None) -> User: """Get a user Resource from the server. Args: id (str): ID of the user to get expand (Optional[Any]): Extra information to fetch inside each resource Returns: User """ user = User(self._options, self._session) params = {} if expand is not None: params["expand"] = expand user.find(id, params=params) return user def search_assignable_users_for_projects( self, username: str, projectKeys: str, startAt: int = 0, maxResults: int = 50 ) -> ResultList: """Get a list of user Resources that match the search string and can be assigned issues for projects. Args: username (str): A string to match usernames against projectKeys (str): Comma-separated list of project keys to check for issue assignment permissions startAt (int): Index of the first user to return (Default: 0) maxResults (int): Maximum number of users to return. If maxResults evaluates as False, it will try to get all users in batches. (Default: 50) Returns: ResultList """ params = {"username": username, "projectKeys": projectKeys} return self._fetch_pages( User, None, "user/assignable/multiProjectSearch", startAt, maxResults, params, ) def search_assignable_users_for_issues( self, username: str, project: Optional[str] = None, issueKey: Optional[str] = None, expand: Optional[Any] = None, startAt: int = 0, maxResults: int = 50, ): """Get a list of user Resources that match the search string for assigning or creating issues. This method is intended to find users that are eligible to create issues in a project or be assigned to an existing issue. When searching for eligible creators, specify a project. When searching for eligible assignees, specify an issue key. Args: username (str): A string to match usernames against project (Optional[str]): Filter returned users by permission in this project (expected if a result will be used to create an issue) issueKey (Optional[str]): Filter returned users by this issue (expected if a result will be used to edit this issue) expand (Optional[Any]): Extra information to fetch inside each resource startAt (int): Index of the first user to return (Default: 0) maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) Returns: ResultList """ params = {"username": username} if project is not None: params["project"] = project if issueKey is not None: params["issueKey"] = issueKey if expand is not None: params["expand"] = expand return self._fetch_pages( User, None, "user/assignable/search", startAt, maxResults, params ) # non-resource def user_avatars(self, username: str) -> Dict[str, Any]: """Get a dict of avatars for the specified user. Args: username (str): the username to get avatars for """ return self._get_json("user/avatars", params={"username": username}) def create_temp_user_avatar( self, user: str, filename: str, size: int, avatar_img: bytes, contentType: Any = None, auto_confirm: bool = False, ): """Register an image file as a user avatar. The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, size, and file object. By default, the client will attempt to autodetect the picture's content type: this mechanism relies on ``libmagic`` and will not work out of the box on Windows systems (see http://filemagic.readthedocs.org/en/latest/guide.html for details on how to install support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) This method returns a dict of properties that can be used to crop a subarea of a larger image for use. This dict should be saved and passed to :py:meth:`confirm_user_avatar` to finish the avatar creation process. If you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the ``auto_confirm`` argument with a truthy value and :py:meth:`confirm_user_avatar` will be called for you before this method returns. Args: user (str): User to register the avatar for filename (str): name of the avatar file size (int): size of the avatar file avatar_img (bytes): file-like object containing the avatar contentType (Optional[Any]): explicit specification for the avatar image's content-type auto_confirm (bool): whether to automatically confirm the temporary avatar by calling :py:meth:`confirm_user_avatar` with the return value of this method. (Default: False) """ size_from_file = os.path.getsize(filename) if size != size_from_file: size = size_from_file # remove path from filename filename = os.path.split(filename)[1] params = {"username": user, "filename": filename, "size": size} headers: Dict[str, Any] headers = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType else: # try to detect content-type, this may return None headers["content-type"] = self._get_mime_type(avatar_img) url = self._get_url("user/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_user_avatar(user, cropping_properties) else: return cropping_properties def confirm_user_avatar(self, user: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_user_avatar`, use this method to confirm the avatar for use. The final avatar can be a subarea of the uploaded image, which is customized with the ``cropping_properties``: the return value of :py:meth:`create_temp_user_avatar` should be used for this argument. Args: user (str): the user to confirm the avatar for cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_user_avatar` """ data = cropping_properties url = self._get_url("user/avatar") r = self._session.post(url, params={"username": user}, data=json.dumps(data)) return json_loads(r) def set_user_avatar(self, username: str, avatar: str) -> Response: """Set a user's avatar. Args: username (str): the user to set the avatar for avatar (str): ID of the avatar to set """ return self._set_avatar( {"username": username}, self._get_url("user/avatar"), avatar ) def delete_user_avatar(self, username: str, avatar: str): """Delete a user's avatar. Args: username (str): the user to delete the avatar from avatar (str): ID of the avatar to remove """ params = {"username": username} url = self._get_url("user/avatar/" + avatar) return self._session.delete(url, params=params) def search_users( self, user: Optional[str] = None, startAt: int = 0, maxResults: int = 50, includeActive: bool = True, includeInactive: bool = False, query: Optional[str] = None, ) -> ResultList[User]: """Get a list of user Resources that match the specified search string. "username" query parameter is deprecated in Jira Cloud; the expected parameter now is "query", which can just be the full email again. But the "user" parameter is kept for backwards compatibility, i.e. Jira Server/Data Center. Args: user (Optional[str]): a string to match usernames, name or email against. startAt (int): index of the first user to return. maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. includeActive (bool): If true, then active users are included in the results. (Default: True) includeInactive (bool): If true, then inactive users are included in the results. (Default: False) query (Optional[str]): Search term. It can just be the email. Returns: ResultList[User] """ if not user and not query: raise ValueError("Either 'user' or 'query' arguments must be specified.") params = { "username": user, "query": query, "includeActive": includeActive, "includeInactive": includeInactive, } return self._fetch_pages(User, None, "user/search", startAt, maxResults, params) def search_allowed_users_for_issue( self, user: str, issueKey: str = None, projectKey: str = None, startAt: int = 0, maxResults: int = 50, ) -> ResultList: """Get a list of user Resources that match a username string and have browse permission for the issue or project. Args: user (str): a string to match usernames against. issueKey (Optional[str]): find users with browse permission for this issue. projectKey (Optional[str]): find users with browse permission for this project. startAt (int): index of the first user to return. (Default: 0) maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) Returns: ResultList """ params = {"username": user} if issueKey is not None: params["issueKey"] = issueKey if projectKey is not None: params["projectKey"] = projectKey return self._fetch_pages( User, None, "user/viewissue/search", startAt, maxResults, params ) # Versions @translate_resource_args def create_version( self, name: str, project: str, description: str = None, releaseDate: Any = None, startDate: Any = None, archived: bool = False, released: bool = False, ) -> Version: """Create a version in a project and return a Resource for it. Args: name (str): name of the version to create project (str): key of the project to create the version in description (str): a description of the version releaseDate (Optional[Any]): the release date assigned to the version startDate (Optional[Any]): The start date for the version archived (bool): Denotes whether a version should be archived. (Default: False) released (bool): Denotes whether a version is released. (Default: False) Returns: Version """ data = { "name": name, "project": project, "archived": archived, "released": released, } if description is not None: data["description"] = description if releaseDate is not None: data["releaseDate"] = releaseDate if startDate is not None: data["startDate"] = startDate url = self._get_url("version") r = self._session.post(url, data=json.dumps(data)) time.sleep(1) version = Version(self._options, self._session, raw=json_loads(r)) return version def move_version(self, id: str, after: str = None, position: str = None) -> Version: """Move a version within a project's ordered version list and return a new version Resource for it. One, but not both, of ``after`` and ``position`` must be specified. Args: id (str): ID of the version to move after (str): the self attribute of a version to place the specified version after (that is, higher in the list) position (Optional[str]): the absolute position to move this version to: must be one of ``First``, ``Last``, ``Earlier``, or ``Later`` Returns: Version """ data = {} if after is not None: data["after"] = after elif position is not None: data["position"] = position url = self._get_url("version/" + id + "/move") r = self._session.post(url, data=json.dumps(data)) version = Version(self._options, self._session, raw=json_loads(r)) return version def version(self, id: str, expand: Any = None) -> Version: """Get a version Resource. Args: id (str): ID of the version to get expand (Optional[Any]): extra information to fetch inside each resource Returns: Version """ version = Version(self._options, self._session) params = {} if expand is not None: params["expand"] = expand version.find(id, params=params) return version def version_count_related_issues(self, id: str): """Get a dict of the counts of issues fixed and affected by a version. Args: id (str): the version to count issues for """ r_json: Dict[str, Any] = self._get_json("version/" + id + "/relatedIssueCounts") del r_json["self"] # this isn't really an addressable resource return r_json def version_count_unresolved_issues(self, id: str): """Get the number of unresolved issues for a version. Args: id (str): ID of the version to count issues for """ r_json: Dict[str, Any] = self._get_json( "version/" + id + "/unresolvedIssueCount" ) return r_json["issuesUnresolvedCount"] # Session authentication def session(self) -> User: """Get a dict of the current authenticated user's session information. Returns: User """ url = "{server}{auth_url}".format(**self._options) r = self._session.get(url) user = User(self._options, self._session, json_loads(r)) return user def kill_session(self) -> Response: """Destroy the session of the current authenticated user.""" url = self.server_url + "/rest/auth/latest/session" return self._session.delete(url) # Websudo def kill_websudo(self) -> Optional[Response]: """Destroy the user's current WebSudo session. Works only for non-cloud deployments, for others does nothing. Returns: Optional[Response] """ if self.deploymentType != "Cloud": url = self.server_url + "/rest/auth/1/websudo" return self._session.delete(url) return None # Utilities def _create_http_basic_session( self, username: str, password: str, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, ): """Creates a basic http session. Args: username (str): Username for the session password (str): Password for the username timeout (Optional[int]): If set determines the timeout period for the Session. Returns: ResilientSession """ verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.auth = (username, password) client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy self._session.cert = client_cert def _create_oauth_session( self, oauth, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] ): verify = bool(self._options["verify"]) from oauthlib.oauth1 import SIGNATURE_RSA from requests_oauthlib import OAuth1 oauth_instance = OAuth1( oauth["consumer_key"], rsa_key=oauth["key_cert"], signature_method=SIGNATURE_RSA, resource_owner_key=oauth["access_token"], resource_owner_secret=oauth["access_token_secret"], ) self._session = ResilientSession(timeout) self._session.verify = verify self._session.auth = oauth_instance def _create_kerberos_session( self, timeout: Optional[Union[Union[float, int], Tuple[float, float]]], kerberos_options=None, ): verify = bool(self._options["verify"]) if kerberos_options is None: kerberos_options = {} from requests_kerberos import DISABLED, OPTIONAL, HTTPKerberosAuth if kerberos_options.get("mutual_authentication", "OPTIONAL") == "OPTIONAL": mutual_authentication = OPTIONAL elif kerberos_options.get("mutual_authentication") == "DISABLED": mutual_authentication = DISABLED else: raise ValueError( "Unknown value for mutual_authentication: %s" % kerberos_options["mutual_authentication"] ) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.auth = HTTPKerberosAuth( mutual_authentication=mutual_authentication ) @staticmethod def _timestamp(dt: datetime.timedelta = None): t = datetime.datetime.utcnow() if dt is not None: t += dt return calendar.timegm(t.timetuple()) def _create_jwt_session( self, jwt, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] ): try: jwt_auth = JWTAuth(jwt["secret"], alg="HS256") except NameError as e: self.log.error("JWT authentication requires requests_jwt") raise e jwt_auth.set_header_format("JWT %s") jwt_auth.add_field("iat", lambda req: JIRA._timestamp()) jwt_auth.add_field( "exp", lambda req: JIRA._timestamp(datetime.timedelta(minutes=3)) ) jwt_auth.add_field("qsh", QshGenerator(self._options["context_path"])) for f in jwt["payload"].items(): jwt_auth.add_field(f[0], f[1]) self._session = ResilientSession(timeout=timeout) self._session.verify = bool(self._options["verify"]) self._session.auth = jwt_auth def _set_avatar(self, params, url, avatar): data = {"id": avatar} return self._session.put(url, params=params, data=json.dumps(data)) def _get_url(self, path: str, base: str = JIRA_BASE_URL) -> str: """Returns the full url based on Jira base url and the path provided. Using the API version specified during the __init__. Args: path (str): The subpath desired. base (Optional[str]): The base url which should be prepended to the path Returns: str: Fully qualified URL """ options = self._options.copy() options.update({"path": path}) return base.format(**options) def _get_latest_url(self, path: str, base: str = JIRA_BASE_URL) -> str: """Returns the full url based on Jira base url and the path provided. Using the latest API endpoint. Args: path (str): The subpath desired. base (Optional[str]): The base url which should be prepended to the path Returns: str: Fully qualified URL """ options = self._options.copy() options.update({"path": path, "rest_api_version": "latest"}) return base.format(**options) def _get_json( self, path: str, params: Dict[str, Any] = None, base: str = JIRA_BASE_URL ): """Get the json for a given path and params. Args: path (str): The subpath required params (Optional[Dict[str, Any]]): Parameters to filter the json query. base (Optional[str]): The Base Jira URL, defaults to the instance base. Returns: Union[Dict[str, Any], List[Dict[str, str]]] """ url = self._get_url(path, base) r = self._session.get(url, params=params) try: r_json = json_loads(r) except ValueError as e: self.log.error(f"{e}\n{r.text if r else r}") raise e return r_json def _find_for_resource( self, resource_cls: Any, ids: Union[Tuple[str, str], int, str], expand=None ) -> Any: """Uses the find method of the provided Resource class Args: resource_cls (Any): Any instance of :py:class`Resource` ids (Union[Tuple[str, str], int, str]): The arguments to the Resource's ``find()`` expand ([type], optional): The value for the expand property in the Resource's ``find()`` params. Defaults to None. Raises: JIRAError: If the Resource cannot be found Returns: Any: A class of the same type as ``resource_cls`` """ resource = resource_cls(self._options, self._session) params = {} if expand is not None: params["expand"] = expand resource.find(id=ids, params=params) if not resource: raise JIRAError("Unable to find resource %s(%s)", resource_cls, str(ids)) return resource def _try_magic(self): try: import weakref import magic except ImportError: self._magic = None else: try: _magic = magic.Magic(flags=magic.MAGIC_MIME_TYPE) def cleanup(x): _magic.close() self._magic_weakref = weakref.ref(self, cleanup) self._magic = _magic except TypeError: self._magic = None except AttributeError: self._magic = None def _get_mime_type(self, buff: bytes) -> Optional[str]: """Get the MIME type for a given stream of bytes Args: buff (bytes): Stream of bytes Returns: Optional[str]: the MIME type """ if self._magic is not None: return self._magic.id_buffer(buff) else: try: return mimetypes.guess_type("f." + str(imghdr.what(0, buff)))[0] except (IOError, TypeError): self.log.warning( "Couldn't detect content type of avatar image" ". Specify the 'contentType' parameter explicitly." ) return None def rename_user(self, old_user: str, new_user: str): """Rename a Jira user. Args: old_user (str): Old username login new_user (str): New username login """ if self._version > (6, 0, 0): url = self._get_latest_url("user") payload = {"name": new_user} params = {"username": old_user} # raw displayName self.log.debug(f"renaming {self.user(old_user).emailAddress}") r = self._session.put(url, params=params, data=json.dumps(payload)) raise_on_error(r) else: raise NotImplementedError( "Support for renaming users in Jira " "< 6.0.0 has been removed." ) def delete_user(self, username: str) -> bool: """Deletes a Jira User. Args: username (str): Username to delete Returns: bool: Success of user deletion """ url = self._get_latest_url(f"user/?username={username}") r = self._session.delete(url) if 200 <= r.status_code <= 299: return True else: self.log.error(r.status_code) return False def deactivate_user(self, username: str) -> Union[str, int]: """Disable/deactivate the user. Args: username (str): User to be deactivated. Returns: Union[str, int] """ if self.deploymentType == "Cloud": # Disabling users now needs cookie auth in the Cloud - see https://jira.atlassian.com/browse/ID-6230 if "authCookie" not in vars(self): user = self.session() if user.raw is None: raise JIRAError("Can not log in!") self.authCookie = "%s=%s" % ( user.raw["session"]["name"], user.raw["session"]["value"], ) url = ( self._options["server"] + f"/admin/rest/um/1/user/deactivate?username={username}" ) # We can't use our existing session here - this endpoint is fragile and objects to extra headers try: r = requests.post( url, headers={ "Cookie": self.authCookie, "Content-Type": "application/json", }, proxies=self._session.proxies, data={}, ) if r.status_code == 200: return True else: self.log.warning( f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: self.log.error(f"Error Deactivating {username}: {e}") raise JIRAError(f"Error Deactivating {username}: {e}") else: url = self.server_url + "/secure/admin/user/EditUser.jspa" self._options["headers"][ "Content-Type" ] = "application/x-www-form-urlencoded; charset=UTF-8" user = self.user(username) userInfo = { "inline": "true", "decorator": "dialog", "username": user.name, "fullName": user.displayName, "email": user.emailAddress, "editName": user.name, } try: r = self._session.post( url, headers=self._options["headers"], data=userInfo ) if r.status_code == 200: return True else: self.log.warning( f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: self.log.error(f"Error Deactivating {username}: {e}") raise JIRAError(f"Error Deactivating {username}: {e}") def reindex(self, force: bool = False, background: bool = True) -> bool: """Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if Jira thinks it should do it. Args: force (bool): reindex even if Jira doesn't say this is needed, False by default. background (bool): reindex in background, slower but does not impact the users, defaults to True. Returns: bool: Returns True if reindexing is in progress or not needed, or False. """ # /secure/admin/IndexAdmin.jspa # /secure/admin/jira/IndexProgress.jspa?taskId=1 if background: indexingStrategy = "background" else: indexingStrategy = "stoptheworld" url = self.server_url + "/secure/admin/jira/IndexReIndex.jspa" r = self._session.get(url, headers=self._options["headers"]) if r.status_code == 503: # self.log.warning("Jira returned 503, this could mean that a full reindex is in progress.") return 503 # type: ignore # FIXME: is this a bug? if ( not r.text.find("To perform the re-index now, please go to the") and force is False ): return True if r.text.find("All issues are being re-indexed"): self.log.warning("Jira re-indexing is already running.") return True # still reindexing is considered still a success if r.text.find("To perform the re-index now, please go to the") or force: r = self._session.post( url, headers=self._options["headers"], params={"indexingStrategy": indexingStrategy, "reindex": "Re-Index"}, ) if r.text.find("All issues are being re-indexed") != -1: return True self.log.error("Failed to reindex jira, probably a bug.") return False def backup(self, filename: str = "backup.zip", attachments: bool = False): """Will call jira export to backup as zipped xml. Returning with success does not mean that the backup process finished.""" payload: Any # _session.post is pretty open if self.deploymentType == "Cloud": url = self.server_url + "/rest/backup/1/export/runbackup" payload = json.dumps({"cbAttachments": attachments}) self._options["headers"]["X-Requested-With"] = "XMLHttpRequest" else: url = self.server_url + "/secure/admin/XmlBackup.jspa" payload = {"filename": filename} try: r = self._session.post(url, headers=self._options["headers"], data=payload) if r.status_code == 200: return True else: self.log.warning(f"Got {r.status_code} response from calling backup.") return r.status_code except Exception as e: self.log.error("I see %s", e) def backup_progress(self): """Return status of cloud backup as a dict. Is there a way to get progress for Server version? """ epoch_time = int(time.time() * 1000) if self.deploymentType == "Cloud": url = self.server_url + "/rest/obm/1.0/getprogress?_=%i" % epoch_time else: self.log.warning("This functionality is not available in Server version") return None r = self._session.get(url, headers=self._options["headers"]) # This is weird. I used to get xml, but now I'm getting json try: return json.loads(r.text) except Exception: import defusedxml.ElementTree as etree progress = {} try: root = etree.fromstring(r.text) except etree.ParseError as pe: self.log.warning( "Unable to find backup info. You probably need to initiate a new backup. %s" % pe ) return None for k in root.keys(): progress[k] = root.get(k) return progress def backup_complete(self) -> Optional[bool]: """Return boolean based on 'alternativePercentage' and 'size' returned from backup_progress (cloud only).""" if self.deploymentType != "Cloud": self.log.warning("This functionality is not available in Server version") return None status = self.backup_progress() perc_search = re.search(r"\s([0-9]*)\s", status["alternativePercentage"]) perc_complete = int( perc_search.group(1) # type: ignore # ignore that re.search can return None ) file_size = int(status["size"]) return perc_complete >= 100 and file_size > 0 def backup_download(self, filename: str = None): """Download backup file from WebDAV (cloud only).""" if self.deploymentType != "Cloud": self.log.warning("This functionality is not available in Server version") return None remote_file = self.backup_progress()["fileName"] local_file = filename or remote_file url = self.server_url + "/webdav/backupmanager/" + remote_file try: self.log.debug(f"Writing file to {local_file}") with open(local_file, "wb") as file: try: resp = self._session.get( url, headers=self._options["headers"], stream=True ) except Exception: raise JIRAError() if not resp.ok: self.log.error(f"Something went wrong with download: {resp.text}") raise JIRAError(resp.text) for block in resp.iter_content(1024): file.write(block) except JIRAError as je: self.log.error(f"Unable to access remote backup file: {je}") except IOError as ioe: self.log.error(ioe) return None def current_user(self, field: str = "key") -> str: """Returns the username or emailAddress of the current user. For anonymous users it will return a value that evaluates as False. Returns: str """ if not hasattr(self, "_myself"): url = self._get_url("myself") r = self._session.get(url, headers=self._options["headers"]) r_json: Dict[str, str] = json_loads(r) self._myself = r_json return self._myself[field] def delete_project(self, pid: Union[str, Project]) -> Optional[bool]: """Delete project from Jira. Args: pid (Union[str, Project]): Jira projectID or Project or slug Raises: JIRAError: If project not found or not enough permissions ValueError: If pid parameter is not Project, slug or ProjectID Returns: bool: True if project was deleted """ # allows us to call it with Project objects if isinstance(pid, Project) and hasattr(pid, "id"): pid = str(pid.id) url = self._get_url(f"project/{pid}") r = self._session.delete(url) if r.status_code == 403: raise JIRAError("Not enough permissions to delete project") if r.status_code == 404: raise JIRAError("Project not found in Jira") return r.ok def _gain_sudo_session(self, options, destination): url = self.server_url + "/secure/admin/WebSudoAuthenticate.jspa" if not self._session.auth: self._session.auth = get_netrc_auth(url) payload = { "webSudoPassword": self._session.auth[1], "webSudoDestination": destination, "webSudoIsPost": "true", } payload.update(options) return self._session.post( url, headers=CaseInsensitiveDict( {"content-type": "application/x-www-form-urlencoded"} ), data=payload, ) @lru_cache(maxsize=None) def templates(self) -> Dict: url = self.server_url + "/rest/project-templates/latest/templates" r = self._session.get(url) data: Dict[str, Any] = json_loads(r) templates = {} if "projectTemplatesGroupedByType" in data: for group in data["projectTemplatesGroupedByType"]: for t in group["projectTemplates"]: templates[t["name"]] = t # pprint(templates.keys()) return templates @lru_cache(maxsize=None) def permissionschemes(self): url = self._get_url("permissionscheme") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["permissionSchemes"] @lru_cache(maxsize=None) def issuesecurityschemes(self): url = self._get_url("issuesecurityschemes") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["issueSecuritySchemes"] @lru_cache(maxsize=None) def projectcategories(self): url = self._get_url("projectCategory") r = self._session.get(url) data = json_loads(r) return data @lru_cache(maxsize=None) def avatars(self, entity="project"): url = self._get_url(f"avatar/{entity}/system") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["system"] @lru_cache(maxsize=None) def notificationschemes(self): # TODO(ssbarnea): implement pagination support url = self._get_url("notificationscheme") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def screens(self): # TODO(ssbarnea): implement pagination support url = self._get_url("screens") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def workflowscheme(self): # TODO(ssbarnea): implement pagination support url = self._get_url("workflowschemes") r = self._session.get(url) data = json_loads(r) return data # ['values'] @lru_cache(maxsize=None) def workflows(self): # TODO(ssbarnea): implement pagination support url = self._get_url("workflow") r = self._session.get(url) data = json_loads(r) return data # ['values'] def delete_screen(self, id: str): url = self._get_url(f"screens/{id}") r = self._session.delete(url) data = json_loads(r) self.screens.cache_clear() return data def delete_permissionscheme(self, id: str): url = self._get_url(f"permissionscheme/{id}") r = self._session.delete(url) data = json_loads(r) self.permissionschemes.cache_clear() return data def create_project( self, key: str, name: str = None, assignee: str = None, ptype: str = "software", template_name: str = None, avatarId=None, issueSecurityScheme=None, permissionScheme=None, projectCategory=None, notificationScheme=10000, categoryId=None, url: str = "", ): """Create a project with the specified parameters. Args: key (str): Mandatory. Must match Jira project key requirements, usually only 2-10 uppercase characters. name (Optional[str]): If not specified it will use the key value. assignee (Optional[str]): key of the lead, if not specified it will use current user. ptype (Optional[str]): Determines the type of project should be created. template_name (Optional[str]): is used to create a project based on one of the existing project templates. If `template_name` is not specified, then it should use one of the default values. Returns: Union[bool,int]: Should evaluate to False if it fails otherwise it will be the new project id. """ template_key = None if assignee is None: assignee = self.current_user() if name is None: name = key ps_list: List[Dict[str, Any]] if not permissionScheme: ps_list = self.permissionschemes() for sec in ps_list: if sec["name"] == "Default Permission Scheme": permissionScheme = sec["id"] break if not permissionScheme: permissionScheme = ps_list[0]["id"] if not issueSecurityScheme: ps_list = self.issuesecurityschemes() for sec in ps_list: if sec["name"] == "Default": # no idea which one is default issueSecurityScheme = sec["id"] break if not issueSecurityScheme and ps_list: issueSecurityScheme = ps_list[0]["id"] if not projectCategory: ps_list = self.projectcategories() for sec in ps_list: if sec["name"] == "Default": # no idea which one is default projectCategory = sec["id"] break if not projectCategory and ps_list: projectCategory = ps_list[0]["id"] # <beep> Atlassian for failing to provide an API to get projectTemplateKey values # Possible values are just hardcoded and obviously depending on Jira version. # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?_ga=2.88310429.766596084.1562439833-992274574.1559129176#api-rest-api-3-project-post # https://jira.atlassian.com/browse/JRASERVER-59658 # preference list for picking a default template if not template_name: # https://confluence.atlassian.com/jirakb/creating-projects-via-rest-api-in-jira-963651978.html template_key = ( "com.pyxis.greenhopper.jira:basic-software-development-template" ) # https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-projects/#api-rest-api-2-project-get # template_keys = [ # "com.pyxis.greenhopper.jira:gh-simplified-agility-kanban", # "com.pyxis.greenhopper.jira:gh-simplified-agility-scrum", # "com.pyxis.greenhopper.jira:gh-simplified-basic", # "com.pyxis.greenhopper.jira:gh-simplified-kanban-classic", # "com.pyxis.greenhopper.jira:gh-simplified-scrum-classic", # "com.atlassian.servicedesk:simplified-it-service-desk", # "com.atlassian.servicedesk:simplified-internal-service-desk", # "com.atlassian.servicedesk:simplified-external-service-desk", # "com.atlassian.jira-core-project-templates:jira-core-simplified-content-management", # "com.atlassian.jira-core-project-templates:jira-core-simplified-document-approval", # "com.atlassian.jira-core-project-templates:jira-core-simplified-lead-tracking", # "com.atlassian.jira-core-project-templates:jira-core-simplified-process-control", # "com.atlassian.jira-core-project-templates:jira-core-simplified-procurement", # "com.atlassian.jira-core-project-templates:jira-core-simplified-project-management", # "com.atlassian.jira-core-project-templates:jira-core-simplified-recruitment", # "com.atlassian.jira-core-project-templates:jira-core-simplified-task-", # "com.atlassian.jira.jira-incident-management-plugin:im-incident-management", # ] # possible_templates = [ # "Scrum software development", # have Bug # "Agility", # cannot set summary # "Bug tracking", # "JIRA Classic", # "JIRA Default Schemes", # "Basic software development", # "Project management", # "Kanban software development", # "Task management", # "Basic", # does not have Bug # "Content Management", # "Customer service", # "Document Approval", # "IT Service Desk", # "Lead Tracking", # "Process management", # "Procurement", # "Recruitment", # ] # templates = self.templates() # if not template_name: # for k, v in templates.items(): # if v['projectTypeKey'] == type: # template_name = k # template_name = next((t for t in templates if t['projectTypeKey'] == 'x')) # template_key = templates[template_name]["projectTemplateModuleCompleteKey"] # project_type_key = templates[template_name]["projectTypeKey"] # https://confluence.atlassian.com/jirakb/creating-a-project-via-rest-based-on-jira-default-schemes-744325852.html # see https://confluence.atlassian.com/jirakb/creating-projects-via-rest-api-in-jira-963651978.html payload = { "name": name, "key": key, "projectTypeKey": ptype, "projectTemplateKey": template_key, "lead": assignee, # "leadAccountId": assignee, "assigneeType": "PROJECT_LEAD", "description": "", # "avatarId": 13946, "permissionScheme": int(permissionScheme), "notificationScheme": notificationScheme, "url": url, } if issueSecurityScheme: payload["issueSecurityScheme"] = int(issueSecurityScheme) if projectCategory: payload["categoryId"] = int(projectCategory) url = self._get_url("project") r = self._session.post(url, data=json.dumps(payload)) r.raise_for_status() r_json = json_loads(r) return r_json def add_user( self, username: str, email: str, directoryId: int = 1, password: str = None, fullname: str = None, notify: bool = False, active: bool = True, ignore_existing: bool = False, application_keys: Optional[List] = None, ): """Create a new Jira user. Args: username (str): the username of the new user email (str): email address of the new user directoryId (int): The directory ID the new user should be a part of (Default: 1) password (Optional[str]): Optional, the password for the new user fullname (Optional[str]): Optional, the full name of the new user notify (bool): Whether or not to send a notification to the new user. (Default: False) active (bool): Whether or not to make the new user active upon creation. (Default: True) ignore_existing (bool): Whether or not to ignore and existing user. (Default: False) applicationKeys (Optional[list]): Keys of products user should have access to Raises: JIRAError: If username already exists and `ignore_existing` has not been set to `True`. Returns: bool: Whether or not the user creation was successful. """ if not fullname: fullname = username # TODO(ssbarnea): default the directoryID to the first directory in jira instead # of 1 which is the internal one. url = self._get_latest_url("user") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 x: Dict[str, Any] = OrderedDict() x["displayName"] = fullname x["emailAddress"] = email x["name"] = username if password: x["password"] = password if notify: x["notification"] = "True" if application_keys is not None: x["applicationKeys"] = application_keys payload = json.dumps(x) try: self._session.post(url, data=payload) except JIRAError as e: if e.response: err = e.response.json()["errors"] if ( "username" in err and err["username"] == "A user with that username already exists." and ignore_existing ): return True raise e return True def add_user_to_group( self, username: str, group: str ) -> Union[bool, Dict[str, Any]]: """Add a user to an existing group. Args: username (str): Username that will be added to specified group. group (str): Group that the user will be added to. Returns: Union[bool,Dict[str,Any]]: json response from Jira server for success or a value that evaluates as False in case of failure. """ url = self._get_latest_url("group/user") x = {"groupname": group} y = {"name": username} payload = json.dumps(y) r: Dict[str, Any] = json_loads(self._session.post(url, params=x, data=payload)) if "name" not in r or r["name"] != group: return False else: return r def remove_user_from_group(self, username: str, groupname: str): """Remove a user from a group. Args: username (str): The user to remove from the group. groupname (str): The group that the user will be removed from. """ url = self._get_latest_url("group/user") x = {"groupname": groupname, "username": username} self._session.delete(url, params=x) return True def role(self) -> List[Dict[str, Any]]: """Return Jira role information. Returns: List[Dict[str,Any]]: List of current user roles """ # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-rest-api-3-role-get url = self._get_latest_url("role") r = self._session.get(url) data: List[Dict[str, Any]] = json_loads(r) return data # Experimental # Experimental support for iDalko Grid, expect API to change as it's using private APIs currently # https://support.idalko.com/browse/IGRID-1017 def get_igrid(self, issueid: str, customfield: str, schemeid: str): url = self.server_url + "/rest/idalko-igrid/1.0/datagrid/data" if str(customfield).isdigit(): customfield = f"customfield_{customfield}" params = { "_issueId": issueid, "_fieldId": customfield, "_confSchemeId": schemeid, } r = self._session.get(url, headers=self._options["headers"], params=params) return json_loads(r) # Jira Agile specific methods (GreenHopper) """ Define the functions that interact with GreenHopper. """ @translate_resource_args def boards( self, startAt: int = 0, maxResults: int = 50, type: str = None, name: str = None, projectKeyOrID=None, ) -> ResultList[Board]: """Get a list of board resources. Args: startAt: The starting index of the returned boards. Base index: 0. maxResults: The maximum number of boards to return per page. Default: 50 type: Filters results to boards of the specified type. Valid values: scrum, kanban. name: Filters results to boards that match or partially match the specified name. projectKeyOrID: Filters results to boards that match the specified project key or ID. Returns: ResultList[Board] When old GreenHopper private API is used, paging is not enabled and all parameters are ignored. """ params = {} if type: params["type"] = type if name: params["name"] = name if projectKeyOrID: params["projectKeyOrId"] = projectKeyOrID if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # Old, private API did not support pagination, all records were present in response, # and no parameters were supported. if startAt or maxResults or params: warnings.warn( "Old private GreenHopper API is used, all parameters will be ignored.", Warning, ) r_json: Dict[str, Any] = self._get_json( "rapidviews/list", base=self.AGILE_BASE_URL ) boards = [ Board(self._options, self._session, raw_boards_json) for raw_boards_json in r_json["views"] ] return ResultList(boards, 0, len(boards), len(boards), True) else: return self._fetch_pages( Board, "values", "board", startAt, maxResults, params, base=self.AGILE_BASE_URL, ) @translate_resource_args def sprints( self, board_id: int, extended: bool = False, startAt: int = 0, maxResults: int = 50, state: str = None, ) -> ResultList[Sprint]: """Get a list of sprint GreenHopperResources. Args: board_id (int): the board to get sprints from extended (bool): Used only by old GreenHopper API to fetch additional information like startDate, endDate, completeDate, much slower because it requires an additional requests for each sprint. New Jira Agile API always returns this information without a need for additional requests. startAt (int): the index of the first sprint to return (0 based) maxResults (int): the maximum number of sprints to return state (str): Filters results to sprints in specified states. Valid values: `future`, `active`, `closed`. You can define multiple states separated by commas Returns: ResultList[Sprint]: (content depends on API version, but always contains id, name, state, startDate and endDate) When old GreenHopper private API is used, paging is not enabled, and `startAt`, `maxResults` and `state` parameters are ignored. """ params = {} if state: params["state"] = state if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): r_json: Dict[str, Any] = self._get_json( "sprintquery/%s?includeHistoricSprints=true&includeFutureSprints=true" % board_id, base=self.AGILE_BASE_URL, ) if params: warnings.warn( "Old private GreenHopper API is used, parameters %s will be ignored." % params, Warning, ) if extended: sprints = [ Sprint( self._options, self._session, self.sprint_info("", raw_sprints_json["id"]), ) for raw_sprints_json in r_json["sprints"] ] else: sprints = [ Sprint(self._options, self._session, raw_sprints_json) for raw_sprints_json in r_json["sprints"] ] return ResultList(sprints, 0, len(sprints), len(sprints), True) else: return self._fetch_pages( Sprint, "values", f"board/{board_id}/sprint", startAt, maxResults, params, self.AGILE_BASE_URL, ) def sprints_by_name(self, id, extended=False): sprints = {} for s in self.sprints(id, extended=extended): if s.name not in sprints: sprints[s.name] = s.raw else: raise Exception return sprints def update_sprint(self, id, name=None, startDate=None, endDate=None, state=None): payload = {} if name: payload["name"] = name if startDate: payload["startDate"] = startDate if endDate: payload["endDate"] = endDate if state: if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): raise NotImplementedError( "Public Jira API does not support state update" ) payload["state"] = state url = self._get_url(f"sprint/{id}", base=self.AGILE_BASE_URL) r = self._session.put(url, data=json.dumps(payload)) return json_loads(r) def incompletedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" data: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) return data["contents"]["incompletedIssuesEstimateSum"]["value"] def removed_issues(self, board_id: str, sprint_id: str): """Return the completed issues for the sprint.""" r_json: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) issues = [ Issue(self._options, self._session, raw_issues_json) for raw_issues_json in r_json["contents"]["puntedIssues"] ] return issues def removedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" data: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) return data["contents"]["puntedIssuesEstimateSum"]["value"] # TODO(ssbarnea): remove sprint_info() method, sprint() method suit the convention more def sprint_info(self, board_id: str, sprint_id: str) -> Optional[Dict[str, Any]]: """Return the information about a sprint. Args: board_id (str): the board retrieving issues from. Deprecated and ignored. sprint_id (str): the sprint retrieving issues from """ sprint = Sprint(self._options, self._session) sprint.find(sprint_id) return sprint.raw def sprint(self, id: int) -> Sprint: """Return the information about a sprint. Args: sprint_id (int): the sprint retrieving issues from Returns: Sprint """ sprint = Sprint(self._options, self._session) sprint.find(id) return sprint # TODO(ssbarnea): remove this as we do have Board.delete() def delete_board(self, id): """Delete an agile board.""" board = Board(self._options, self._session, raw={"id": id}) board.delete() def create_board( self, name: str, project_ids: Union[str, List[str]], preset: str = "scrum", location_type: str = "user", location_id: Optional[str] = None, ) -> Board: """Create a new board for the ``project_ids``. Args: name (str): name of the board project_ids (str): the projects to create the board in preset (str): What preset to use for this board, options: kanban, scrum, diy. (Default: scrum) location_type (str): the location type. Available in cloud. (Default: user) location_id (Optional[str]): the id of project that the board should be located under. Omit this for a 'user' location_type. Available in cloud. Returns: Board: The newly created board """ if ( self._options["agile_rest_path"] != GreenHopperResource.GREENHOPPER_REST_PATH ): raise NotImplementedError( "Jira Agile Public API does not support this request" ) payload: Dict[str, Any] = {} if isinstance(project_ids, str): ids = [] for p in project_ids.split(","): ids.append(self.project(p).id) project_ids = ",".join(ids) if location_id is not None: location_id = self.project(location_id).id payload["name"] = name if isinstance(project_ids, str): project_ids = project_ids.split(",") # type: ignore # re-use of variable payload["projectIds"] = project_ids payload["preset"] = preset if self.deploymentType == "Cloud": payload["locationType"] = location_type payload["locationId"] = location_id url = self._get_url("rapidview/create/presets", base=self.AGILE_BASE_URL) r = self._session.post(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) return Board(self._options, self._session, raw=raw_issue_json) def create_sprint( self, name: str, board_id: int, startDate: Optional[Any] = None, endDate: Optional[Any] = None, ) -> Sprint: """Create a new sprint for the ``board_id``. Args: name (str): Name of the sprint board_id (int): Which board the sprint should be assigned. startDate (Optional[Any]): Start date for the sprint. endDate (Optional[Any]): End date for the sprint. Returns: Sprint: The newly created Sprint """ payload: Dict[str, Any] = {"name": name} if startDate: payload["startDate"] = startDate if endDate: payload["endDate"] = endDate raw_issue_json: Dict[str, Any] if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): url = self._get_url(f"sprint/{board_id}", base=self.AGILE_BASE_URL) r = self._session.post(url) raw_issue_json = json_loads(r) """ now r contains something like: { "id": 742, "name": "Sprint 89", "state": "FUTURE", "linkedPagesCount": 0, "startDate": "None", "endDate": "None", "completeDate": "None", "remoteLinks": [] }""" url = self._get_url( f"sprint/{raw_issue_json["id"]}", base=self.AGILE_BASE_URL ) r = self._session.put(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) else: url = self._get_url("sprint", base=self.AGILE_BASE_URL) payload["originBoardId"] = board_id r = self._session.post(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) return Sprint(self._options, self._session, raw=raw_issue_json) def add_issues_to_sprint(self, sprint_id: int, issue_keys: List[str]) -> Response: """Add the issues in ``issue_keys`` to the ``sprint_id``. The sprint must be started but not completed. If a sprint was completed, then have to also edit the history of the issue so that it was added to the sprint before it was completed, preferably before it started. A completed sprint's issues also all have a resolution set before the completion date. If a sprint was not started, then have to edit the marker and copy the rank of each issue too. Args: sprint_id (int): the sprint to add issues to issue_keys (List[str]): the issues to add to the sprint Returns: Response """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url(f"sprint/{sprint_id}/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # In old, private API the function does not exist anymore and we need to use # issue.update() to perform this operation # Workaround based on https://answers.atlassian.com/questions/277651/jira-agile-rest-api-example sprint_field_id = self._get_sprint_field_id() data = { "idOrKeys": issue_keys, "customFieldId": sprint_field_id, "sprintId": sprint_id, "addToBacklog": False, } url = self._get_url("sprint/rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for adding issues to sprint for agile_rest_path="%s"' % self._options["agile_rest_path"] ) def add_issues_to_epic( self, epic_id: str, issue_keys: str, ignore_epics: bool = True ) -> Response: """Add the issues in ``issue_keys`` to the ``epic_id``. Args: epic_id (str): The ID for the epic where issues should be added. issue_keys (str): The issues to add to the epic ignore_epics (bool): ignore any issues listed in ``issue_keys`` that are epics. (Default: True) """ if ( self._options["agile_rest_path"] != GreenHopperResource.GREENHOPPER_REST_PATH ): # TODO(ssbarnea): simulate functionality using issue.update()? raise NotImplementedError( "Jira Agile Public API does not support this request" ) data: Dict[str, Any] = {} data["issueKeys"] = issue_keys data["ignoreEpics"] = ignore_epics url = self._get_url(f"epics/{epic_id}/add", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) # TODO(ssbarnea): Both GreenHopper and new Jira Agile API support moving more than one issue. def rank(self, issue: str, next_issue: str) -> Response: """Rank an issue before another using the default Ranking field, the one named 'Rank'. Args: issue (str): issue key of the issue to be ranked before the second one. next_issue (str): issue key of the second issue. """ if not self._rank: for field in self.fields(): if field["name"] == "Rank": if ( field["schema"]["custom"] == "com.pyxis.greenhopper.jira:gh-lexo-rank" ): self._rank = field["schema"]["customId"] break elif ( field["schema"]["custom"] == "com.pyxis.greenhopper.jira:gh-global-rank" ): # Obsolete since Jira v6.3.13.1 self._rank = field["schema"]["customId"] if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url("issue/rank", base=self.AGILE_BASE_URL) payload = { "issues": [issue], "rankBeforeIssue": next_issue, "rankCustomFieldId": self._rank, } try: return self._session.put(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): data = { "issueKeys": [issue], "rankBeforeKey": next_issue, "customFieldId": self._rank, } url = self._get_url("rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for ranking issues for agile_rest_path="%s"' % self._options["agile_rest_path"] ) def move_to_backlog(self, issue_keys: str) -> Response: """Move issues in ``issue_keys`` to the backlog, removing them from all sprints that have not been completed. Args: issue_keys (str): the issues to move to the backlog Raises: JIRAError: If moving issues to backlog fails """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url("backlog/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # In old, private API the function does not exist anymore and we need to use # issue.update() to perform this operation # Workaround based on https://answers.atlassian.com/questions/277651/jira-agile-rest-api-example sprint_field_id = self._get_sprint_field_id() data = { "idOrKeys": issue_keys, "customFieldId": sprint_field_id, "addToBacklog": True, } url = self._get_url("sprint/rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for moving issues to backlog for agile_rest_path="%s"' % self._options["agile_rest_path"] ) class GreenHopper(JIRA): def __init__(self, options=None, basic_auth=None, oauth=None, async_=None): warnings.warn( "GreenHopper() class is deprecated, just use JIRA() instead.", DeprecationWarning, ) JIRA.__init__( self, options=options, basic_auth=basic_auth, oauth=oauth, async_=async_ )
#!/usr/bin/python # -*- coding: utf-8 -*- """ This module implements a friendly (well, friendlier) interface between the raw JSON responses from Jira and the Resource/dict abstractions provided by this library. Users will construct a JIRA object as described below. Full API documentation can be found at: https://jira.readthedocs.io/en/latest/ """ import calendar import copy import datetime import hashlib import imghdr import json import logging as _logging import mimetypes import os import re import sys import time import warnings from collections import OrderedDict from collections.abc import Iterable from functools import lru_cache, wraps from io import BufferedReader from numbers import Number from typing import ( Any, Callable, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, cast, no_type_check, ) from urllib.parse import urlparse import requests from pkg_resources import parse_version from requests import Response from requests.auth import AuthBase from requests.utils import get_netrc_auth from jira import __version__ # GreenHopper specific resources from jira.exceptions import JIRAError from jira.resilientsession import ResilientSession, raise_on_error # Jira-specific resources from jira.resources import ( Attachment, Board, Comment, Component, Customer, CustomFieldOption, Dashboard, Filter, GreenHopperResource, Group, Issue, IssueLink, IssueLinkType, IssueType, Priority, Project, RemoteLink, RequestType, Resolution, Resource, Role, SecurityLevel, ServiceDesk, Sprint, Status, StatusCategory, User, Version, Votes, Watchers, Worklog, ) from jira.utils import CaseInsensitiveDict, json_loads, threaded_requests try: # noinspection PyUnresolvedReferences from requests_toolbelt import MultipartEncoder except ImportError: pass try: from requests_jwt import JWTAuth except ImportError: pass LOG = _logging.getLogger("jira") LOG.addHandler(_logging.NullHandler()) def translate_resource_args(func: Callable): """Decorator that converts Issue and Project resources to their keys when used as arguments.""" @wraps(func) def wrapper(*args: Any, **kwargs: Any) -> Any: arg_list = [] for arg in args: if isinstance(arg, (Issue, Project)): arg_list.append(arg.key) else: arg_list.append(arg) result = func(*arg_list, **kwargs) return result return wrapper def _field_worker( fields: Dict[str, Any] = None, **fieldargs: Any ) -> Union[Dict[str, Dict[str, Any]], Dict[str, Dict[str, str]]]: if fields is not None: return {"fields": fields} return {"fields": fieldargs} ResourceType = TypeVar("ResourceType", contravariant=True, bound=Resource) class ResultList(list, Generic[ResourceType]): def __init__( self, iterable: Iterable = None, _startAt: int = 0, _maxResults: int = 0, _total: Optional[int] = None, _isLast: Optional[bool] = None, ) -> None: """ Args: iterable (Iterable): [description]. Defaults to None. _startAt (int): Start page. Defaults to 0. _maxResults (int): Max results per page. Defaults to 0. _total (Optional[int]): Total results from query. Defaults to 0. _isLast (Optional[bool]): Last Page? Defaults to None. """ if iterable is not None: list.__init__(self, iterable) else: list.__init__(self) self.startAt = _startAt self.maxResults = _maxResults # Optional parameters: self.isLast = _isLast self.total = _total if _total is not None else len(self) self.iterable: List = list(iterable) if iterable else [] self.current = self.startAt def __next__(self) -> Type[ResourceType]: self.current += 1 if self.current > self.total: raise StopIteration else: return self.iterable[self.current - 1] class QshGenerator(object): def __init__(self, context_path): self.context_path = context_path def __call__(self, req): parse_result = urlparse(req.url) path = ( parse_result.path[len(self.context_path) :] if len(self.context_path) > 1 else parse_result.path ) # Per Atlassian docs, use %20 for whitespace when generating qsh for URL # https://developer.atlassian.com/cloud/jira/platform/understanding-jwt/#qsh query = "&".join(sorted(parse_result.query.split("&"))).replace("+", "%20") qsh = f"{req.method.upper()}&{path}&{query}" return hashlib.sha256(qsh.encode("utf-8")).hexdigest() class JiraCookieAuth(AuthBase): """Jira Cookie Authentication Allows using cookie authentication as described by https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-cookie-based-authentication """ def __init__( self, session: ResilientSession, _get_session: Callable, auth: Tuple[str, str] ): """Cookie Based Authentication Args: session (ResilientSession): The Session object to communicate with the API. _get_session (Callable): The function that returns a :py_class:``User`` auth (Tuple[str, str]): The username, password tuple """ self._session = session self._get_session = _get_session self.__auth = auth def handle_401(self, response, **kwargs): if response.status_code != 401: return response self.init_session() response = self.process_original_request(response.request.copy()) return response def process_original_request(self, original_request): self.update_cookies(original_request) return self.send_request(original_request) def update_cookies(self, original_request): # Cookie header needs first to be deleted for the header to be updated using # the prepare_cookies method. See request.PrepareRequest.prepare_cookies if "Cookie" in original_request.headers: del original_request.headers["Cookie"] original_request.prepare_cookies(self.cookies) def init_session(self): self.start_session() def __call__(self, request): request.register_hook("response", self.handle_401) return request def send_request(self, request): return self._session.send(request) @property def cookies(self): return self._session.cookies def start_session(self): self._get_session(self.__auth) class JIRA(object): """User interface to Jira. Clients interact with Jira by constructing an instance of this object and calling its methods. For addressable resources in Jira -- those with "self" links -- an appropriate subclass of :py:class:`jira.resources.Resource` will be returned with customized ``update()`` and ``delete()`` methods, along with attribute access to fields. This means that calls of the form ``issue.fields.summary`` will be resolved into the proper lookups to return the JSON value at that mapping. Methods that do not return resources will return a dict constructed from the JSON response or a scalar value; see each method's documentation for details on what that method returns. Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``, or ``atlas-run-standalone`` commands. By default, this instance runs at ``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use. Authentication is handled with the ``basic_auth`` argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests. For quick command line access to a server, see the ``jirashell`` script included with this distribution. The easiest way to instantiate is using ``j = JIRA("https://jira.atlassian.com")`` """ DEFAULT_OPTIONS = { "server": "http://localhost:2990/jira", "auth_url": "/rest/auth/1/session", "context_path": "/", "rest_path": "api", "rest_api_version": "2", "agile_rest_path": GreenHopperResource.GREENHOPPER_REST_PATH, "agile_rest_api_version": "1.0", "verify": True, "resilient": True, "async": False, "async_workers": 5, "client_cert": None, "check_update": False, # amount of seconds to wait for loading a resource after updating it # used to avoid server side caching issues, used to be 4 seconds. "delay_reload": 0, "headers": { "Cache-Control": "no-cache", # 'Accept': 'application/json;charset=UTF-8', # default for REST "Content-Type": "application/json", # ;charset=UTF-8', # 'Accept': 'application/json', # default for REST # 'Pragma': 'no-cache', # 'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT' "X-Atlassian-Token": "no-check", }, } checked_version = False # TODO(ssbarnea): remove these two variables and use the ones defined in resources JIRA_BASE_URL = Resource.JIRA_BASE_URL AGILE_BASE_URL = GreenHopperResource.AGILE_BASE_URL def __init__( self, server: str = None, options: Dict[str, Union[str, bool, Any]] = None, basic_auth: Union[None, Tuple[str, str]] = None, oauth: Dict[str, Any] = None, jwt: Dict[str, Any] = None, kerberos=False, kerberos_options: Dict[str, Any] = None, validate=False, get_server_info: bool = True, async_: bool = False, async_workers: int = 5, logging: bool = True, max_retries: int = 3, proxies: Any = None, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, auth: Tuple[str, str] = None, ): """Construct a Jira client instance. Without any arguments, this client will connect anonymously to the Jira instance started by the Atlassian Plugin SDK from one of the 'atlas-run', ``atlas-debug``, or ``atlas-run-standalone`` commands. By default, this instance runs at ``http://localhost:2990/jira``. The ``options`` argument can be used to set the Jira instance to use. Authentication is handled with the ``basic_auth`` argument. If authentication is supplied (and is accepted by Jira), the client will remember it for subsequent requests. For quick command line access to a server, see the ``jirashell`` script included with this distribution. The easiest way to instantiate is using ``j = JIRA("https://jira.atlasian.com")`` Args: server (Optional[str]): The server address and context path to use. Defaults to ``http://localhost:2990/jira``. options (Optional[Dict[str, Any]]): Specify the server and properties this client will use. Use a dict with any of the following properties: * server -- the server address and context path to use. Defaults to ``http://localhost:2990/jira``. * rest_path -- the root REST path to use. Defaults to ``api``, where the Jira REST resources live. * rest_api_version -- the version of the REST resources under rest_path to use. Defaults to ``2``. * agile_rest_path - the REST path to use for Jira Agile requests. Defaults to ``greenhopper`` (old, private API). Check :py:class:`jira.resources.GreenHopperResource` for other supported values. * verify -- Verify SSL certs. Defaults to ``True``. * client_cert -- a tuple of (cert,key) for the requests library for client side SSL * check_update -- Check whether using the newest python-jira library version. basic_auth (Union[None, Tuple[str, str]]): A tuple of username and password to use when establishing a session via HTTP BASIC authentication. oauth (Optional[Any]): A dict of properties for OAuth authentication. The following properties are required: * access_token -- OAuth access token for the user * access_token_secret -- OAuth access token secret to sign with the key * consumer_key -- key of the OAuth application link defined in Jira * key_cert -- private key file to sign requests with (should be the pair of the public key supplied to Jira in the OAuth application link) kerberos (bool): If true it will enable Kerberos authentication. kerberos_options (Optional[Dict[str,str]]): A dict of properties for Kerberos authentication. The following properties are possible: * mutual_authentication -- string DISABLED or OPTIONAL. Example kerberos_options structure: ``{'mutual_authentication': 'DISABLED'}`` jwt (Optional[Any]): A dict of properties for JWT authentication supported by Atlassian Connect. The following properties are required: * secret -- shared secret as delivered during 'installed' lifecycle event (see https://developer.atlassian.com/static/connect/docs/latest/modules/lifecycle.html for details) * payload -- dict of fields to be inserted in the JWT payload, e.g. 'iss' Example jwt structure: ``{'secret': SHARED_SECRET, 'payload': {'iss': PLUGIN_KEY}}`` validate (bool): If true it will validate your credentials first. Remember that if you are accessing Jira as anonymous it will fail to instantiate. get_server_info (bool): If true it will fetch server version info first to determine if some API calls are available. async_ (bool): To enable async requests for those actions where we implemented it, like issue update() or delete(). async_workers (int): Set the number of worker threads for async operations. timeout (Optional[Union[Union[float, int], Tuple[float, float]]]): Set a read/connect timeout for the underlying calls to Jira (default: None). Obviously this means that you cannot rely on the return code when this is enabled. max_retries (int): Sets the amount Retries for the HTTP sessions initiated by the client. (Default: 3) proxies (Optional[Any]): Sets the proxies for the HTTP session. auth (Optional[Tuple[str,str]]): Set a cookie auth token if this is required. logging (bool): Determine whether or not logging should be enabled. (Default: True) """ # force a copy of the tuple to be used in __del__() because # sys.version_info could have already been deleted in __del__() self.sys_version_info = tuple([i for i in sys.version_info]) if options is None: options = {} if server and isinstance(server, dict): warnings.warn( "Old API usage, use JIRA(url) or JIRA(options={'server': url}, when using dictionary always use named parameters.", DeprecationWarning, ) options = server server = "" if server: options["server"] = server if async_: options["async"] = async_ options["async_workers"] = async_workers LOG.setLevel(_logging.INFO if logging else _logging.CRITICAL) self.log = LOG self._options: Dict[str, Any] = copy.copy(JIRA.DEFAULT_OPTIONS) self._options.update(options) self._rank = None # Rip off trailing slash since all urls depend on that assert isinstance(self._options["server"], str) # to help mypy if self._options["server"].endswith("/"): self._options["server"] = self._options["server"][:-1] context_path = urlparse(self.server_url).path if len(context_path) > 0: self._options["context_path"] = context_path self._try_magic() assert isinstance(self._options["headers"], dict) # for mypy benefit self._session: ResilientSession # for mypy benefit if oauth: self._create_oauth_session(oauth, timeout) elif basic_auth: self._create_http_basic_session(*basic_auth, timeout=timeout) self._session.headers.update(self._options["headers"]) elif jwt: self._create_jwt_session(jwt, timeout) elif kerberos: self._create_kerberos_session(timeout, kerberos_options=kerberos_options) elif auth: self._create_cookie_auth(auth, timeout) # always log in for cookie based auth, as we need a first request to be logged in validate = True else: verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.headers.update(self._options["headers"]) if "cookies" in self._options: self._session.cookies.update(self._options["cookies"]) self._session.max_retries = max_retries if proxies: self._session.proxies = proxies self.auth = auth if validate: # This will raise an Exception if you are not allowed to login. # It's better to fail faster than later. user = self.session() if user.raw is None: auth_method = ( oauth or basic_auth or jwt or kerberos or auth or "anonymous" ) raise JIRAError(f"Can not log in with {str(auth_method)}") self.deploymentType = None if get_server_info: # We need version in order to know what API calls are available or not si = self.server_info() try: self._version = tuple(si["versionNumbers"]) except Exception as e: self.log.error("invalid server_info: %s", si) raise e self.deploymentType = si.get("deploymentType") else: self._version = (0, 0, 0) if self._options["check_update"] and not JIRA.checked_version: self._check_update_() JIRA.checked_version = True self._fields = {} for f in self.fields(): if "clauseNames" in f: for name in f["clauseNames"]: self._fields[name] = f["id"] @property def server_url(self) -> str: """Return the server url""" return str(self._options["server"]) def _create_cookie_auth( self, auth: Tuple[str, str], timeout: Optional[Union[Union[float, int], Tuple[float, float]]], ): self._session = ResilientSession(timeout=timeout) self._session.auth = JiraCookieAuth(self._session, self.session, auth) self._session.verify = bool(self._options["verify"]) client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy self._session.cert = client_cert def _check_update_(self): """Check if the current version of the library is outdated.""" try: data = requests.get( "https://pypi.python.org/pypi/jira/json", timeout=2.001 ).json() released_version = data["info"]["version"] if parse_version(released_version) > parse_version(__version__): warnings.warn( "You are running an outdated version of Jira Python %s. Current version is %s. Do not file any bugs against older versions." % (__version__, released_version) ) except requests.RequestException: pass except Exception as e: self.log.warning(e) def __del__(self): """Destructor for JIRA instance.""" self.close() def close(self): session = getattr(self, "_session", None) if session is not None: try: session.close() except TypeError: # TypeError: "'NoneType' object is not callable" # Could still happen here because other references are also # in the process to be torn down, see warning section in # https://docs.python.org/2/reference/datamodel.html#object.__del__ pass self._session = None def _check_for_html_error(self, content: str): # Jira has the bad habit of returning errors in pages with 200 and # embedding the error in a huge webpage. if "<!-- SecurityTokenMissing -->" in content: self.log.warning("Got SecurityTokenMissing") raise JIRAError(f"SecurityTokenMissing: {content}") return False return True def _get_sprint_field_id(self): sprint_field_name = "Sprint" sprint_field_id = [ f["schema"]["customId"] for f in self.fields() if f["name"] == sprint_field_name ][0] return sprint_field_id def _fetch_pages( self, item_type: Type[ResourceType], items_key: Optional[str], request_path: str, startAt: int = 0, maxResults: int = 50, params: Dict[str, Any] = None, base: str = JIRA_BASE_URL, ) -> ResultList[ResourceType]: """Fetch from a paginated end point. Args: item_type (Type[Resource]): Type of single item. ResultList of such items will be returned. items_key (Optional[str]): Path to the items in JSON returned from server. Set it to None, if response is an array, and not a JSON object. request_path (str): path in request URL startAt (int): index of the first record to be fetched. (Default: 0) maxResults (int): Maximum number of items to return. If maxResults evaluates as False, it will try to get all items in batches. (Default:50) params (Dict[str, Any]): Params to be used in all requests. Should not contain startAt and maxResults, as they will be added for each request created from this function. base (str): base URL to use for the requests. Returns: ResultList """ async_workers = None async_class = None if self._options["async"]: try: from requests_futures.sessions import FuturesSession async_class = FuturesSession except ImportError: pass async_workers = self._options.get("async_workers") page_params = params.copy() if params else {} if startAt: page_params["startAt"] = startAt if maxResults: page_params["maxResults"] = maxResults resource = self._get_json(request_path, params=page_params, base=base) next_items_page = self._get_items_from_page(item_type, items_key, resource) items = next_items_page if True: # isinstance(resource, dict): if isinstance(resource, dict): total = resource.get("total") total = int(total) if total is not None else total # 'isLast' is the optional key added to responses in Jira Agile 6.7.6. So far not used in basic Jira API. is_last = resource.get("isLast", False) start_at_from_response = resource.get("startAt", 0) max_results_from_response = resource.get("maxResults", 1) else: # if is a list total = 1 is_last = True start_at_from_response = 0 max_results_from_response = 1 # If maxResults evaluates as False, get all items in batches if not maxResults: page_size = max_results_from_response or len(items) page_start = (startAt or start_at_from_response or 0) + page_size if ( async_class is not None and not is_last and (total is not None and len(items) < total) ): async_fetches = [] future_session = async_class( session=self._session, max_workers=async_workers ) for start_index in range(page_start, total, page_size): page_params = params.copy() if params else {} page_params["startAt"] = start_index page_params["maxResults"] = page_size url = self._get_url(request_path) r = future_session.get(url, params=page_params) async_fetches.append(r) for future in async_fetches: response = future.result() resource = json_loads(response) if resource: next_items_page = self._get_items_from_page( item_type, items_key, resource ) items.extend(next_items_page) while ( async_class is None and not is_last and (total is None or page_start < total) and len(next_items_page) == page_size ): page_params["startAt"] = page_start page_params["maxResults"] = page_size resource = self._get_json( request_path, params=page_params, base=base ) if resource: next_items_page = self._get_items_from_page( item_type, items_key, resource ) items.extend(next_items_page) page_start += page_size else: # if resource is an empty dictionary we assume no-results break return ResultList( items, start_at_from_response, max_results_from_response, total, is_last ) else: # TODO: unreachable # it seems that search_users can return a list() containing a single user! return ResultList( [item_type(self._options, self._session, resource)], 0, 1, 1, True ) def _get_items_from_page( self, item_type: Type[ResourceType], items_key: Optional[str], resource: Dict[str, Any], ) -> List[ResourceType]: try: return [ # We need to ignore the type here, as 'Resource' is an option item_type(self._options, self._session, raw_issue_json) # type: ignore for raw_issue_json in (resource[items_key] if items_key else resource) ] except KeyError as e: # improving the error text so we know why it happened raise KeyError(str(e) + " : " + json.dumps(resource)) # Information about this client def client_info(self) -> str: """Get the server this client is connected to.""" return self.server_url # Universal resource loading def find( self, resource_format: str, ids: Union[Tuple[str, str], int, str] = "" ) -> Resource: """Find Resource object for any addressable resource on the server. This method is a universal resource locator for any REST-ful resource in Jira. The argument ``resource_format`` is a string of the form ``resource``, ``resource/{0}``, ``resource/{0}/sub``, ``resource/{0}/sub/{1}``, etc. The format placeholders will be populated from the ``ids`` argument if present. The existing authentication session will be used. The return value is an untyped Resource object, which will not support specialized :py:meth:`.Resource.update` or :py:meth:`.Resource.delete` behavior. Moreover, it will not know to return an issue Resource if the client uses the resource issue path. For this reason, it is intended to support resources that are not included in the standard Atlassian REST API. Args: resource_format (str): the subpath to the resource string ids (Optional[Tuple]): values to substitute in the ``resource_format`` string Returns: Resource """ resource = Resource(resource_format, self._options, self._session) resource.find(ids) return resource @no_type_check # FIXME: This function fails type checking, probably a bug or two def async_do(self, size: int = 10): """Execute all asynchronous jobs and wait for them to finish. By default it will run on 10 threads. Args: size (int): number of threads to run on. """ if hasattr(self._session, "_async_jobs"): self.log.info( "Executing asynchronous %s jobs found in queue by using %s threads..." % (len(self._session._async_jobs), size) ) threaded_requests.map(self._session._async_jobs, size=size) # Application properties # non-resource def application_properties( self, key: str = None ) -> Union[Dict[str, str], List[Dict[str, str]]]: """Return the mutable server application properties. Args: key (Optional[str]): the single property to return a value for Returns: Union[Dict[str, str], List[Dict[str, str]]] """ params = {} if key is not None: params["key"] = key return self._get_json("application-properties", params=params) def set_application_property(self, key: str, value: str): """Set the application property. Args: key (str): key of the property to set value (str): value to assign to the property """ url = self._get_latest_url("application-properties/" + key) payload = {"id": key, "value": value} return self._session.put(url, data=json.dumps(payload)) def applicationlinks(self, cached: bool = True) -> List: """List of application links. Returns: List[Dict]: json, or empty list """ self._applicationlinks: List[Dict] # for mypy benefit # if cached, return the last result if cached and hasattr(self, "_applicationlinks"): return self._applicationlinks # url = self._options['server'] + '/rest/applinks/latest/applicationlink' url = self.server_url + "/rest/applinks/latest/listApplicationlinks" r = self._session.get(url) o = json_loads(r) if "list" in o and isinstance(o, dict): self._applicationlinks = o["list"] else: self._applicationlinks = [] return self._applicationlinks # Attachments def attachment(self, id: str) -> Attachment: """Get an attachment Resource from the server for the specified ID. Args: id (str): The Attachment ID Returns: Attachment """ return self._find_for_resource(Attachment, id) # non-resource def attachment_meta(self) -> Dict[str, int]: """Get the attachment metadata. Return: Dict[str, int] """ return self._get_json("attachment/meta") @translate_resource_args def add_attachment( self, issue: str, attachment: Union[str, BufferedReader], filename: str = None ) -> Attachment: """Attach an attachment to an issue and returns a Resource for it. The client will *not* attempt to open or validate the attachment; it expects a file-like object to be ready for its use. The user is still responsible for tidying up (e.g., closing the file, killing the socket, etc.) Args: issue (str): the issue to attach the attachment to attachment (Union[str,BufferedReader]): file-like object to attach to the issue, also works if it is a string with the filename. filename (str): optional name for the attached file. If omitted, the file object's ``name`` attribute is used. If you acquired the file-like object by any other method than ``open()``, make sure that a name is specified in one way or the other. Returns: Attachment """ close_attachment = False if isinstance(attachment, str): attachment: BufferedReader = open(attachment, "rb") # type: ignore attachment = cast(BufferedReader, attachment) close_attachment = True elif isinstance(attachment, BufferedReader) and attachment.mode != "rb": self.log.warning( "%s was not opened in 'rb' mode, attaching file may fail." % attachment.name ) url = self._get_url("issue/" + str(issue) + "/attachments") fname = filename if not fname and isinstance(attachment, BufferedReader): fname = os.path.basename(attachment.name) if "MultipartEncoder" not in globals(): method = "old" try: r = self._session.post( url, files={"file": (fname, attachment, "application/octet-stream")}, headers=CaseInsensitiveDict( {"content-type": None, "X-Atlassian-Token": "no-check"} ), ) finally: if close_attachment: attachment.close() else: method = "MultipartEncoder" def file_stream() -> MultipartEncoder: """Returns files stream of attachment.""" return MultipartEncoder( fields={"file": (fname, attachment, "application/octet-stream")} ) m = file_stream() try: r = self._session.post( url, data=m, headers=CaseInsensitiveDict( { "content-type": m.content_type, "X-Atlassian-Token": "no-check", } ), retry_data=file_stream, ) finally: if close_attachment: attachment.close() js: Union[Dict[str, Any], List[Dict[str, Any]]] = json_loads(r) if not js or not isinstance(js, Iterable): raise JIRAError(f"Unable to parse JSON: {js}") jira_attachment = Attachment( self._options, self._session, js[0] if isinstance(js, List) else js ) if jira_attachment.size == 0: raise JIRAError( "Added empty attachment via %s method?!: r: %s\nattachment: %s" % (method, r, jira_attachment) ) return jira_attachment def delete_attachment(self, id: str) -> Response: """Delete attachment by id. Args: id (str): ID of the attachment to delete Returns: Response """ url = self._get_url("attachment/" + str(id)) return self._session.delete(url) # Components def component(self, id: str): """Get a component Resource from the server. Args: id (str): ID of the component to get """ return self._find_for_resource(Component, id) @translate_resource_args def create_component( self, name: str, project: str, description=None, leadUserName=None, assigneeType=None, isAssigneeTypeValid=False, ) -> Component: """Create a component inside a project and return a Resource for it. Args: name (str): name of the component project (str): key of the project to create the component in description (str): a description of the component leadUserName (Optional[str]): the username of the user responsible for this component assigneeType (Optional[str]): see the ComponentBean.AssigneeType class for valid values isAssigneeTypeValid (bool): boolean specifying whether the assignee type is acceptable (Default: False) Returns: Component """ data = { "name": name, "project": project, "isAssigneeTypeValid": isAssigneeTypeValid, } if description is not None: data["description"] = description if leadUserName is not None: data["leadUserName"] = leadUserName if assigneeType is not None: data["assigneeType"] = assigneeType url = self._get_url("component") r = self._session.post(url, data=json.dumps(data)) component = Component(self._options, self._session, raw=json_loads(r)) return component def component_count_related_issues(self, id: str): """Get the count of related issues for a component. Args: id (str): ID of the component to use """ data: Dict[str, Any] = self._get_json( "component/" + str(id) + "/relatedIssueCounts" ) return data["issueCount"] def delete_component(self, id: str) -> Response: """Delete component by id. Args: id (str): ID of the component to use Returns: Response """ url = self._get_url("component/" + str(id)) return self._session.delete(url) # Custom field options def custom_field_option(self, id: str) -> CustomFieldOption: """Get a custom field option Resource from the server. Args: id (str): ID of the custom field to use Returns: CustomFieldOption """ return self._find_for_resource(CustomFieldOption, id) # Dashboards def dashboards( self, filter=None, startAt=0, maxResults=20 ) -> ResultList[Dashboard]: """Return a ResultList of Dashboard resources and a ``total`` count. Args: filter (Optional[str]): either "favourite" or "my", the type of dashboards to return startAt (int): index of the first dashboard to return (Default: 0) maxResults (int): maximum number of dashboards to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 20) Returns: ResultList """ params = {} if filter is not None: params["filter"] = filter return self._fetch_pages( Dashboard, "dashboards", "dashboard", startAt, maxResults, params ) def dashboard(self, id: str) -> Dashboard: """Get a dashboard Resource from the server. Args: id (str): ID of the dashboard to get. Returns: Dashboard """ return self._find_for_resource(Dashboard, id) # Fields # non-resource def fields(self) -> List[Dict[str, Any]]: """Return a list of all issue fields. Returns: List[Dict[str, Any]] """ return self._get_json("field") # Filters def filter(self, id: str) -> Filter: """Get a filter Resource from the server. Args: id (str): ID of the filter to get. Returns: Filter """ return self._find_for_resource(Filter, id) def favourite_filters(self) -> List[Filter]: """Get a list of filter Resources which are the favourites of the currently authenticated user. Returns: List[Filter] """ r_json: List[Dict[str, Any]] = self._get_json("filter/favourite") filters = [ Filter(self._options, self._session, raw_filter_json) for raw_filter_json in r_json ] return filters def create_filter( self, name: str = None, description: str = None, jql: str = None, favourite: bool = None, ): """Create a new filter and return a filter Resource for it. Args: name (str): name of the new filter description (str): useful human readable description of the new filter jql (str): query string that defines the filter favourite (bool): whether to add this filter to the current user's favorites Returns: Filter """ data: Dict[str, Any] = {} if name is not None: data["name"] = name if description is not None: data["description"] = description if jql is not None: data["jql"] = jql if favourite is not None: data["favourite"] = favourite url = self._get_url("filter") r = self._session.post(url, data=json.dumps(data)) raw_filter_json: Dict[str, Any] = json_loads(r) return Filter(self._options, self._session, raw=raw_filter_json) def update_filter( self, filter_id, name: str = None, description: str = None, jql: str = None, favourite: bool = None, ): """Update a filter and return a filter Resource for it. Args: name (Optional[str]): name of the new filter description (Optional[str]): useful human readable description of the new filter jql (Optional[str]): query string that defines the filter favourite (Optional[bool]): whether to add this filter to the current user's favorites """ filter = self.filter(filter_id) data = {} data["name"] = name or filter.name data["description"] = description or filter.description data["jql"] = jql or filter.jql data["favourite"] = favourite or filter.favourite url = self._get_url(f"filter/{filter_id}") r = self._session.put( url, headers={"content-type": "application/json"}, data=json.dumps(data) ) raw_filter_json = json.loads(r.text) return Filter(self._options, self._session, raw=raw_filter_json) # Groups def group(self, id: str, expand: Any = None) -> Group: """Get a group Resource from the server. Args: id (str): ID of the group to get expand (Optional[Any]): Extra information to fetch inside each resource Returns: Group """ group = Group(self._options, self._session) params = {} if expand is not None: params["expand"] = expand group.find(id, params=params) return group # non-resource def groups( self, query: Optional[str] = None, exclude: Optional[Any] = None, maxResults: int = 9999, ) -> List[str]: """Return a list of groups matching the specified criteria. Args: query (Optional[str]): filter groups by name with this string exclude (Optional[Any]): filter out groups by name with this string maxResults (int): maximum results to return. (Default: 9999) Returns: List[str] """ params: Dict[str, Any] = {} groups = [] if query is not None: params["query"] = query if exclude is not None: params["exclude"] = exclude if maxResults is not None: params["maxResults"] = maxResults for group in self._get_json("groups/picker", params=params)["groups"]: groups.append(group["name"]) return sorted(groups) def group_members(self, group: str) -> OrderedDict: """Return a hash or users with their information. Requires Jira 6.0 or will raise NotImplemented. Args: group (str): Name of the group. """ if self._version < (6, 0, 0): raise NotImplementedError( "Group members is not implemented in Jira before version 6.0, upgrade the instance, if possible." ) params = {"groupname": group, "expand": "users"} r = self._get_json("group", params=params) size = r["users"]["size"] end_index = r["users"]["end-index"] while end_index < size - 1: params = { "groupname": group, "expand": f"users[{end_index + 1}:{end_index + 50}]", } r2 = self._get_json("group", params=params) for user in r2["users"]["items"]: r["users"]["items"].append(user) end_index = r2["users"]["end-index"] size = r["users"]["size"] result = {} for user in r["users"]["items"]: result[user["id"]] = { "name": user.get("name"), "id": user.get("id"), "accountId": user.get("accountId"), "fullname": user.get("displayName"), "email": user.get("emailAddress", "hidden"), "active": user.get("active"), "timezone": user.get("timezone"), } return OrderedDict(sorted(result.items(), key=lambda t: t[0])) def add_group(self, groupname: str) -> bool: """Create a new group in Jira. Args: groupname (str): The name of the group you wish to create. Returns: bool: True if successful. """ url = self._get_latest_url("group") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 x = OrderedDict() x["name"] = groupname payload = json.dumps(x) self._session.post(url, data=payload) return True def remove_group(self, groupname: str) -> bool: """Delete a group from the Jira instance. Args: groupname (str): The group to be deleted from the Jira instance. Returns: bool: Returns True on success. """ # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 url = self._get_latest_url("group") x = {"groupname": groupname} self._session.delete(url, params=x) return True # Issues def issue( self, id: Union[Issue, str], fields: Optional[str] = None, expand: Optional[str] = None, ) -> Issue: """Get an issue Resource from the server. Args: id (Union[Issue, str]): ID or key of the issue to get fields (Optional[str]): comma-separated string of issue fields to include in the results expand (Optional[str]): extra information to fetch inside each resource Returns: Issue """ # this allows us to pass Issue objects to issue() if isinstance(id, Issue): return id issue = Issue(self._options, self._session) params = {} if fields is not None: params["fields"] = fields if expand is not None: params["expand"] = expand issue.find(id, params=params) return issue def create_issue( self, fields: Optional[Dict[str, Any]] = None, prefetch: bool = True, **fieldargs, ) -> Issue: """Create a new issue and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. By default, the client will immediately reload the issue Resource created by this method in order to return a complete Issue object to the caller; this behavior can be controlled through the 'prefetch' argument. Jira projects may contain many different issue types. Some issue screens have different requirements for fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue Args: fields (Optional[Dict[str, Any]]): a dict containing field names and the values to use. If present, all other keyword arguments will be ignored prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value returned from this method Returns: Issue """ data: Dict[str, Any] = _field_worker(fields, **fieldargs) p = data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): data["fields"]["project"] = {"id": self.project(str(p)).id} p = data["fields"]["issuetype"] if isinstance(p, int): data["fields"]["issuetype"] = {"id": p} if isinstance(p, str) or isinstance(p, int): data["fields"]["issuetype"] = {"id": self.issue_type_by_name(str(p)).id} url = self._get_url("issue") r = self._session.post(url, data=json.dumps(data)) raw_issue_json = json_loads(r) if "key" not in raw_issue_json: raise JIRAError( status_code=r.status_code, response=r, url=url, text=json.dumps(data) ) if prefetch: return self.issue(raw_issue_json["key"]) else: return Issue(self._options, self._session, raw=raw_issue_json) def create_issues( self, field_list: List[Dict[str, Any]], prefetch: bool = True ) -> List[Dict[str, Any]]: """Bulk create new issues and return an issue Resource for each successfully created issue. See `create_issue` documentation for field information. Args: field_list (List[Dict[str, Any]]): a list of dicts each containing field names and the values to use. Each dict is an individual issue to create and is subject to its minimum requirements. prefetch (bool): whether to reload the created issue Resource for each created issue so that all of its data is present in the value returned from this method. Returns: List[Dict[str, Any]] """ data: Dict[str, List] = {"issueUpdates": []} for field_dict in field_list: issue_data: Dict[str, Any] = _field_worker(field_dict) p = issue_data["fields"]["project"] if isinstance(p, str) or isinstance(p, int): issue_data["fields"]["project"] = {"id": self.project(str(p)).id} p = issue_data["fields"]["issuetype"] if isinstance(p, int): issue_data["fields"]["issuetype"] = {"id": p} if isinstance(p, str): issue_data["fields"]["issuetype"] = { "id": self.issue_type_by_name(str(p)).id } data["issueUpdates"].append(issue_data) url = self._get_url("issue/bulk") try: r = self._session.post(url, data=json.dumps(data)) raw_issue_json = json_loads(r) # Catching case where none of the issues has been created. See https://github.com/pycontribs/jira/issues/350 except JIRAError as je: if je.status_code == 400 and je.response: raw_issue_json = json.loads(je.response.text) else: raise issue_list = [] errors = {} for error in raw_issue_json["errors"]: errors[error["failedElementNumber"]] = error["elementErrors"]["errors"] for index, fields in enumerate(field_list): if index in errors: issue_list.append( { "status": "Error", "error": errors[index], "issue": None, "input_fields": fields, } ) else: issue = raw_issue_json["issues"].pop(0) if prefetch: issue = self.issue(issue["key"]) else: issue = Issue(self._options, self._session, raw=issue) issue_list.append( { "status": "Success", "issue": issue, "error": None, "input_fields": fields, } ) return issue_list def supports_service_desk(self): """Returns whether or not the Jira instance supports service desk. Returns: bool """ url = self.server_url + "/rest/servicedeskapi/info" headers = {"X-ExperimentalApi": "opt-in"} try: r = self._session.get(url, headers=headers) return r.status_code == 200 except JIRAError: return False def create_customer(self, email: str, displayName: str) -> Customer: """Create a new customer and return an issue Resource for it. Args: email (str): Customer Email displayName (str): Customer display name Returns: Customer """ url = self.server_url + "/rest/servicedeskapi/customer" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post( url, headers=headers, data=json.dumps({"email": email, "displayName": displayName}), ) raw_customer_json = json_loads(r) if r.status_code != 201: raise JIRAError(status_code=r.status_code, request=r) return Customer(self._options, self._session, raw=raw_customer_json) def service_desks(self) -> List[ServiceDesk]: """Get a list of ServiceDesk Resources from the server visible to the current authenticated user. Returns: List[ServiceDesk] """ url = self.server_url + "/rest/servicedeskapi/servicedesk" headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) print(r_json) projects = [ ServiceDesk(self._options, self._session, raw_project_json) for raw_project_json in r_json["values"] ] return projects def service_desk(self, id: str) -> ServiceDesk: """Get a Service Desk Resource from the server. Args: id (str): ID or key of the Service Desk to get Returns: ServiceDesk """ return self._find_for_resource(ServiceDesk, id) @no_type_check # FIXME: This function does not do what it wants to with fieldargs def create_customer_request( self, fields: Dict[str, Any] = None, prefetch: bool = True, **fieldargs ) -> Issue: """Create a new customer request and return an issue Resource for it. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. By default, the client will immediately reload the issue Resource created by this method in order to return a complete Issue object to the caller; this behavior can be controlled through the 'prefetch' argument. Jira projects may contain many different issue types. Some issue screens have different requirements for fields in a new issue. This information is available through the 'createmeta' method. Further examples are available here: https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+Example+-+Create+Issue Args: fields (Dict[str, Any]): a dict containing field names and the values to use. If present, all other keyword arguments will be ignored prefetch (bool): whether to reload the created issue Resource so that all of its data is present in the value returned from this method Returns: Issue """ data = fields p = data["serviceDeskId"] service_desk = None if isinstance(p, str) or isinstance(p, int): service_desk = self.service_desk(p) elif isinstance(p, ServiceDesk): service_desk = p data["serviceDeskId"] = service_desk.id p = data["requestTypeId"] if isinstance(p, int): data["requestTypeId"] = p elif isinstance(p, str): data["requestTypeId"] = self.request_type_by_name(service_desk, p).id url = self.server_url + "/rest/servicedeskapi/request" headers = {"X-ExperimentalApi": "opt-in"} r = self._session.post(url, headers=headers, data=json.dumps(data)) raw_issue_json = json_loads(r) if "issueKey" not in raw_issue_json: raise JIRAError(status_code=r.status_code, request=r) if prefetch: return self.issue(raw_issue_json["issueKey"]) else: return Issue(self._options, self._session, raw=raw_issue_json) def createmeta( self, projectKeys: Optional[Union[Tuple[str, str], str]] = None, projectIds: Union[List, Tuple[str, str]] = [], issuetypeIds: Optional[List[str]] = None, issuetypeNames: Optional[str] = None, expand: Optional[str] = None, ) -> Dict[str, Any]: """Get the metadata required to create issues, optionally filtered by projects and issue types. Args: projectKeys (Optional[Union[Tuple[str, str], str]]): keys of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectIds. projectIds (Union[List, Tuple[str, str]]): IDs of the projects to filter the results with. Can be a single value or a comma-delimited string. May be combined with projectKeys. issuetypeIds (Optional[List[str]]): IDs of the issue types to filter the results with. Can be a single value or a comma-delimited string. May be combined with issuetypeNames. issuetypeNames (Optional[str]): Names of the issue types to filter the results with. Can be a single value or a comma-delimited string. May be combined with issuetypeIds. expand (Optional[str]): extra information to fetch inside each resource. Returns: Dict[str, Any] """ params: Dict[str, Any] = {} if projectKeys is not None: params["projectKeys"] = projectKeys if projectIds is not None: if isinstance(projectIds, str): projectIds = projectIds.split(",") params["projectIds"] = projectIds if issuetypeIds is not None: params["issuetypeIds"] = issuetypeIds if issuetypeNames is not None: params["issuetypeNames"] = issuetypeNames if expand is not None: params["expand"] = expand return self._get_json("issue/createmeta", params) def _get_user_key(self, user: str) -> str: """Internal method for translating an user (str) to an key.""" try: key = self.search_users(user, maxResults=1)[0].key except Exception as e: raise JIRAError(str(e)) return key # non-resource @translate_resource_args def assign_issue(self, issue: Union[int, str], assignee: str) -> bool: """Assign an issue to a user. None will set it to unassigned. -1 will set it to Automatic. Args: issue (Union[int,str]): the issue ID or key to assign assignee (str): the user to assign the issue to Returns: bool """ url = self._get_latest_url("issue/{}/assignee".format(str(issue))) payload = {"name": self._get_user_key(assignee)} # 'key' and 'name' are deprecated in favor of accountId r = self._session.put(url, data=json.dumps(payload)) raise_on_error(r) return True @translate_resource_args def comments(self, issue: str, expand: Optional[str] = None) -> List[Comment]: """Get a list of comment Resources. :param issue: the issue to get comments from :type issue: str :param expand: extra information to fetch for each comment such as renderedBody and properties. :type expand: str :rtype: List[Comment] """ params = {} if expand is not None: params["expand"] = expand r_json = self._get_json("issue/{}/comment".format(str(issue)), params=params) comments = [ Comment(self._options, self._session, raw_comment_json) for raw_comment_json in r_json["comments"] ] return comments @translate_resource_args def comment( self, issue: str, comment: str, expand: Optional[str] = None ) -> Comment: """Get a comment Resource from the server for the specified ID. :param issue: ID or key of the issue to get the comment from :param comment: ID of the comment to get :param expand: extra information to fetch for comment such as renderedBody and properties. """ return self._find_for_resource(Comment, (issue, comment), expand=expand) @translate_resource_args def add_comment( self, issue: str, body: str, visibility: Optional[Dict[str, str]] = None, is_internal: bool = False, ) -> Comment: """Add a comment from the current authenticated user on the specified issue and return a Resource for it. The issue identifier and comment body are required. Args: issue (str): ID or key of the issue to add the comment to body (str): Text of the comment to add visibility (Optional[Dict[str, str]]): a dict containing two entries: "type" and "value". "type" is 'role' (or 'group' if the Jira server has configured comment visibility for groups) and 'value' is the name of the role (or group) to which viewing of this comment will be restricted. is_internal (bool): Defines whether a comment has to be marked as 'Internal' in Jira Service Desk (Default: False) Returns: Comment: the created comment """ data: Dict[str, Any] = {"body": body} if is_internal: data.update( { "properties": [ {"key": "sd.public.comment", "value": {"internal": is_internal}} ] } ) if visibility is not None: data["visibility"] = visibility url = self._get_url("issue/" + str(issue) + "/comment") r = self._session.post(url, data=json.dumps(data)) comment = Comment(self._options, self._session, raw=json_loads(r)) return comment # non-resource @translate_resource_args def editmeta(self, issue: Union[str, int]): """Get the edit metadata for an issue. Args: issue (str): the issue to get metadata for Returns: Dict[str, Dict[str, Dict[str, Any]]] """ return self._get_json("issue/" + str(issue) + "/editmeta") @translate_resource_args def remote_links(self, issue: Union[str, int]) -> List[RemoteLink]: """Get a list of remote link Resources from an issue. Args: issue (str): the issue to get remote links from """ r_json = self._get_json("issue/" + str(issue) + "/remotelink") remote_links = [ RemoteLink(self._options, self._session, raw_remotelink_json) for raw_remotelink_json in r_json ] return remote_links @translate_resource_args def remote_link(self, issue: str, id: str) -> RemoteLink: """Get a remote link Resource from the server. Args: issue (str): the issue holding the remote link id (str): ID of the remote link """ return self._find_for_resource(RemoteLink, (issue, id)) # removed the @translate_resource_args because it prevents us from finding # information for building a proper link def add_remote_link( self, issue: str, destination: Union[Issue, Dict[str, Any]], globalId: Optional[str] = None, application: Optional[Dict[str, Any]] = None, relationship: Optional[str] = None, ) -> RemoteLink: """Add a remote link from an issue to an external application and returns a remote link Resource for it. ``destination`` should be a dict containing at least ``url`` to the linked external URL and ``title`` to display for the link inside Jira. For definitions of the allowable fields for ``object`` and the keyword arguments ``globalId``, ``application`` and ``relationship``, see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. Args: issue (str): the issue to add the remote link to destination (Union[Issue, Dict[str, Any]]): the link details to add (see the above link for details) globalId (Optional[str]): unique ID for the link (see the above link for details) application (Optional[Dict[str,Any]]): application information for the link (see the above link for details) relationship (Optional[str]): relationship description for the link (see the above link for details) Returns: RemoteLink: the added remote lint """ try: applicationlinks: List[Dict] = self.applicationlinks() except JIRAError as e: applicationlinks = [] # In many (if not most) configurations, non-admin users are # not allowed to list applicationlinks; if we aren't allowed, # let's let people try to add remote links anyway, we just # won't be able to be quite as helpful. warnings.warn( "Unable to gather applicationlinks; you will not be able " "to add links to remote issues: (%s) %s" % (e.status_code, e.text), Warning, ) data: Dict[str, Any] = {} if isinstance(destination, Issue) and destination.raw: data["object"] = {"title": str(destination), "url": destination.permalink()} for x in applicationlinks: if x["application"]["displayUrl"] == destination._options["server"]: data["globalId"] = "appId=%s&issueId=%s" % ( x["application"]["id"], destination.raw["id"], ) data["application"] = { "name": x["application"]["name"], "type": "com.atlassian.jira", } break if "globalId" not in data: raise NotImplementedError("Unable to identify the issue to link to.") else: if globalId is not None: data["globalId"] = globalId if application is not None: data["application"] = application data["object"] = destination if relationship is not None: data["relationship"] = relationship # check if the link comes from one of the configured application links if isinstance(destination, Issue) and destination.raw: for x in applicationlinks: if x["application"]["displayUrl"] == self.server_url: data["globalId"] = "appId=%s&issueId=%s" % ( x["application"]["id"], destination.raw["id"], # .raw only present on Issue ) data["application"] = { "name": x["application"]["name"], "type": "com.atlassian.jira", } break url = self._get_url("issue/" + str(issue) + "/remotelink") r = self._session.post(url, data=json.dumps(data)) remote_link = RemoteLink(self._options, self._session, raw=json_loads(r)) return remote_link def add_simple_link(self, issue: str, object: Dict[str, Any]): """Add a simple remote link from an issue to web resource. This avoids the admin access problems from add_remote_link by just using a simple object and presuming all fields are correct and not requiring more complex ``application`` data. ``object`` should be a dict containing at least ``url`` to the linked external URL and ``title`` to display for the link inside Jira. For definitions of the allowable fields for ``object`` , see https://developer.atlassian.com/display/JIRADEV/JIRA+REST+API+for+Remote+Issue+Links. Args: issue (str): the issue to add the remote link to object (Dict[str,Any]): the dictionary used to create remotelink data Returns: RemoteLint """ data = {"object": object} url = self._get_url("issue/" + str(issue) + "/remotelink") r = self._session.post(url, data=json.dumps(data)) simple_link = RemoteLink(self._options, self._session, raw=json_loads(r)) return simple_link # non-resource @translate_resource_args def transitions(self, issue: str, id: Optional[str] = None, expand=None): """Get a list of the transitions available on the specified issue to the current user. Args: issue (str): ID or key of the issue to get the transitions from id (Optional[str]): if present, get only the transition matching this ID expand (Optional): extra information to fetch inside each transition Returns: Any: json of response """ params = {} if id is not None: params["transitionId"] = id if expand is not None: params["expand"] = expand return self._get_json("issue/" + str(issue) + "/transitions", params=params)[ "transitions" ] def find_transitionid_by_name( self, issue: str, transition_name: str ) -> Optional[int]: """Get a transitionid available on the specified issue to the current user. Look at https://developer.atlassian.com/static/rest/jira/6.1.html#d2e1074 for json reference Args: issue (str): ID or key of the issue to get the transitions from trans_name (str): iname of transition we are looking for """ transitions_json = self.transitions(issue) id: Optional[int] = None for transition in transitions_json: if transition["name"].lower() == transition_name.lower(): id = transition["id"] break return id @translate_resource_args def transition_issue( self, issue: str, transition: str, fields: Optional[Dict[str, Any]] = None, comment: Optional[str] = None, worklog: Optional[str] = None, **fieldargs, ): """Perform a transition on an issue. Each keyword argument (other than the predefined ones) is treated as a field name and the argument's value is treated as the intended value for that field -- if the fields argument is used, all other keyword arguments will be ignored. Field values will be set on the issue as part of the transition process. Args: issue (str): ID or key of the issue to perform the transition on transition (str): ID or name of the transition to perform fields (Optional[Dict[str,Any]]): a dict containing field names and the values to use. comment (Optional[str]): String to add as comment to the issue when performing the transition. workload (Optional[str]): String to add as time spent on the issue when performing the transition. **fieldargs: If present, all other keyword arguments will be ignored """ transitionId: Optional[int] = None try: transitionId = int(transition) except Exception: # cannot cast to int, so try to find transitionId by name transitionId = self.find_transitionid_by_name(issue, transition) if transitionId is None: raise JIRAError(f"Invalid transition name. {transition}") data: Dict[str, Any] = {"transition": {"id": transitionId}} if comment: data["update"] = {"comment": [{"add": {"body": comment}}]} if worklog: data["update"] = {"worklog": [{"add": {"timeSpent": worklog}}]} if fields is not None: data["fields"] = fields else: fields_dict = {} for field in fieldargs: fields_dict[field] = fieldargs[field] data["fields"] = fields_dict url = self._get_url("issue/" + str(issue) + "/transitions") r = self._session.post(url, data=json.dumps(data)) try: r_json = json_loads(r) except ValueError as e: self.log.error(f"{e}\n{r.text}") raise e return r_json @translate_resource_args def votes(self, issue: str) -> Votes: """Get a votes Resource from the server. Args: issue (str): ID or key of the issue to get the votes for Returns: Votes """ return self._find_for_resource(Votes, issue) @translate_resource_args def add_vote(self, issue: str) -> Response: """Register a vote for the current authenticated user on an issue. Args: issue (str): ID or key of the issue to vote on Returns: Response """ url = self._get_url("issue/" + str(issue) + "/votes") return self._session.post(url) @translate_resource_args def remove_vote(self, issue: str): """Remove the current authenticated user's vote from an issue. Args: issue (str): ID or key of the issue to remove vote on """ url = self._get_url("issue/" + str(issue) + "/votes") self._session.delete(url) @translate_resource_args def watchers(self, issue: str) -> Watchers: """Get a watchers Resource from the server for an issue. Args: issue (str): ID or key of the issue to get the watchers for Returns: Watchers """ return self._find_for_resource(Watchers, issue) @translate_resource_args def add_watcher(self, issue: str, watcher: str) -> Response: """Add a user to an issue's watchers list. Args: issue (str): ID or key of the issue affected watcher (str): key of the user to add to the watchers list """ url = self._get_url("issue/" + str(issue) + "/watchers") return self._session.post(url, data=json.dumps(watcher)) @translate_resource_args def remove_watcher(self, issue: str, watcher: str) -> Response: """Remove a user from an issue's watch list. Args: issue (str): ID or key of the issue affected watcher (str): key of the user to remove from the watchers list Returns: Response """ url = self._get_url("issue/" + str(issue) + "/watchers") # https://docs.atlassian.com/software/jira/docs/api/REST/8.13.6/#api/2/issue-removeWatcher params = {"username": watcher} result = self._session.delete(url, params=params) return result @translate_resource_args def worklogs(self, issue: str) -> List[Worklog]: """Get a list of worklog Resources from the server for an issue. Args: issue (str): ID or key of the issue to get worklogs from Returns: List[Worklog] """ r_json = self._get_json("issue/" + str(issue) + "/worklog") worklogs = [ Worklog(self._options, self._session, raw_worklog_json) for raw_worklog_json in r_json["worklogs"] ] return worklogs @translate_resource_args def worklog(self, issue: str, id: str) -> Worklog: """Get a specific worklog Resource from the server. Args: issue (str): ID or key of the issue to get the worklog from id (str): ID of the worklog to get Returns: Worklog """ return self._find_for_resource(Worklog, (issue, id)) @translate_resource_args def add_worklog( self, issue, timeSpent: (Optional[str]) = None, timeSpentSeconds: (Optional[str]) = None, adjustEstimate: (Optional[str]) = None, newEstimate: (Optional[str]) = None, reduceBy: (Optional[str]) = None, comment: (Optional[str]) = None, started: (Optional[datetime.datetime]) = None, user: (Optional[str]) = None, ) -> Worklog: """Add a new worklog entry on an issue and return a Resource for it. Args: issue (str): the issue to add the worklog to timeSpent (Optional[str]): a worklog entry with this amount of time spent, e.g. "2d" timeSpentSeconds (Optional[str]): a worklog entry with this amount of time spent in seconds adjustEstimate (Optional[str]): allows the user to provide specific instructions to update the remaining time estimate of the issue. The value can either be ``new``, ``leave``, ``manual`` or ``auto`` (default). newEstimate (Optional[str]): the new value for the remaining estimate field. e.g. "2d" reduceBy (Optional[str]): the amount to reduce the remaining estimate by e.g. "2d" comment (Optional[str]): optional worklog comment started (Optional[datetime.datetime]): Moment when the work is logged, if not specified will default to now user (Optional[str]): the user ID or name to use for this worklog Returns: Worklog """ params = {} if adjustEstimate is not None: params["adjustEstimate"] = adjustEstimate if newEstimate is not None: params["newEstimate"] = newEstimate if reduceBy is not None: params["reduceBy"] = reduceBy data: Dict[str, Any] = {} if timeSpent is not None: data["timeSpent"] = timeSpent if timeSpentSeconds is not None: data["timeSpentSeconds"] = timeSpentSeconds if comment is not None: data["comment"] = comment elif user: # we log user inside comment as it doesn't always work data["comment"] = user if started is not None: # based on REST Browser it needs: "2014-06-03T08:21:01.273+0000" if started.tzinfo is None: data["started"] = started.strftime("%Y-%m-%dT%H:%M:%S.000+0000") else: data["started"] = started.strftime("%Y-%m-%dT%H:%M:%S.000%z") if user is not None: data["author"] = { "name": user, "self": self.JIRA_BASE_URL + "/rest/api/latest/user?username=" + user, "displayName": user, "active": False, } data["updateAuthor"] = data["author"] # report bug to Atlassian: author and updateAuthor parameters are # ignored. url = self._get_url(f"issue/{issue}/worklog") r = self._session.post(url, params=params, data=json.dumps(data)) return Worklog(self._options, self._session, json_loads(r)) # Issue links @translate_resource_args def create_issue_link( self, type: Union[str, IssueLinkType], inwardIssue: str, outwardIssue: str, comment: Optional[Dict[str, Any]] = None, ) -> Response: """Create a link between two issues. Args: type (Union[str,IssueLinkType]): the type of link to create inwardIssue: the issue to link from outwardIssue: the issue to link to comment (Optional[Dict[str, Any]]): a comment to add to the issues with the link. Should be a dict containing ``body`` and ``visibility`` fields: ``body`` being the text of the comment and ``visibility`` being a dict containing two entries: ``type`` and ``value``. ``type`` is ``role`` (or ``group`` if the Jira server has configured comment visibility for groups) and ``value`` is the name of the role (or group) to which viewing of this comment will be restricted. Returns: Response """ # let's see if we have the right issue link 'type' and fix it if needed issue_link_types = self.issue_link_types() if type not in issue_link_types: for lt in issue_link_types: if lt.outward == type: # we are smart to figure it out what he meant type = lt.name break elif lt.inward == type: # so that's the reverse, so we fix the request type = lt.name inwardIssue, outwardIssue = outwardIssue, inwardIssue break data = { "type": {"name": type}, "inwardIssue": {"key": inwardIssue}, "outwardIssue": {"key": outwardIssue}, "comment": comment, } url = self._get_url("issueLink") return self._session.post(url, data=json.dumps(data)) def delete_issue_link(self, id: str): """Delete a link between two issues. Args: id (str): ID of the issue link to delete """ url = self._get_url("issueLink") + "/" + id return self._session.delete(url) def issue_link(self, id: str): """Get an issue link Resource from the server. Args: id (str): ID of the issue link to get """ return self._find_for_resource(IssueLink, id) # Issue link types def issue_link_types(self, force: bool = False) -> List[IssueLinkType]: """Get a list of issue link type Resources from the server. Returns: List[IssueLinkType] """ if not hasattr(self, "self._cached_issue_link_types") or force: r_json = self._get_json("issueLinkType") self._cached_issue_link_types = [ IssueLinkType(self._options, self._session, raw_link_json) for raw_link_json in r_json["issueLinkTypes"] ] return self._cached_issue_link_types def issue_link_type(self, id: str) -> IssueLinkType: """Get an issue link type Resource from the server. Args: id (str): ID of the issue link type to get Returns: IssueLinkType """ return self._find_for_resource(IssueLinkType, id) # Issue types def issue_types(self) -> List[IssueType]: """Get a list of issue type Resources from the server. Returns: List[IssueType] """ r_json = self._get_json("issuetype") issue_types = [ IssueType(self._options, self._session, raw_type_json) for raw_type_json in r_json ] return issue_types def issue_type(self, id: str) -> IssueType: """Get an issue type Resource from the server. Args: id (str): ID of the issue type to get Returns: IssueType """ return self._find_for_resource(IssueType, id) def issue_type_by_name(self, name: str) -> IssueType: """ Args: name (str): Name of the issue type Returns: IssueType """ matching_issue_types = [it for it in self.issue_types() if it.name == name] if len(matching_issue_types) == 1: return matching_issue_types[0] elif len(matching_issue_types) == 0: raise KeyError(f"Issue type '{name}' is unknown.") else: raise KeyError(f"Issue type '{name}' appears more than once.") def request_types(self, service_desk: ServiceDesk) -> List[RequestType]: """Returns request types supported by a service desk instance. Args: service_desk (ServiceDesk): The service desk instance. Returns: List[RequestType] """ if hasattr(service_desk, "id"): service_desk = service_desk.id url = ( self.server_url + f"/rest/servicedeskapi/servicedesk/{service_desk}/requesttype" ) headers = {"X-ExperimentalApi": "opt-in"} r_json = json_loads(self._session.get(url, headers=headers)) request_types = [ RequestType(self._options, self._session, raw_type_json) for raw_type_json in r_json["values"] ] return request_types def request_type_by_name(self, service_desk: ServiceDesk, name: str): request_types = self.request_types(service_desk) try: request_type = [rt for rt in request_types if rt.name == name][0] except IndexError: raise KeyError(f"Request type '{name}' is unknown.") return request_type # User permissions # non-resource def my_permissions( self, projectKey: Optional[str] = None, projectId: Optional[str] = None, issueKey: Optional[str] = None, issueId: Optional[str] = None, ) -> Dict[str, Dict[str, Dict[str, str]]]: """Get a dict of all available permissions on the server. Args: projectKey (Optional[str]): limit returned permissions to the specified project projectId (Optional[str]): limit returned permissions to the specified project issueKey (Optional[str]): limit returned permissions to the specified issue issueId (Optional[str]): limit returned permissions to the specified issue Returns: Dict[str, Dict[str, Dict[str, str]]] """ params = {} if projectKey is not None: params["projectKey"] = projectKey if projectId is not None: params["projectId"] = projectId if issueKey is not None: params["issueKey"] = issueKey if issueId is not None: params["issueId"] = issueId return self._get_json("mypermissions", params=params) # Priorities def priorities(self): """Get a list of priority Resources from the server. Returns: List[Priority] """ r_json = self._get_json("priority") priorities = [ Priority(self._options, self._session, raw_priority_json) for raw_priority_json in r_json ] return priorities def priority(self, id: str) -> Priority: """Get a priority Resource from the server. Args: id (str): ID of the priority to get Returns: Priority """ return self._find_for_resource(Priority, id) # Projects def projects(self) -> List[Project]: """Get a list of project Resources from the server visible to the current authenticated user. Returns: List[Project] """ r_json = self._get_json("project") projects = [ Project(self._options, self._session, raw_project_json) for raw_project_json in r_json ] return projects def project(self, id: str) -> Project: """Get a project Resource from the server. Args: id (str): ID or key of the project to get Returns: Project """ return self._find_for_resource(Project, id) # non-resource @translate_resource_args def project_avatars(self, project: str): """Get a dict of all avatars for a project visible to the current authenticated user. Args: project (str): ID or key of the project to get avatars for """ return self._get_json("project/" + project + "/avatars") @translate_resource_args def create_temp_project_avatar( self, project: str, filename: str, size: int, avatar_img: bytes, contentType: str = None, auto_confirm: bool = False, ): """Register an image file as a project avatar. The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, size, and file object. By default, the client will attempt to autodetect the picture's content type: this mechanism relies on libmagic and will not work out of the box on Windows systems (see https://filemagic.readthedocs.io/en/latest/guide.html for details on how to install support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) This method returns a dict of properties that can be used to crop a subarea of a larger image for use. This dict should be saved and passed to :py:meth:`confirm_project_avatar` to finish the avatar creation process. If you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the 'auto_confirm' argument with a truthy value and :py:meth:`confirm_project_avatar` will be called for you before this method returns. Args: project (str): ID or key of the project to create the avatar in filename (str): name of the avatar file size (int): size of the avatar file avatar_img (bytes): file-like object holding the avatar contentType (str): explicit specification for the avatar image's content-type auto_confirm (bool): whether to automatically confirm the temporary avatar by calling :py:meth:`confirm_project_avatar` with the return value of this method. (Default: False) """ size_from_file = os.path.getsize(filename) if size != size_from_file: size = size_from_file params = {"filename": filename, "size": size} headers: Dict[str, Any] = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType else: # try to detect content-type, this may return None headers["content-type"] = self._get_mime_type(avatar_img) url = self._get_url("project/" + project + "/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_project_avatar(project, cropping_properties) else: return cropping_properties @translate_resource_args def confirm_project_avatar(self, project: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar for use. The final avatar can be a subarea of the uploaded image, which is customized with the ``cropping_properties``: the return value of :py:meth:`create_temp_project_avatar` should be used for this argument. Args: project (str): ID or key of the project to confirm the avatar in cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_project_avatar` """ data = cropping_properties url = self._get_url("project/" + project + "/avatar") r = self._session.post(url, data=json.dumps(data)) return json_loads(r) @translate_resource_args def set_project_avatar(self, project: str, avatar: str): """Set a project's avatar. Args: project (str): ID or key of the project to set the avatar on avatar (str): ID of the avatar to set """ self._set_avatar(None, self._get_url("project/" + project + "/avatar"), avatar) @translate_resource_args def delete_project_avatar(self, project: str, avatar: str) -> Response: """Delete a project's avatar. Args: project (str): ID or key of the project to delete the avatar from avatar (str): ID of the avatar to delete """ url = self._get_url("project/" + project + "/avatar/" + avatar) return self._session.delete(url) @translate_resource_args def project_components(self, project: str) -> List[Component]: """Get a list of component Resources present on a project. Args: project (str): ID or key of the project to get components from Returns: List[Component] """ r_json = self._get_json("project/" + project + "/components") components = [ Component(self._options, self._session, raw_comp_json) for raw_comp_json in r_json ] return components @translate_resource_args def project_versions(self, project: str) -> List[Version]: """Get a list of version Resources present on a project. Args: project (str): ID or key of the project to get versions from Returns: List[Version] """ r_json = self._get_json("project/" + project + "/versions") versions = [ Version(self._options, self._session, raw_ver_json) for raw_ver_json in r_json ] return versions @translate_resource_args def get_project_version_by_name( self, project: str, version_name: str ) -> Optional[Version]: """Get a version Resource by its name present on a project. Args: project (str): ID or key of the project to get versions from version_name (str): name of the version to search for Returns: Optional[Version] """ versions: List[Version] = self.project_versions(project) for version in versions: if version.name == version_name: return version return None @translate_resource_args def rename_version(self, project: str, old_name: str, new_name: str) -> None: """Rename a version Resource on a project. Args: project (str): ID or key of the project to get versions from old_name (str): old name of the version to rename new_name (str): new name of the version to rename Returns: None """ version = self.get_project_version_by_name(project, old_name) if version: version.update(name=new_name) # non-resource @translate_resource_args def project_roles(self, project: str) -> Dict[str, Dict[str, str]]: """Get a dict of role names to resource locations for a project. Args: project (str): ID or key of the project to get roles from """ path = "project/" + project + "/role" _rolesdict: Dict[str, str] = self._get_json(path) rolesdict: Dict[str, Dict[str, str]] = {} for k, v in _rolesdict.items(): tmp: Dict[str, str] = {} tmp["id"] = v.split("/")[-1] tmp["url"] = v rolesdict[k] = tmp return rolesdict # TODO(ssbarnea): return a list of Roles() @translate_resource_args def project_role(self, project: str, id: str) -> Role: """Get a role Resource. Args: project (str): ID or key of the project to get the role from id (str): ID of the role to get """ if isinstance(id, Number): id = f"{id}" return self._find_for_resource(Role, (project, id)) # Resolutions def resolutions(self) -> List[Resolution]: """Get a list of resolution Resources from the server. Returns: List[Resolution] """ r_json = self._get_json("resolution") resolutions = [ Resolution(self._options, self._session, raw_res_json) for raw_res_json in r_json ] return resolutions def resolution(self, id: str) -> Resolution: """Get a resolution Resource from the server. Args: id (str): ID of the resolution to get Returns: Resolution """ return self._find_for_resource(Resolution, id) # Search def search_issues( self, jql_str: str, startAt: int = 0, maxResults: int = 50, validate_query: bool = True, fields: Optional[Union[str, List[str]]] = None, expand: Optional[str] = None, json_result: bool = False, ) -> Union[List[Dict[str, Any]], ResultList[Issue]]: """Get a :class:`~jira.client.ResultList` of issue Resources matching a JQL search string. Args: jql_str (str): The JQL search string. startAt (int): Index of the first issue to return. (Default: 0) maxResults (int): Maximum number of issues to return. Total number of results is available in the ``total`` attribute of the returned :class:`~jira.client.ResultList`. If maxResults evaluates as False, it will try to get all issues in batches. (Default: 50) validate_query (bool): Whether or not the query should be validated. (Default: True) fields (Optional[Union[str, List[str]]]): comma-separated string or list of issue fields to include in the results. Default is to include all fields. expand (Optional[str]): extra information to fetch inside each resource json_result (bool): JSON response will be returned when this parameter is set to True. Otherwise, :class:`~jira.client.ResultList` will be returned. Returns: Union[Dict,ResultList]: Dict if ``json_result=True`` """ if isinstance(fields, str): fields = fields.split(",") else: fields = list(fields or []) # this will translate JQL field names to REST API Name # most people do know the JQL names so this will help them use the API easier untranslate = {} # use to add friendly aliases when we get the results back if self._fields: for i, field in enumerate(fields): if field in self._fields: untranslate[self._fields[field]] = fields[i] fields[i] = self._fields[field] search_params = { "jql": jql_str, "startAt": startAt, "validateQuery": validate_query, "fields": fields, "expand": expand, } if json_result: search_params["maxResults"] = maxResults if not maxResults: warnings.warn( "All issues cannot be fetched at once, when json_result parameter is set", Warning, ) r_json: List[Dict[str, Any]] = self._get_json( "search", params=search_params ) return r_json issues = self._fetch_pages( Issue, "issues", "search", startAt, maxResults, search_params ) if untranslate: iss: Issue for iss in issues: for k, v in untranslate.items(): if iss.raw: if k in iss.raw.get("fields", {}): iss.raw["fields"][v] = iss.raw["fields"][k] return issues # Security levels def security_level(self, id: str) -> SecurityLevel: """Get a security level Resource. Args: id (str): ID of the security level to get """ return self._find_for_resource(SecurityLevel, id) # Server info # non-resource def server_info(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance. Returns: Dict[str, Any] """ retry = 0 j = self._get_json("serverInfo") while not j and retry < 3: self.log.warning( "Bug https://jira.atlassian.com/browse/JRA-59676 trying again..." ) retry += 1 j = self._get_json("serverInfo") return j def myself(self) -> Dict[str, Any]: """Get a dict of server information for this Jira instance.""" return self._get_json("myself") # Status def statuses(self) -> List[Status]: """Get a list of status Resources from the server. Returns: List[Status] """ r_json = self._get_json("status") statuses = [ Status(self._options, self._session, raw_stat_json) for raw_stat_json in r_json ] return statuses def status(self, id: str) -> Status: """Get a status Resource from the server. Args: id (str): ID of the status resource to get Returns: Status """ return self._find_for_resource(Status, id) # Category def statuscategories(self) -> List[StatusCategory]: """Get a list of status category Resources from the server. Returns: List[StatusCategory] """ r_json = self._get_json("statuscategory") statuscategories = [ StatusCategory(self._options, self._session, raw_stat_json) for raw_stat_json in r_json ] return statuscategories def statuscategory(self, id: int) -> StatusCategory: """Get a status category Resource from the server. Args: id (int): ID of the status category resource to get Returns: StatusCategory """ return self._find_for_resource(StatusCategory, id) # Users def user(self, id: str, expand: Optional[Any] = None) -> User: """Get a user Resource from the server. Args: id (str): ID of the user to get expand (Optional[Any]): Extra information to fetch inside each resource Returns: User """ user = User(self._options, self._session) params = {} if expand is not None: params["expand"] = expand user.find(id, params=params) return user def search_assignable_users_for_projects( self, username: str, projectKeys: str, startAt: int = 0, maxResults: int = 50 ) -> ResultList: """Get a list of user Resources that match the search string and can be assigned issues for projects. Args: username (str): A string to match usernames against projectKeys (str): Comma-separated list of project keys to check for issue assignment permissions startAt (int): Index of the first user to return (Default: 0) maxResults (int): Maximum number of users to return. If maxResults evaluates as False, it will try to get all users in batches. (Default: 50) Returns: ResultList """ params = {"username": username, "projectKeys": projectKeys} return self._fetch_pages( User, None, "user/assignable/multiProjectSearch", startAt, maxResults, params, ) def search_assignable_users_for_issues( self, username: str, project: Optional[str] = None, issueKey: Optional[str] = None, expand: Optional[Any] = None, startAt: int = 0, maxResults: int = 50, ): """Get a list of user Resources that match the search string for assigning or creating issues. This method is intended to find users that are eligible to create issues in a project or be assigned to an existing issue. When searching for eligible creators, specify a project. When searching for eligible assignees, specify an issue key. Args: username (str): A string to match usernames against project (Optional[str]): Filter returned users by permission in this project (expected if a result will be used to create an issue) issueKey (Optional[str]): Filter returned users by this issue (expected if a result will be used to edit this issue) expand (Optional[Any]): Extra information to fetch inside each resource startAt (int): Index of the first user to return (Default: 0) maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) Returns: ResultList """ params = {"username": username} if project is not None: params["project"] = project if issueKey is not None: params["issueKey"] = issueKey if expand is not None: params["expand"] = expand return self._fetch_pages( User, None, "user/assignable/search", startAt, maxResults, params ) # non-resource def user_avatars(self, username: str) -> Dict[str, Any]: """Get a dict of avatars for the specified user. Args: username (str): the username to get avatars for """ return self._get_json("user/avatars", params={"username": username}) def create_temp_user_avatar( self, user: str, filename: str, size: int, avatar_img: bytes, contentType: Any = None, auto_confirm: bool = False, ): """Register an image file as a user avatar. The avatar created is temporary and must be confirmed before it can be used. Avatar images are specified by a filename, size, and file object. By default, the client will attempt to autodetect the picture's content type: this mechanism relies on ``libmagic`` and will not work out of the box on Windows systems (see http://filemagic.readthedocs.org/en/latest/guide.html for details on how to install support). The ``contentType`` argument can be used to explicitly set the value (note that Jira will reject any type other than the well-known ones for images, e.g. ``image/jpg``, ``image/png``, etc.) This method returns a dict of properties that can be used to crop a subarea of a larger image for use. This dict should be saved and passed to :py:meth:`confirm_user_avatar` to finish the avatar creation process. If you want to cut out the middleman and confirm the avatar with Jira's default cropping, pass the ``auto_confirm`` argument with a truthy value and :py:meth:`confirm_user_avatar` will be called for you before this method returns. Args: user (str): User to register the avatar for filename (str): name of the avatar file size (int): size of the avatar file avatar_img (bytes): file-like object containing the avatar contentType (Optional[Any]): explicit specification for the avatar image's content-type auto_confirm (bool): whether to automatically confirm the temporary avatar by calling :py:meth:`confirm_user_avatar` with the return value of this method. (Default: False) """ size_from_file = os.path.getsize(filename) if size != size_from_file: size = size_from_file # remove path from filename filename = os.path.split(filename)[1] params = {"username": user, "filename": filename, "size": size} headers: Dict[str, Any] headers = {"X-Atlassian-Token": "no-check"} if contentType is not None: headers["content-type"] = contentType else: # try to detect content-type, this may return None headers["content-type"] = self._get_mime_type(avatar_img) url = self._get_url("user/avatar/temporary") r = self._session.post(url, params=params, headers=headers, data=avatar_img) cropping_properties: Dict[str, Any] = json_loads(r) if auto_confirm: return self.confirm_user_avatar(user, cropping_properties) else: return cropping_properties def confirm_user_avatar(self, user: str, cropping_properties: Dict[str, Any]): """Confirm the temporary avatar image previously uploaded with the specified cropping. After a successful registry with :py:meth:`create_temp_user_avatar`, use this method to confirm the avatar for use. The final avatar can be a subarea of the uploaded image, which is customized with the ``cropping_properties``: the return value of :py:meth:`create_temp_user_avatar` should be used for this argument. Args: user (str): the user to confirm the avatar for cropping_properties (Dict[str,Any]): a dict of cropping properties from :py:meth:`create_temp_user_avatar` """ data = cropping_properties url = self._get_url("user/avatar") r = self._session.post(url, params={"username": user}, data=json.dumps(data)) return json_loads(r) def set_user_avatar(self, username: str, avatar: str) -> Response: """Set a user's avatar. Args: username (str): the user to set the avatar for avatar (str): ID of the avatar to set """ return self._set_avatar( {"username": username}, self._get_url("user/avatar"), avatar ) def delete_user_avatar(self, username: str, avatar: str): """Delete a user's avatar. Args: username (str): the user to delete the avatar from avatar (str): ID of the avatar to remove """ params = {"username": username} url = self._get_url("user/avatar/" + avatar) return self._session.delete(url, params=params) def search_users( self, user: Optional[str] = None, startAt: int = 0, maxResults: int = 50, includeActive: bool = True, includeInactive: bool = False, query: Optional[str] = None, ) -> ResultList[User]: """Get a list of user Resources that match the specified search string. "username" query parameter is deprecated in Jira Cloud; the expected parameter now is "query", which can just be the full email again. But the "user" parameter is kept for backwards compatibility, i.e. Jira Server/Data Center. Args: user (Optional[str]): a string to match usernames, name or email against. startAt (int): index of the first user to return. maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. includeActive (bool): If true, then active users are included in the results. (Default: True) includeInactive (bool): If true, then inactive users are included in the results. (Default: False) query (Optional[str]): Search term. It can just be the email. Returns: ResultList[User] """ if not user and not query: raise ValueError("Either 'user' or 'query' arguments must be specified.") params = { "username": user, "query": query, "includeActive": includeActive, "includeInactive": includeInactive, } return self._fetch_pages(User, None, "user/search", startAt, maxResults, params) def search_allowed_users_for_issue( self, user: str, issueKey: str = None, projectKey: str = None, startAt: int = 0, maxResults: int = 50, ) -> ResultList: """Get a list of user Resources that match a username string and have browse permission for the issue or project. Args: user (str): a string to match usernames against. issueKey (Optional[str]): find users with browse permission for this issue. projectKey (Optional[str]): find users with browse permission for this project. startAt (int): index of the first user to return. (Default: 0) maxResults (int): maximum number of users to return. If maxResults evaluates as False, it will try to get all items in batches. (Default: 50) Returns: ResultList """ params = {"username": user} if issueKey is not None: params["issueKey"] = issueKey if projectKey is not None: params["projectKey"] = projectKey return self._fetch_pages( User, None, "user/viewissue/search", startAt, maxResults, params ) # Versions @translate_resource_args def create_version( self, name: str, project: str, description: str = None, releaseDate: Any = None, startDate: Any = None, archived: bool = False, released: bool = False, ) -> Version: """Create a version in a project and return a Resource for it. Args: name (str): name of the version to create project (str): key of the project to create the version in description (str): a description of the version releaseDate (Optional[Any]): the release date assigned to the version startDate (Optional[Any]): The start date for the version archived (bool): Denotes whether a version should be archived. (Default: False) released (bool): Denotes whether a version is released. (Default: False) Returns: Version """ data = { "name": name, "project": project, "archived": archived, "released": released, } if description is not None: data["description"] = description if releaseDate is not None: data["releaseDate"] = releaseDate if startDate is not None: data["startDate"] = startDate url = self._get_url("version") r = self._session.post(url, data=json.dumps(data)) time.sleep(1) version = Version(self._options, self._session, raw=json_loads(r)) return version def move_version(self, id: str, after: str = None, position: str = None) -> Version: """Move a version within a project's ordered version list and return a new version Resource for it. One, but not both, of ``after`` and ``position`` must be specified. Args: id (str): ID of the version to move after (str): the self attribute of a version to place the specified version after (that is, higher in the list) position (Optional[str]): the absolute position to move this version to: must be one of ``First``, ``Last``, ``Earlier``, or ``Later`` Returns: Version """ data = {} if after is not None: data["after"] = after elif position is not None: data["position"] = position url = self._get_url("version/" + id + "/move") r = self._session.post(url, data=json.dumps(data)) version = Version(self._options, self._session, raw=json_loads(r)) return version def version(self, id: str, expand: Any = None) -> Version: """Get a version Resource. Args: id (str): ID of the version to get expand (Optional[Any]): extra information to fetch inside each resource Returns: Version """ version = Version(self._options, self._session) params = {} if expand is not None: params["expand"] = expand version.find(id, params=params) return version def version_count_related_issues(self, id: str): """Get a dict of the counts of issues fixed and affected by a version. Args: id (str): the version to count issues for """ r_json: Dict[str, Any] = self._get_json("version/" + id + "/relatedIssueCounts") del r_json["self"] # this isn't really an addressable resource return r_json def version_count_unresolved_issues(self, id: str): """Get the number of unresolved issues for a version. Args: id (str): ID of the version to count issues for """ r_json: Dict[str, Any] = self._get_json( "version/" + id + "/unresolvedIssueCount" ) return r_json["issuesUnresolvedCount"] # Session authentication def session(self) -> User: """Get a dict of the current authenticated user's session information. Returns: User """ url = "{server}{auth_url}".format(**self._options) r = self._session.get(url) user = User(self._options, self._session, json_loads(r)) return user def kill_session(self) -> Response: """Destroy the session of the current authenticated user.""" url = self.server_url + "/rest/auth/latest/session" return self._session.delete(url) # Websudo def kill_websudo(self) -> Optional[Response]: """Destroy the user's current WebSudo session. Works only for non-cloud deployments, for others does nothing. Returns: Optional[Response] """ if self.deploymentType != "Cloud": url = self.server_url + "/rest/auth/1/websudo" return self._session.delete(url) return None # Utilities def _create_http_basic_session( self, username: str, password: str, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] = None, ): """Creates a basic http session. Args: username (str): Username for the session password (str): Password for the username timeout (Optional[int]): If set determines the timeout period for the Session. Returns: ResilientSession """ verify = bool(self._options["verify"]) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.auth = (username, password) client_cert: Tuple[str, str] = self._options["client_cert"] # to help mypy self._session.cert = client_cert def _create_oauth_session( self, oauth, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] ): verify = bool(self._options["verify"]) from oauthlib.oauth1 import SIGNATURE_RSA from requests_oauthlib import OAuth1 oauth_instance = OAuth1( oauth["consumer_key"], rsa_key=oauth["key_cert"], signature_method=SIGNATURE_RSA, resource_owner_key=oauth["access_token"], resource_owner_secret=oauth["access_token_secret"], ) self._session = ResilientSession(timeout) self._session.verify = verify self._session.auth = oauth_instance def _create_kerberos_session( self, timeout: Optional[Union[Union[float, int], Tuple[float, float]]], kerberos_options=None, ): verify = bool(self._options["verify"]) if kerberos_options is None: kerberos_options = {} from requests_kerberos import DISABLED, OPTIONAL, HTTPKerberosAuth if kerberos_options.get("mutual_authentication", "OPTIONAL") == "OPTIONAL": mutual_authentication = OPTIONAL elif kerberos_options.get("mutual_authentication") == "DISABLED": mutual_authentication = DISABLED else: raise ValueError( "Unknown value for mutual_authentication: %s" % kerberos_options["mutual_authentication"] ) self._session = ResilientSession(timeout=timeout) self._session.verify = verify self._session.auth = HTTPKerberosAuth( mutual_authentication=mutual_authentication ) @staticmethod def _timestamp(dt: datetime.timedelta = None): t = datetime.datetime.utcnow() if dt is not None: t += dt return calendar.timegm(t.timetuple()) def _create_jwt_session( self, jwt, timeout: Optional[Union[Union[float, int], Tuple[float, float]]] ): try: jwt_auth = JWTAuth(jwt["secret"], alg="HS256") except NameError as e: self.log.error("JWT authentication requires requests_jwt") raise e jwt_auth.set_header_format("JWT %s") jwt_auth.add_field("iat", lambda req: JIRA._timestamp()) jwt_auth.add_field( "exp", lambda req: JIRA._timestamp(datetime.timedelta(minutes=3)) ) jwt_auth.add_field("qsh", QshGenerator(self._options["context_path"])) for f in jwt["payload"].items(): jwt_auth.add_field(f[0], f[1]) self._session = ResilientSession(timeout=timeout) self._session.verify = bool(self._options["verify"]) self._session.auth = jwt_auth def _set_avatar(self, params, url, avatar): data = {"id": avatar} return self._session.put(url, params=params, data=json.dumps(data)) def _get_url(self, path: str, base: str = JIRA_BASE_URL) -> str: """Returns the full url based on Jira base url and the path provided. Using the API version specified during the __init__. Args: path (str): The subpath desired. base (Optional[str]): The base url which should be prepended to the path Returns: str: Fully qualified URL """ options = self._options.copy() options.update({"path": path}) return base.format(**options) def _get_latest_url(self, path: str, base: str = JIRA_BASE_URL) -> str: """Returns the full url based on Jira base url and the path provided. Using the latest API endpoint. Args: path (str): The subpath desired. base (Optional[str]): The base url which should be prepended to the path Returns: str: Fully qualified URL """ options = self._options.copy() options.update({"path": path, "rest_api_version": "latest"}) return base.format(**options) def _get_json( self, path: str, params: Dict[str, Any] = None, base: str = JIRA_BASE_URL ): """Get the json for a given path and params. Args: path (str): The subpath required params (Optional[Dict[str, Any]]): Parameters to filter the json query. base (Optional[str]): The Base Jira URL, defaults to the instance base. Returns: Union[Dict[str, Any], List[Dict[str, str]]] """ url = self._get_url(path, base) r = self._session.get(url, params=params) try: r_json = json_loads(r) except ValueError as e: self.log.error(f"{e}\n{r.text if r else r}") raise e return r_json def _find_for_resource( self, resource_cls: Any, ids: Union[Tuple[str, str], int, str], expand=None ) -> Any: """Uses the find method of the provided Resource class Args: resource_cls (Any): Any instance of :py:class`Resource` ids (Union[Tuple[str, str], int, str]): The arguments to the Resource's ``find()`` expand ([type], optional): The value for the expand property in the Resource's ``find()`` params. Defaults to None. Raises: JIRAError: If the Resource cannot be found Returns: Any: A class of the same type as ``resource_cls`` """ resource = resource_cls(self._options, self._session) params = {} if expand is not None: params["expand"] = expand resource.find(id=ids, params=params) if not resource: raise JIRAError("Unable to find resource %s(%s)", resource_cls, str(ids)) return resource def _try_magic(self): try: import weakref import magic except ImportError: self._magic = None else: try: _magic = magic.Magic(flags=magic.MAGIC_MIME_TYPE) def cleanup(x): _magic.close() self._magic_weakref = weakref.ref(self, cleanup) self._magic = _magic except TypeError: self._magic = None except AttributeError: self._magic = None def _get_mime_type(self, buff: bytes) -> Optional[str]: """Get the MIME type for a given stream of bytes Args: buff (bytes): Stream of bytes Returns: Optional[str]: the MIME type """ if self._magic is not None: return self._magic.id_buffer(buff) else: try: return mimetypes.guess_type("f." + str(imghdr.what(0, buff)))[0] except (IOError, TypeError): self.log.warning( "Couldn't detect content type of avatar image" ". Specify the 'contentType' parameter explicitly." ) return None def rename_user(self, old_user: str, new_user: str): """Rename a Jira user. Args: old_user (str): Old username login new_user (str): New username login """ if self._version > (6, 0, 0): url = self._get_latest_url("user") payload = {"name": new_user} params = {"username": old_user} # raw displayName self.log.debug(f"renaming {self.user(old_user).emailAddress}") r = self._session.put(url, params=params, data=json.dumps(payload)) raise_on_error(r) else: raise NotImplementedError( "Support for renaming users in Jira " "< 6.0.0 has been removed." ) def delete_user(self, username: str) -> bool: """Deletes a Jira User. Args: username (str): Username to delete Returns: bool: Success of user deletion """ url = self._get_latest_url(f"user/?username={username}") r = self._session.delete(url) if 200 <= r.status_code <= 299: return True else: self.log.error(r.status_code) return False def deactivate_user(self, username: str) -> Union[str, int]: """Disable/deactivate the user. Args: username (str): User to be deactivated. Returns: Union[str, int] """ if self.deploymentType == "Cloud": # Disabling users now needs cookie auth in the Cloud - see https://jira.atlassian.com/browse/ID-6230 if "authCookie" not in vars(self): user = self.session() if user.raw is None: raise JIRAError("Can not log in!") self.authCookie = "%s=%s" % ( user.raw["session"]["name"], user.raw["session"]["value"], ) url = ( self._options["server"] + f"/admin/rest/um/1/user/deactivate?username={username}" ) # We can't use our existing session here - this endpoint is fragile and objects to extra headers try: r = requests.post( url, headers={ "Cookie": self.authCookie, "Content-Type": "application/json", }, proxies=self._session.proxies, data={}, ) if r.status_code == 200: return True else: self.log.warning( f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: self.log.error(f"Error Deactivating {username}: {e}") raise JIRAError(f"Error Deactivating {username}: {e}") else: url = self.server_url + "/secure/admin/user/EditUser.jspa" self._options["headers"][ "Content-Type" ] = "application/x-www-form-urlencoded; charset=UTF-8" user = self.user(username) userInfo = { "inline": "true", "decorator": "dialog", "username": user.name, "fullName": user.displayName, "email": user.emailAddress, "editName": user.name, } try: r = self._session.post( url, headers=self._options["headers"], data=userInfo ) if r.status_code == 200: return True else: self.log.warning( f"Got response from deactivating {username}: {r.status_code}" ) return r.status_code except Exception as e: self.log.error(f"Error Deactivating {username}: {e}") raise JIRAError(f"Error Deactivating {username}: {e}") def reindex(self, force: bool = False, background: bool = True) -> bool: """Start jira re-indexing. Returns True if reindexing is in progress or not needed, or False. If you call reindex() without any parameters it will perform a background reindex only if Jira thinks it should do it. Args: force (bool): reindex even if Jira doesn't say this is needed, False by default. background (bool): reindex in background, slower but does not impact the users, defaults to True. Returns: bool: Returns True if reindexing is in progress or not needed, or False. """ # /secure/admin/IndexAdmin.jspa # /secure/admin/jira/IndexProgress.jspa?taskId=1 if background: indexingStrategy = "background" else: indexingStrategy = "stoptheworld" url = self.server_url + "/secure/admin/jira/IndexReIndex.jspa" r = self._session.get(url, headers=self._options["headers"]) if r.status_code == 503: # self.log.warning("Jira returned 503, this could mean that a full reindex is in progress.") return 503 # type: ignore # FIXME: is this a bug? if ( not r.text.find("To perform the re-index now, please go to the") and force is False ): return True if r.text.find("All issues are being re-indexed"): self.log.warning("Jira re-indexing is already running.") return True # still reindexing is considered still a success if r.text.find("To perform the re-index now, please go to the") or force: r = self._session.post( url, headers=self._options["headers"], params={"indexingStrategy": indexingStrategy, "reindex": "Re-Index"}, ) if r.text.find("All issues are being re-indexed") != -1: return True self.log.error("Failed to reindex jira, probably a bug.") return False def backup(self, filename: str = "backup.zip", attachments: bool = False): """Will call jira export to backup as zipped xml. Returning with success does not mean that the backup process finished.""" payload: Any # _session.post is pretty open if self.deploymentType == "Cloud": url = self.server_url + "/rest/backup/1/export/runbackup" payload = json.dumps({"cbAttachments": attachments}) self._options["headers"]["X-Requested-With"] = "XMLHttpRequest" else: url = self.server_url + "/secure/admin/XmlBackup.jspa" payload = {"filename": filename} try: r = self._session.post(url, headers=self._options["headers"], data=payload) if r.status_code == 200: return True else: self.log.warning(f"Got {r.status_code} response from calling backup.") return r.status_code except Exception as e: self.log.error("I see %s", e) def backup_progress(self): """Return status of cloud backup as a dict. Is there a way to get progress for Server version? """ epoch_time = int(time.time() * 1000) if self.deploymentType == "Cloud": url = self.server_url + "/rest/obm/1.0/getprogress?_=%i" % epoch_time else: self.log.warning("This functionality is not available in Server version") return None r = self._session.get(url, headers=self._options["headers"]) # This is weird. I used to get xml, but now I'm getting json try: return json.loads(r.text) except Exception: import defusedxml.ElementTree as etree progress = {} try: root = etree.fromstring(r.text) except etree.ParseError as pe: self.log.warning( "Unable to find backup info. You probably need to initiate a new backup. %s" % pe ) return None for k in root.keys(): progress[k] = root.get(k) return progress def backup_complete(self) -> Optional[bool]: """Return boolean based on 'alternativePercentage' and 'size' returned from backup_progress (cloud only).""" if self.deploymentType != "Cloud": self.log.warning("This functionality is not available in Server version") return None status = self.backup_progress() perc_search = re.search(r"\s([0-9]*)\s", status["alternativePercentage"]) perc_complete = int( perc_search.group(1) # type: ignore # ignore that re.search can return None ) file_size = int(status["size"]) return perc_complete >= 100 and file_size > 0 def backup_download(self, filename: str = None): """Download backup file from WebDAV (cloud only).""" if self.deploymentType != "Cloud": self.log.warning("This functionality is not available in Server version") return None remote_file = self.backup_progress()["fileName"] local_file = filename or remote_file url = self.server_url + "/webdav/backupmanager/" + remote_file try: self.log.debug(f"Writing file to {local_file}") with open(local_file, "wb") as file: try: resp = self._session.get( url, headers=self._options["headers"], stream=True ) except Exception: raise JIRAError() if not resp.ok: self.log.error(f"Something went wrong with download: {resp.text}") raise JIRAError(resp.text) for block in resp.iter_content(1024): file.write(block) except JIRAError as je: self.log.error(f"Unable to access remote backup file: {je}") except IOError as ioe: self.log.error(ioe) return None def current_user(self, field: str = "key") -> str: """Returns the username or emailAddress of the current user. For anonymous users it will return a value that evaluates as False. Returns: str """ if not hasattr(self, "_myself"): url = self._get_url("myself") r = self._session.get(url, headers=self._options["headers"]) r_json: Dict[str, str] = json_loads(r) self._myself = r_json return self._myself[field] def delete_project(self, pid: Union[str, Project]) -> Optional[bool]: """Delete project from Jira. Args: pid (Union[str, Project]): Jira projectID or Project or slug Raises: JIRAError: If project not found or not enough permissions ValueError: If pid parameter is not Project, slug or ProjectID Returns: bool: True if project was deleted """ # allows us to call it with Project objects if isinstance(pid, Project) and hasattr(pid, "id"): pid = str(pid.id) url = self._get_url(f"project/{pid}") r = self._session.delete(url) if r.status_code == 403: raise JIRAError("Not enough permissions to delete project") if r.status_code == 404: raise JIRAError("Project not found in Jira") return r.ok def _gain_sudo_session(self, options, destination): url = self.server_url + "/secure/admin/WebSudoAuthenticate.jspa" if not self._session.auth: self._session.auth = get_netrc_auth(url) payload = { "webSudoPassword": self._session.auth[1], "webSudoDestination": destination, "webSudoIsPost": "true", } payload.update(options) return self._session.post( url, headers=CaseInsensitiveDict( {"content-type": "application/x-www-form-urlencoded"} ), data=payload, ) @lru_cache(maxsize=None) def templates(self) -> Dict: url = self.server_url + "/rest/project-templates/latest/templates" r = self._session.get(url) data: Dict[str, Any] = json_loads(r) templates = {} if "projectTemplatesGroupedByType" in data: for group in data["projectTemplatesGroupedByType"]: for t in group["projectTemplates"]: templates[t["name"]] = t # pprint(templates.keys()) return templates @lru_cache(maxsize=None) def permissionschemes(self): url = self._get_url("permissionscheme") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["permissionSchemes"] @lru_cache(maxsize=None) def issuesecurityschemes(self): url = self._get_url("issuesecurityschemes") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["issueSecuritySchemes"] @lru_cache(maxsize=None) def projectcategories(self): url = self._get_url("projectCategory") r = self._session.get(url) data = json_loads(r) return data @lru_cache(maxsize=None) def avatars(self, entity="project"): url = self._get_url(f"avatar/{entity}/system") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["system"] @lru_cache(maxsize=None) def notificationschemes(self): # TODO(ssbarnea): implement pagination support url = self._get_url("notificationscheme") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def screens(self): # TODO(ssbarnea): implement pagination support url = self._get_url("screens") r = self._session.get(url) data: Dict[str, Any] = json_loads(r) return data["values"] @lru_cache(maxsize=None) def workflowscheme(self): # TODO(ssbarnea): implement pagination support url = self._get_url("workflowschemes") r = self._session.get(url) data = json_loads(r) return data # ['values'] @lru_cache(maxsize=None) def workflows(self): # TODO(ssbarnea): implement pagination support url = self._get_url("workflow") r = self._session.get(url) data = json_loads(r) return data # ['values'] def delete_screen(self, id: str): url = self._get_url(f"screens/{id}") r = self._session.delete(url) data = json_loads(r) self.screens.cache_clear() return data def delete_permissionscheme(self, id: str): url = self._get_url(f"permissionscheme/{id}") r = self._session.delete(url) data = json_loads(r) self.permissionschemes.cache_clear() return data def create_project( self, key: str, name: str = None, assignee: str = None, ptype: str = "software", template_name: str = None, avatarId=None, issueSecurityScheme=None, permissionScheme=None, projectCategory=None, notificationScheme=10000, categoryId=None, url: str = "", ): """Create a project with the specified parameters. Args: key (str): Mandatory. Must match Jira project key requirements, usually only 2-10 uppercase characters. name (Optional[str]): If not specified it will use the key value. assignee (Optional[str]): key of the lead, if not specified it will use current user. ptype (Optional[str]): Determines the type of project should be created. template_name (Optional[str]): is used to create a project based on one of the existing project templates. If `template_name` is not specified, then it should use one of the default values. Returns: Union[bool,int]: Should evaluate to False if it fails otherwise it will be the new project id. """ template_key = None if assignee is None: assignee = self.current_user() if name is None: name = key ps_list: List[Dict[str, Any]] if not permissionScheme: ps_list = self.permissionschemes() for sec in ps_list: if sec["name"] == "Default Permission Scheme": permissionScheme = sec["id"] break if not permissionScheme: permissionScheme = ps_list[0]["id"] if not issueSecurityScheme: ps_list = self.issuesecurityschemes() for sec in ps_list: if sec["name"] == "Default": # no idea which one is default issueSecurityScheme = sec["id"] break if not issueSecurityScheme and ps_list: issueSecurityScheme = ps_list[0]["id"] if not projectCategory: ps_list = self.projectcategories() for sec in ps_list: if sec["name"] == "Default": # no idea which one is default projectCategory = sec["id"] break if not projectCategory and ps_list: projectCategory = ps_list[0]["id"] # <beep> Atlassian for failing to provide an API to get projectTemplateKey values # Possible values are just hardcoded and obviously depending on Jira version. # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?_ga=2.88310429.766596084.1562439833-992274574.1559129176#api-rest-api-3-project-post # https://jira.atlassian.com/browse/JRASERVER-59658 # preference list for picking a default template if not template_name: # https://confluence.atlassian.com/jirakb/creating-projects-via-rest-api-in-jira-963651978.html template_key = ( "com.pyxis.greenhopper.jira:basic-software-development-template" ) # https://developer.atlassian.com/cloud/jira/platform/rest/v2/api-group-projects/#api-rest-api-2-project-get # template_keys = [ # "com.pyxis.greenhopper.jira:gh-simplified-agility-kanban", # "com.pyxis.greenhopper.jira:gh-simplified-agility-scrum", # "com.pyxis.greenhopper.jira:gh-simplified-basic", # "com.pyxis.greenhopper.jira:gh-simplified-kanban-classic", # "com.pyxis.greenhopper.jira:gh-simplified-scrum-classic", # "com.atlassian.servicedesk:simplified-it-service-desk", # "com.atlassian.servicedesk:simplified-internal-service-desk", # "com.atlassian.servicedesk:simplified-external-service-desk", # "com.atlassian.jira-core-project-templates:jira-core-simplified-content-management", # "com.atlassian.jira-core-project-templates:jira-core-simplified-document-approval", # "com.atlassian.jira-core-project-templates:jira-core-simplified-lead-tracking", # "com.atlassian.jira-core-project-templates:jira-core-simplified-process-control", # "com.atlassian.jira-core-project-templates:jira-core-simplified-procurement", # "com.atlassian.jira-core-project-templates:jira-core-simplified-project-management", # "com.atlassian.jira-core-project-templates:jira-core-simplified-recruitment", # "com.atlassian.jira-core-project-templates:jira-core-simplified-task-", # "com.atlassian.jira.jira-incident-management-plugin:im-incident-management", # ] # possible_templates = [ # "Scrum software development", # have Bug # "Agility", # cannot set summary # "Bug tracking", # "JIRA Classic", # "JIRA Default Schemes", # "Basic software development", # "Project management", # "Kanban software development", # "Task management", # "Basic", # does not have Bug # "Content Management", # "Customer service", # "Document Approval", # "IT Service Desk", # "Lead Tracking", # "Process management", # "Procurement", # "Recruitment", # ] # templates = self.templates() # if not template_name: # for k, v in templates.items(): # if v['projectTypeKey'] == type: # template_name = k # template_name = next((t for t in templates if t['projectTypeKey'] == 'x')) # template_key = templates[template_name]["projectTemplateModuleCompleteKey"] # project_type_key = templates[template_name]["projectTypeKey"] # https://confluence.atlassian.com/jirakb/creating-a-project-via-rest-based-on-jira-default-schemes-744325852.html # see https://confluence.atlassian.com/jirakb/creating-projects-via-rest-api-in-jira-963651978.html payload = { "name": name, "key": key, "projectTypeKey": ptype, "projectTemplateKey": template_key, "lead": assignee, # "leadAccountId": assignee, "assigneeType": "PROJECT_LEAD", "description": "", # "avatarId": 13946, "permissionScheme": int(permissionScheme), "notificationScheme": notificationScheme, "url": url, } if issueSecurityScheme: payload["issueSecurityScheme"] = int(issueSecurityScheme) if projectCategory: payload["categoryId"] = int(projectCategory) url = self._get_url("project") r = self._session.post(url, data=json.dumps(payload)) r.raise_for_status() r_json = json_loads(r) return r_json def add_user( self, username: str, email: str, directoryId: int = 1, password: str = None, fullname: str = None, notify: bool = False, active: bool = True, ignore_existing: bool = False, application_keys: Optional[List] = None, ): """Create a new Jira user. Args: username (str): the username of the new user email (str): email address of the new user directoryId (int): The directory ID the new user should be a part of (Default: 1) password (Optional[str]): Optional, the password for the new user fullname (Optional[str]): Optional, the full name of the new user notify (bool): Whether or not to send a notification to the new user. (Default: False) active (bool): Whether or not to make the new user active upon creation. (Default: True) ignore_existing (bool): Whether or not to ignore and existing user. (Default: False) applicationKeys (Optional[list]): Keys of products user should have access to Raises: JIRAError: If username already exists and `ignore_existing` has not been set to `True`. Returns: bool: Whether or not the user creation was successful. """ if not fullname: fullname = username # TODO(ssbarnea): default the directoryID to the first directory in jira instead # of 1 which is the internal one. url = self._get_latest_url("user") # implementation based on # https://docs.atlassian.com/jira/REST/ondemand/#d2e5173 x: Dict[str, Any] = OrderedDict() x["displayName"] = fullname x["emailAddress"] = email x["name"] = username if password: x["password"] = password if notify: x["notification"] = "True" if application_keys is not None: x["applicationKeys"] = application_keys payload = json.dumps(x) try: self._session.post(url, data=payload) except JIRAError as e: if e.response: err = e.response.json()["errors"] if ( "username" in err and err["username"] == "A user with that username already exists." and ignore_existing ): return True raise e return True def add_user_to_group( self, username: str, group: str ) -> Union[bool, Dict[str, Any]]: """Add a user to an existing group. Args: username (str): Username that will be added to specified group. group (str): Group that the user will be added to. Returns: Union[bool,Dict[str,Any]]: json response from Jira server for success or a value that evaluates as False in case of failure. """ url = self._get_latest_url("group/user") x = {"groupname": group} y = {"name": username} payload = json.dumps(y) r: Dict[str, Any] = json_loads(self._session.post(url, params=x, data=payload)) if "name" not in r or r["name"] != group: return False else: return r def remove_user_from_group(self, username: str, groupname: str): """Remove a user from a group. Args: username (str): The user to remove from the group. groupname (str): The group that the user will be removed from. """ url = self._get_latest_url("group/user") x = {"groupname": groupname, "username": username} self._session.delete(url, params=x) return True def role(self) -> List[Dict[str, Any]]: """Return Jira role information. Returns: List[Dict[str,Any]]: List of current user roles """ # https://developer.atlassian.com/cloud/jira/platform/rest/v3/?utm_source=%2Fcloud%2Fjira%2Fplatform%2Frest%2F&utm_medium=302#api-rest-api-3-role-get url = self._get_latest_url("role") r = self._session.get(url) data: List[Dict[str, Any]] = json_loads(r) return data # Experimental # Experimental support for iDalko Grid, expect API to change as it's using private APIs currently # https://support.idalko.com/browse/IGRID-1017 def get_igrid(self, issueid: str, customfield: str, schemeid: str): url = self.server_url + "/rest/idalko-igrid/1.0/datagrid/data" if str(customfield).isdigit(): customfield = f"customfield_{customfield}" params = { "_issueId": issueid, "_fieldId": customfield, "_confSchemeId": schemeid, } r = self._session.get(url, headers=self._options["headers"], params=params) return json_loads(r) # Jira Agile specific methods (GreenHopper) """ Define the functions that interact with GreenHopper. """ @translate_resource_args def boards( self, startAt: int = 0, maxResults: int = 50, type: str = None, name: str = None, projectKeyOrID=None, ) -> ResultList[Board]: """Get a list of board resources. Args: startAt: The starting index of the returned boards. Base index: 0. maxResults: The maximum number of boards to return per page. Default: 50 type: Filters results to boards of the specified type. Valid values: scrum, kanban. name: Filters results to boards that match or partially match the specified name. projectKeyOrID: Filters results to boards that match the specified project key or ID. Returns: ResultList[Board] When old GreenHopper private API is used, paging is not enabled and all parameters are ignored. """ params = {} if type: params["type"] = type if name: params["name"] = name if projectKeyOrID: params["projectKeyOrId"] = projectKeyOrID if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # Old, private API did not support pagination, all records were present in response, # and no parameters were supported. if startAt or maxResults or params: warnings.warn( "Old private GreenHopper API is used, all parameters will be ignored.", Warning, ) r_json: Dict[str, Any] = self._get_json( "rapidviews/list", base=self.AGILE_BASE_URL ) boards = [ Board(self._options, self._session, raw_boards_json) for raw_boards_json in r_json["views"] ] return ResultList(boards, 0, len(boards), len(boards), True) else: return self._fetch_pages( Board, "values", "board", startAt, maxResults, params, base=self.AGILE_BASE_URL, ) @translate_resource_args def sprints( self, board_id: int, extended: bool = False, startAt: int = 0, maxResults: int = 50, state: str = None, ) -> ResultList[Sprint]: """Get a list of sprint GreenHopperResources. Args: board_id (int): the board to get sprints from extended (bool): Used only by old GreenHopper API to fetch additional information like startDate, endDate, completeDate, much slower because it requires an additional requests for each sprint. New Jira Agile API always returns this information without a need for additional requests. startAt (int): the index of the first sprint to return (0 based) maxResults (int): the maximum number of sprints to return state (str): Filters results to sprints in specified states. Valid values: `future`, `active`, `closed`. You can define multiple states separated by commas Returns: ResultList[Sprint]: (content depends on API version, but always contains id, name, state, startDate and endDate) When old GreenHopper private API is used, paging is not enabled, and `startAt`, `maxResults` and `state` parameters are ignored. """ params = {} if state: params["state"] = state if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): r_json: Dict[str, Any] = self._get_json( "sprintquery/%s?includeHistoricSprints=true&includeFutureSprints=true" % board_id, base=self.AGILE_BASE_URL, ) if params: warnings.warn( "Old private GreenHopper API is used, parameters %s will be ignored." % params, Warning, ) if extended: sprints = [ Sprint( self._options, self._session, self.sprint_info("", raw_sprints_json["id"]), ) for raw_sprints_json in r_json["sprints"] ] else: sprints = [ Sprint(self._options, self._session, raw_sprints_json) for raw_sprints_json in r_json["sprints"] ] return ResultList(sprints, 0, len(sprints), len(sprints), True) else: return self._fetch_pages( Sprint, "values", f"board/{board_id}/sprint", startAt, maxResults, params, self.AGILE_BASE_URL, ) def sprints_by_name(self, id, extended=False): sprints = {} for s in self.sprints(id, extended=extended): if s.name not in sprints: sprints[s.name] = s.raw else: raise Exception return sprints def update_sprint(self, id, name=None, startDate=None, endDate=None, state=None): payload = {} if name: payload["name"] = name if startDate: payload["startDate"] = startDate if endDate: payload["endDate"] = endDate if state: if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): raise NotImplementedError( "Public Jira API does not support state update" ) payload["state"] = state url = self._get_url(f"sprint/{id}", base=self.AGILE_BASE_URL) r = self._session.put(url, data=json.dumps(payload)) return json_loads(r) def incompletedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" data: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) return data["contents"]["incompletedIssuesEstimateSum"]["value"] def removed_issues(self, board_id: str, sprint_id: str): """Return the completed issues for the sprint.""" r_json: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) issues = [ Issue(self._options, self._session, raw_issues_json) for raw_issues_json in r_json["contents"]["puntedIssues"] ] return issues def removedIssuesEstimateSum(self, board_id: str, sprint_id: str): """Return the total incompleted points this sprint.""" data: Dict[str, Any] = self._get_json( f"rapid/charts/sprintreport?rapidViewId={board_id}&sprintId={sprint_id}", base=self.AGILE_BASE_URL, ) return data["contents"]["puntedIssuesEstimateSum"]["value"] # TODO(ssbarnea): remove sprint_info() method, sprint() method suit the convention more def sprint_info(self, board_id: str, sprint_id: str) -> Optional[Dict[str, Any]]: """Return the information about a sprint. Args: board_id (str): the board retrieving issues from. Deprecated and ignored. sprint_id (str): the sprint retrieving issues from """ sprint = Sprint(self._options, self._session) sprint.find(sprint_id) return sprint.raw def sprint(self, id: int) -> Sprint: """Return the information about a sprint. Args: sprint_id (int): the sprint retrieving issues from Returns: Sprint """ sprint = Sprint(self._options, self._session) sprint.find(id) return sprint # TODO(ssbarnea): remove this as we do have Board.delete() def delete_board(self, id): """Delete an agile board.""" board = Board(self._options, self._session, raw={"id": id}) board.delete() def create_board( self, name: str, project_ids: Union[str, List[str]], preset: str = "scrum", location_type: str = "user", location_id: Optional[str] = None, ) -> Board: """Create a new board for the ``project_ids``. Args: name (str): name of the board project_ids (str): the projects to create the board in preset (str): What preset to use for this board, options: kanban, scrum, diy. (Default: scrum) location_type (str): the location type. Available in cloud. (Default: user) location_id (Optional[str]): the id of project that the board should be located under. Omit this for a 'user' location_type. Available in cloud. Returns: Board: The newly created board """ if ( self._options["agile_rest_path"] != GreenHopperResource.GREENHOPPER_REST_PATH ): raise NotImplementedError( "Jira Agile Public API does not support this request" ) payload: Dict[str, Any] = {} if isinstance(project_ids, str): ids = [] for p in project_ids.split(","): ids.append(self.project(p).id) project_ids = ",".join(ids) if location_id is not None: location_id = self.project(location_id).id payload["name"] = name if isinstance(project_ids, str): project_ids = project_ids.split(",") # type: ignore # re-use of variable payload["projectIds"] = project_ids payload["preset"] = preset if self.deploymentType == "Cloud": payload["locationType"] = location_type payload["locationId"] = location_id url = self._get_url("rapidview/create/presets", base=self.AGILE_BASE_URL) r = self._session.post(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) return Board(self._options, self._session, raw=raw_issue_json) def create_sprint( self, name: str, board_id: int, startDate: Optional[Any] = None, endDate: Optional[Any] = None, ) -> Sprint: """Create a new sprint for the ``board_id``. Args: name (str): Name of the sprint board_id (int): Which board the sprint should be assigned. startDate (Optional[Any]): Start date for the sprint. endDate (Optional[Any]): End date for the sprint. Returns: Sprint: The newly created Sprint """ payload: Dict[str, Any] = {"name": name} if startDate: payload["startDate"] = startDate if endDate: payload["endDate"] = endDate raw_issue_json: Dict[str, Any] if ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): url = self._get_url(f"sprint/{board_id}", base=self.AGILE_BASE_URL) r = self._session.post(url) raw_issue_json = json_loads(r) """ now r contains something like: { "id": 742, "name": "Sprint 89", "state": "FUTURE", "linkedPagesCount": 0, "startDate": "None", "endDate": "None", "completeDate": "None", "remoteLinks": [] }""" url = self._get_url( f"sprint/{raw_issue_json['id']}", base=self.AGILE_BASE_URL ) r = self._session.put(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) else: url = self._get_url("sprint", base=self.AGILE_BASE_URL) payload["originBoardId"] = board_id r = self._session.post(url, data=json.dumps(payload)) raw_issue_json = json_loads(r) return Sprint(self._options, self._session, raw=raw_issue_json) def add_issues_to_sprint(self, sprint_id: int, issue_keys: List[str]) -> Response: """Add the issues in ``issue_keys`` to the ``sprint_id``. The sprint must be started but not completed. If a sprint was completed, then have to also edit the history of the issue so that it was added to the sprint before it was completed, preferably before it started. A completed sprint's issues also all have a resolution set before the completion date. If a sprint was not started, then have to edit the marker and copy the rank of each issue too. Args: sprint_id (int): the sprint to add issues to issue_keys (List[str]): the issues to add to the sprint Returns: Response """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url(f"sprint/{sprint_id}/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # In old, private API the function does not exist anymore and we need to use # issue.update() to perform this operation # Workaround based on https://answers.atlassian.com/questions/277651/jira-agile-rest-api-example sprint_field_id = self._get_sprint_field_id() data = { "idOrKeys": issue_keys, "customFieldId": sprint_field_id, "sprintId": sprint_id, "addToBacklog": False, } url = self._get_url("sprint/rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for adding issues to sprint for agile_rest_path="%s"' % self._options["agile_rest_path"] ) def add_issues_to_epic( self, epic_id: str, issue_keys: str, ignore_epics: bool = True ) -> Response: """Add the issues in ``issue_keys`` to the ``epic_id``. Args: epic_id (str): The ID for the epic where issues should be added. issue_keys (str): The issues to add to the epic ignore_epics (bool): ignore any issues listed in ``issue_keys`` that are epics. (Default: True) """ if ( self._options["agile_rest_path"] != GreenHopperResource.GREENHOPPER_REST_PATH ): # TODO(ssbarnea): simulate functionality using issue.update()? raise NotImplementedError( "Jira Agile Public API does not support this request" ) data: Dict[str, Any] = {} data["issueKeys"] = issue_keys data["ignoreEpics"] = ignore_epics url = self._get_url(f"epics/{epic_id}/add", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) # TODO(ssbarnea): Both GreenHopper and new Jira Agile API support moving more than one issue. def rank(self, issue: str, next_issue: str) -> Response: """Rank an issue before another using the default Ranking field, the one named 'Rank'. Args: issue (str): issue key of the issue to be ranked before the second one. next_issue (str): issue key of the second issue. """ if not self._rank: for field in self.fields(): if field["name"] == "Rank": if ( field["schema"]["custom"] == "com.pyxis.greenhopper.jira:gh-lexo-rank" ): self._rank = field["schema"]["customId"] break elif ( field["schema"]["custom"] == "com.pyxis.greenhopper.jira:gh-global-rank" ): # Obsolete since Jira v6.3.13.1 self._rank = field["schema"]["customId"] if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url("issue/rank", base=self.AGILE_BASE_URL) payload = { "issues": [issue], "rankBeforeIssue": next_issue, "rankCustomFieldId": self._rank, } try: return self._session.put(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): data = { "issueKeys": [issue], "rankBeforeKey": next_issue, "customFieldId": self._rank, } url = self._get_url("rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for ranking issues for agile_rest_path="%s"' % self._options["agile_rest_path"] ) def move_to_backlog(self, issue_keys: str) -> Response: """Move issues in ``issue_keys`` to the backlog, removing them from all sprints that have not been completed. Args: issue_keys (str): the issues to move to the backlog Raises: JIRAError: If moving issues to backlog fails """ if self._options["agile_rest_path"] == GreenHopperResource.AGILE_BASE_REST_PATH: url = self._get_url("backlog/issue", base=self.AGILE_BASE_URL) payload = {"issues": issue_keys} try: return self._session.post(url, data=json.dumps(payload)) except JIRAError as e: if e.status_code == 404: warnings.warn( "Status code 404 may mean, that too old Jira Agile version is installed." " At least version 6.7.10 is required." ) raise elif ( self._options["agile_rest_path"] == GreenHopperResource.GREENHOPPER_REST_PATH ): # In old, private API the function does not exist anymore and we need to use # issue.update() to perform this operation # Workaround based on https://answers.atlassian.com/questions/277651/jira-agile-rest-api-example sprint_field_id = self._get_sprint_field_id() data = { "idOrKeys": issue_keys, "customFieldId": sprint_field_id, "addToBacklog": True, } url = self._get_url("sprint/rank", base=self.AGILE_BASE_URL) return self._session.put(url, data=json.dumps(data)) else: raise NotImplementedError( 'No API for moving issues to backlog for agile_rest_path="%s"' % self._options["agile_rest_path"] ) class GreenHopper(JIRA): def __init__(self, options=None, basic_auth=None, oauth=None, async_=None): warnings.warn( "GreenHopper() class is deprecated, just use JIRA() instead.", DeprecationWarning, ) JIRA.__init__( self, options=options, basic_auth=basic_auth, oauth=oauth, async_=async_ )
# cmu_112_graphics.py # version 0.9.0 # Pre-release for CMU 15-112-s21 # Require Python 3.6 or later import sys if (sys.version_info[0] != 3) or (sys.version_info[1] < 6): raise Exception("cmu_112_graphics.py requires Python version 3.6 or later.") # Track version and file update timestamp import datetime MAJOR_VERSION = 0 MINOR_VERSION = 9.0 # version 0.9.0 LAST_UPDATED = datetime.date(year=2021, month=4, day=12) # Pending changes: # * Fix Windows-only bug: Position popup dialog box over app window (already works fine on Macs) # * Add documentation # * integrate sounds (probably from pyGame) # * Improved methodIsOverridden to TopLevelApp and ModalApp # * Save to animated gif and/or mp4 (with audio capture?) # Deferred changes: # * replace/augment tkinter canvas with PIL/Pillow imageDraw (perhaps with our own fn names) # Changes in v0.9.0 # * added simpler top-level modes implementation that does not include mode objects # * added ImageDraw and ImageFont to PIL imports # Changes in v0.8.8 # * added __repr__ methods so: # * print(event) works and prints event.key or event.x + event.y # * print(app) works and prints just the user defined app fields # Changes in v0.8.7 # * removed modes (for now) # Changes in v0.8.6 # * s21 # Changes in v0.8.5 # * Support loadImage from Modes # Changes in v0.8.3 + v0.8.4 # * Use default empty Mode if none is provided # * Add KeyRelease event binding # * Drop user32.SetProcessDPIAware (caused window to be really tiny on some Windows machines) # Changes in v0.8.1 + v0.8.2 # * print version number and last-updated date on load # * restrict modifiers to just control key (was confusing with NumLock, etc) # * replace hasModifiers with 'control-' prefix, as in 'control-A' # * replace app._paused with app.paused, etc (use app._ for private variables) # * use improved ImageGrabber import for linux # Changes in v0.8.0 # * suppress more modifier keys (Super_L, Super_R, ...) # * raise exception on event.keysym or event.char + works with key = 'Enter' # * remove tryToInstall # Changes in v0.7.4 # * renamed drawAll back to redrawAll :-) # Changes in v0.7.3 # * Ignore mousepress-drag-release and defer configure events for drags in titlebar # * Extend deferredRedrawAll to 100ms with replace=True and do not draw while deferred # (together these hopefully fix Windows-only bug: file dialog makes window not moveable) # * changed sizeChanged to not take event (use app.width and app.height) # Changes in v0.7.2 # * Singleton App._theRoot instance (hopefully fixes all those pesky Tkinter errors-on-exit) # * Use user32.SetProcessDPIAware to get resolution of screen grabs right on Windows-only (fine on Macs) # * Replaces showGraphics() with runApp(...), which is a veneer for App(...) [more intuitive for pre-OOP part of course] # * Fixes/updates images: # * disallows loading images in redrawAll (raises exception) # * eliminates cache from loadImage # * eliminates app.getTkinterImage, so user now directly calls ImageTk.PhotoImage(image)) # * also create_image allows magic pilImage=image instead of image=ImageTk.PhotoImage(app.image) # Changes in v0.7.1 # * Added keyboard shortcut: # * cmd/ctrl/alt-x: hard exit (uses os._exit() to exit shell without tkinter error messages) # * Fixed bug: shortcut keys stopped working after an MVC violation (or other exception) # * In app.saveSnapshot(), add .png to path if missing # * Added: Print scripts to copy-paste into shell to install missing modules (more automated approaches proved too brittle) # Changes in v0.7 # * Added some image handling (requires PIL (retained) and pyscreenshot (later removed): # * app.loadImage() # loads PIL/Pillow image from file, with file dialog, or from URL (http or https) # * app.scaleImage() # scales a PIL/Pillow image # * app.getTkinterImage() # converts PIL/Pillow image to Tkinter PhotoImage for use in create_image(...) # * app.getSnapshot() # get a snapshot of the canvas as a PIL/Pillow image # * app.saveSnapshot() # get and save a snapshot # * Added app._paused, app.togglePaused(), and paused highlighting (red outline around canvas when paused) # * Added keyboard shortcuts: # * cmd/ctrl/alt-s: save a snapshot # * cmd/ctrl/alt-p: pause/unpause # * cmd/ctrl/alt-q: quit # Changes in v0.6: # * Added fnPrefix option to TopLevelApp (so multiple TopLevelApp's can be in one file) # * Added showGraphics(drawFn) (for graphics-only drawings before we introduce animations) # Changes in v0.5: # * Added: # * app.winx and app.winy (and add winx,winy parameters to app.__init__, and sets these on configure events) # * app.setSize(width, height) # * app.setPosition(x, y) # * app.quit() # * app.showMessage(message) # * app.getUserInput(prompt) # * App.lastUpdated (instance of datetime.date) # * Show popup dialog box on all exceptions (not just for MVC violations) # * Draw (in canvas) "Exception! App Stopped! (See console for details)" for any exception # * Replace callUserMethod() with more-general @_safeMethod decorator (also handles exceptions outside user methods) # * Only include lines from user's code (and not our framework nor tkinter) in stack traces # * Require Python version (3.6 or greater) # Changes in v0.4: # * Added __setattr__ to enforce Type 1A MVC Violations (setting app.x in redrawAll) with better stack trace # * Added app._deferredRedrawAll() (avoids resizing drawing/crashing bug on some platforms) # * Added deferredMethodCall() and app._afterIdMap to generalize afterId handling # * Use (_ is None) instead of (_ == None) # Changes in v0.3: # * Fixed "event not defined" bug in sizeChanged handlers. # * draw "MVC Violation" on Type 2 violation (calling draw methods outside redrawAll) # Changes in v0.2: # * Handles another MVC violation (now detects drawing on canvas outside of redrawAll) # * App stops running when an exception occurs (in user code) (stops cascading errors) # Changes in v0.1: # * OOPy + supports inheritance + supports multiple apps in one file + etc # * uses import instead of copy-paste-edit starter code + no "do not edit code below here!" # * no longer uses Struct (which was non-Pythonic and a confusing way to sort-of use OOP) # * Includes an early version of MVC violation handling (detects model changes in redrawAll) # * added events: # * appStarted (no init-vs-__init__ confusion) # * appStopped (for cleanup) # * keyReleased (well, sort of works) + mouseReleased # * mouseMoved + mouseDragged # * sizeChanged (when resizing window) # * improved key names (just use event.key instead of event.char and/or event.keysym + use names for 'Enter', 'Escape', ...) # * improved function names (renamed redrawAll to drawAll) # * improved (if not perfect) exiting without that irksome Tkinter error/bug # * app has a title in the titlebar (also shows window's dimensions) # * supports Modes and ModalApp (see ModalApp and Mode, and also see TestModalApp example) # * supports TopLevelApp (using top-level functions instead of subclasses and methods) # * supports version checking with App.majorVersion, App.minorVersion, and App.version # * logs drawing calls to support autograding views (still must write that autograder, but this is a very helpful first step) from tkinter import * from tkinter import messagebox, simpledialog, filedialog import inspect, traceback import sys, os from io import BytesIO def failedImport(importName, installName=None): installName = installName or importName print("**********************************************************") print( f"** Cannot import {importName} -- it seems you need to install {installName}" ) print( f"** This may result in limited functionality or even a runtime error." ) print("**********************************************************") print() try: from PIL import Image, ImageTk, ImageDraw, ImageFont except ModuleNotFoundError: failedImport("PIL", "pillow") if sys.platform.startswith("linux"): try: import pyscreenshot as ImageGrabber except ModuleNotFoundError: failedImport("pyscreenshot") else: try: from PIL import ImageGrab as ImageGrabber except ModuleNotFoundError: pass # Our PIL warning is already printed above try: import requests except ModuleNotFoundError: failedImport("requests") def getHash(obj): # This is used to detect MVC violations in redrawAll # @TODO: Make this more robust and efficient try: return getHash(obj.__dict__) except: if isinstance(obj, list): return getHash(tuple([getHash(v) for v in obj])) elif isinstance(obj, set): return getHash(sorted(obj)) elif isinstance(obj, dict): return getHash(tuple([obj[key] for key in sorted(obj)])) else: try: return hash(obj) except: return getHash(repr(obj)) class WrappedCanvas(Canvas): # Enforces MVC: no drawing outside calls to redrawAll # Logs draw calls (for autograder) in canvas.loggedDrawingCalls def __init__(wrappedCanvas, app): wrappedCanvas.loggedDrawingCalls = [] wrappedCanvas.logDrawingCalls = True wrappedCanvas.inRedrawAll = False wrappedCanvas.app = app super().__init__(app._root, width=app.width, height=app.height) def log(self, methodName, args, kwargs): if not self.inRedrawAll: self.app._mvcViolation( "you may not use the canvas (the view) outside of redrawAll" ) if self.logDrawingCalls: self.loggedDrawingCalls.append((methodName, args, kwargs)) def create_arc(self, *args, **kwargs): self.log("create_arc", args, kwargs) return super().create_arc(*args, **kwargs) def create_bitmap(self, *args, **kwargs): self.log("create_bitmap", args, kwargs) return super().create_bitmap(*args, **kwargs) def create_line(self, *args, **kwargs): self.log("create_line", args, kwargs) return super().create_line(*args, **kwargs) def create_oval(self, *args, **kwargs): self.log("create_oval", args, kwargs) return super().create_oval(*args, **kwargs) def create_polygon(self, *args, **kwargs): self.log("create_polygon", args, kwargs) return super().create_polygon(*args, **kwargs) def create_rectangle(self, *args, **kwargs): self.log("create_rectangle", args, kwargs) return super().create_rectangle(*args, **kwargs) def create_text(self, *args, **kwargs): self.log("create_text", args, kwargs) return super().create_text(*args, **kwargs) def create_window(self, *args, **kwargs): self.log("create_window", args, kwargs) return super().create_window(*args, **kwargs) def create_image(self, *args, **kwargs): self.log("create_image", args, kwargs) usesImage = "image" in kwargs usesPilImage = "pilImage" in kwargs if (not usesImage) and (not usesPilImage): raise Exception("create_image requires an image to draw") elif usesImage and usesPilImage: raise Exception( "create_image cannot use both an image and a pilImage" ) elif usesPilImage: pilImage = kwargs["pilImage"] del kwargs["pilImage"] if not isinstance(pilImage, Image.Image): raise Exception( "create_image: pilImage value is not an instance of a PIL/Pillow image" ) image = ImageTk.PhotoImage(pilImage) else: image = kwargs["image"] if isinstance(image, Image.Image): raise Exception( "create_image: image must not be an instance of a PIL/Pillow image\n" + "You perhaps meant to convert from PIL to Tkinter, like so:\n" + " canvas.create_image(x, y, image=ImageTk.PhotoImage(image))" ) kwargs["image"] = image return super().create_image(*args, **kwargs) class App(object): majorVersion = MAJOR_VERSION minorVersion = MINOR_VERSION version = f"{majorVersion}.{minorVersion}" lastUpdated = LAST_UPDATED _theRoot = None # singleton Tkinter root object #################################### # User Methods: #################################### def redrawAll(app, canvas): pass # draw (view) the model in the canvas def appStarted(app): pass # initialize the model (app.xyz) def appStopped(app): pass # cleanup after app is done running def keyPressed(app, event): pass # use event.key def keyReleased(app, event): pass # use event.key def mousePressed(app, event): pass # use event.x and event.y def mouseReleased(app, event): pass # use event.x and event.y def mouseMoved(app, event): pass # use event.x and event.y def mouseDragged(app, event): pass # use event.x and event.y def timerFired(app): pass # respond to timer events def sizeChanged(app): pass # respond to window size changes #################################### # Implementation: #################################### def __init__( app, width=300, height=300, x=0, y=0, title=None, autorun=True, mvcCheck=True, logDrawingCalls=True, ): app.winx, app.winy, app.width, app.height = x, y, width, height app.timerDelay = 100 # milliseconds app.mouseMovedDelay = 50 # ditto app._title = title app._mvcCheck = mvcCheck app._logDrawingCalls = logDrawingCalls app._running = app._paused = False app._mousePressedOutsideWindow = False if autorun: app.run() def __repr__(app): keys = set(app.__dict__.keys()) keyValues = [] for key in sorted(keys - app._ignoredFields): keyValues.append(f"{key}={app.__dict__[key]}") return f'App({', '.join(keyValues)})' def setSize(app, width, height): app._root.geometry(f"{width}x{height}") def setPosition(app, x, y): app._root.geometry(f"+{x}+{y}") def showMessage(app, message): messagebox.showinfo("showMessage", message, parent=app._root) def getUserInput(app, prompt): return simpledialog.askstring("getUserInput", prompt) def loadImage(app, path=None): if app._canvas.inRedrawAll: raise Exception("Cannot call loadImage in redrawAll") if path is None: path = filedialog.askopenfilename( initialdir=os.getcwd(), title="Select file: ", filetypes=( ("Image files", "*.png *.gif *.jpg"), ("all files", "*.*"), ), ) if not path: return None if path.startswith("http"): response = requests.request("GET", path) # path is a URL! image = Image.open(BytesIO(response.content)) else: image = Image.open(path) return image def scaleImage(app, image, scale, antialias=False): # antialiasing is higher-quality but slower resample = Image.ANTIALIAS if antialias else Image.NEAREST return image.resize( (round(image.width * scale), round(image.height * scale)), resample=resample, ) def getSnapshot(app): app._showRootWindow() x0 = app._root.winfo_rootx() + app._canvas.winfo_x() y0 = app._root.winfo_rooty() + app._canvas.winfo_y() result = ImageGrabber.grab((x0, y0, x0 + app.width, y0 + app.height)) return result def saveSnapshot(app): path = filedialog.asksaveasfilename( initialdir=os.getcwd(), title="Select file: ", filetypes=(("png files", "*.png"), ("all files", "*.*")), ) if path: # defer call to let filedialog close (and not grab those pixels) if not path.endswith(".png"): path += ".png" app._deferredMethodCall( afterId="saveSnapshot", afterDelay=0, afterFn=lambda: app.getSnapshot().save(path), ) def _togglePaused(app): app._paused = not app._paused def quit(app): app._running = False app._root.quit() # break out of root.mainloop() without closing window! def __setattr__(app, attr, val): d = app.__dict__ d[attr] = val canvas = d.get("_canvas", None) if ( d.get("running", False) and d.get("mvcCheck", False) and (canvas is not None) and canvas.inRedrawAll ): app._mvcViolation( f"you may not change app.{attr} in the model while in redrawAll (the view)" ) def _printUserTraceback(app, exception, tb): stack = traceback.extract_tb(tb) lines = traceback.format_list(stack) inRedrawAllWrapper = False printLines = [] for line in lines: if ( ('"cmu_112_graphics.py"' not in line) and ("/cmu_112_graphics.py" not in line) and ("\\cmu_112_graphics.py" not in line) and ("/tkinter/" not in line) and ("\\tkinter\\" not in line) ): printLines.append(line) if "redrawAllWrapper" in line: inRedrawAllWrapper = True if len(printLines) == 0: # No user code in trace, so we have to use all the code (bummer), # but not if we are in a redrawAllWrapper... if inRedrawAllWrapper: printLines = [ " No traceback available. Error occurred in redrawAll.\n" ] else: printLines = lines print("Traceback (most recent call last):") for line in printLines: print(line, end="") print(f"Exception: {exception}") def _safeMethod(appMethod): def m(*args, **kwargs): app = args[0] try: return appMethod(*args, **kwargs) except Exception as e: app._running = False app._printUserTraceback(e, sys.exc_info()[2]) if "_canvas" in app.__dict__: app._canvas.inRedrawAll = ( True # not really, but stops recursive MVC Violations! ) app._canvas.create_rectangle( 0, 0, app.width, app.height, fill=None, width=10, outline="red", ) app._canvas.create_rectangle( 10, app.height - 50, app.width - 10, app.height - 10, fill="white", outline="red", width=4, ) app._canvas.create_text( app.width / 2, app.height - 40, text=f"Exception! App Stopped!", fill="red", font="Arial 12 bold", ) app._canvas.create_text( app.width / 2, app.height - 20, text=f"See console for details", fill="red", font="Arial 12 bold", ) app._canvas.update() app.showMessage( f"Exception: {e}\nClick ok then see console for details." ) return m def _methodIsOverridden(app, methodName): return getattr(type(app), methodName) is not getattr(App, methodName) def _mvcViolation(app, errMsg): app._running = False raise Exception("MVC Violation: " + errMsg) @_safeMethod def _redrawAllWrapper(app): if not app._running: return if "deferredRedrawAll" in app._afterIdMap: return # wait for pending call app._canvas.inRedrawAll = True app._canvas.delete(ALL) width, outline = (10, "red") if app._paused else (0, "white") app._canvas.create_rectangle( 0, 0, app.width, app.height, fill="white", width=width, outline=outline, ) app._canvas.loggedDrawingCalls = [] app._canvas.logDrawingCalls = app._logDrawingCalls hash1 = getHash(app) if app._mvcCheck else None try: app.redrawAll(app._canvas) hash2 = getHash(app) if app._mvcCheck else None if hash1 != hash2: app._mvcViolation( "you may not change the app state (the model) in redrawAll (the view)" ) finally: app._canvas.inRedrawAll = False app._canvas.update() def _deferredMethodCall(app, afterId, afterDelay, afterFn, replace=False): def afterFnWrapper(): app._afterIdMap.pop(afterId, None) afterFn() id = app._afterIdMap.get(afterId, None) if (id is None) or replace: if id: app._root.after_cancel(id) app._afterIdMap[afterId] = app._root.after( afterDelay, afterFnWrapper ) def _deferredRedrawAll(app): app._deferredMethodCall( afterId="deferredRedrawAll", afterDelay=100, afterFn=app._redrawAllWrapper, replace=True, ) @_safeMethod def _appStartedWrapper(app): app.appStarted() app._redrawAllWrapper() _keyNameMap = { "\t": "Tab", "\n": "Enter", "\r": "Enter", "\b": "Backspace", chr(127): "Delete", chr(27): "Escape", " ": "Space", } @staticmethod def _useEventKey(attr): raise Exception(f"Use event.key instead of event.{attr}") @staticmethod def _getEventKeyInfo(event, keysym, char): key = c = char hasControlKey = event.state & 0x4 != 0 if (c in [None, ""]) or (len(c) > 1) or (ord(c) > 255): key = keysym if ( key.endswith("_L") or key.endswith("_R") or key.endswith("_Lock") ): key = "Modifier_Key" elif c in App._keyNameMap: key = App._keyNameMap[c] elif (len(c) == 1) and (1 <= ord(c) <= 26): key = chr(ord("a") - 1 + ord(c)) hasControlKey = True if hasControlKey and (len(key) == 1): # don't add control- prefix to Enter, Tab, Escape, ... key = "control-" + key return key class EventWrapper(Event): def __init__(self, event): for key in event.__dict__: if not key.startswith("__"): self.__dict__[key] = event.__dict__[key] class MouseEventWrapper(EventWrapper): def __repr__(self): return f"Event(x={self.x}, y={self.y})" class KeyEventWrapper(EventWrapper): def __init__(self, event): keysym, char = event.keysym, event.char del event.keysym del event.char super().__init__(event) self.key = App._getEventKeyInfo(event, keysym, char) def __repr__(self): return f"Event(key={repr(self.key)})" keysym = property( lambda *args: App._useEventKey("keysym"), lambda *args: App._useEventKey("keysym"), ) char = property( lambda *args: App._useEventKey("char"), lambda *args: App._useEventKey("char"), ) @_safeMethod def _keyPressedWrapper(app, event): event = App.KeyEventWrapper(event) if event.key == "control-s": app.saveSnapshot() elif event.key == "control-p": app._togglePaused() app._redrawAllWrapper() elif event.key == "control-q": app.quit() elif event.key == "control-x": os._exit(0) # hard exit avoids tkinter error messages elif ( app._running and (not app._paused) and app._methodIsOverridden("keyPressed") and (not event.key == "Modifier_Key") ): app.keyPressed(event) app._redrawAllWrapper() @_safeMethod def _keyReleasedWrapper(app, event): if ( (not app._running) or app._paused or (not app._methodIsOverridden("keyReleased")) ): return event = App.KeyEventWrapper(event) if not event.key == "Modifier_Key": app.keyReleased(event) app._redrawAllWrapper() @_safeMethod def _mousePressedWrapper(app, event): if (not app._running) or app._paused: return if ( (event.x < 0) or (event.x > app.width) or (event.y < 0) or (event.y > app.height) ): app._mousePressedOutsideWindow = True else: app._mousePressedOutsideWindow = False app._mouseIsPressed = True app._lastMousePosn = (event.x, event.y) if app._methodIsOverridden("mousePressed"): event = App.MouseEventWrapper(event) app.mousePressed(event) app._redrawAllWrapper() @_safeMethod def _mouseReleasedWrapper(app, event): if (not app._running) or app._paused: return app._mouseIsPressed = False if app._mousePressedOutsideWindow: app._mousePressedOutsideWindow = False app._sizeChangedWrapper() else: app._lastMousePosn = (event.x, event.y) if app._methodIsOverridden("mouseReleased"): event = App.MouseEventWrapper(event) app.mouseReleased(event) app._redrawAllWrapper() @_safeMethod def _timerFiredWrapper(app): if (not app._running) or (not app._methodIsOverridden("timerFired")): return if not app._paused: app.timerFired() app._redrawAllWrapper() app._deferredMethodCall( afterId="_timerFiredWrapper", afterDelay=app.timerDelay, afterFn=app._timerFiredWrapper, ) @_safeMethod def _sizeChangedWrapper(app, event=None): if not app._running: return if event and ((event.width < 2) or (event.height < 2)): return if app._mousePressedOutsideWindow: return app.width, app.height, app.winx, app.winy = [ int(v) for v in app._root.winfo_geometry().replace("x", "+").split("+") ] if app._lastWindowDims is None: app._lastWindowDims = (app.width, app.height, app.winx, app.winy) else: newDims = (app.width, app.height, app.winx, app.winy) if app._lastWindowDims != newDims: app._lastWindowDims = newDims app.updateTitle() app.sizeChanged() app._deferredRedrawAll() # avoid resize crashing on some platforms @_safeMethod def _mouseMotionWrapper(app): if not app._running: return mouseMovedExists = app._methodIsOverridden("mouseMoved") mouseDraggedExists = app._methodIsOverridden("mouseDragged") if ( (not app._paused) and (not app._mousePressedOutsideWindow) and ( ((not app._mouseIsPressed) and mouseMovedExists) or (app._mouseIsPressed and mouseDraggedExists) ) ): class MouseMotionEvent(object): pass event = MouseMotionEvent() root = app._root event.x = root.winfo_pointerx() - root.winfo_rootx() event.y = root.winfo_pointery() - root.winfo_rooty() event = App.MouseEventWrapper(event) if ( (app._lastMousePosn != (event.x, event.y)) and (event.x >= 0) and (event.x <= app.width) and (event.y >= 0) and (event.y <= app.height) ): if app._mouseIsPressed: app.mouseDragged(event) else: app.mouseMoved(event) app._lastMousePosn = (event.x, event.y) app._redrawAllWrapper() if mouseMovedExists or mouseDraggedExists: app._deferredMethodCall( afterId="mouseMotionWrapper", afterDelay=app.mouseMovedDelay, afterFn=app._mouseMotionWrapper, ) def updateTitle(app): app._title = app._title or type(app).__name__ app._root.title(f"{app._title} ({app.width} x {app.height})") def getQuitMessage(app): appLabel = type(app).__name__ if app._title != appLabel: if app._title.startswith(appLabel): appLabel = app._title else: appLabel += f" '{app._title}'" return f"*** Closing {appLabel}. Bye! ***\n" def _showRootWindow(app): root = app._root root.update() root.deiconify() root.lift() root.focus() def _hideRootWindow(app): root = app._root root.withdraw() @_safeMethod def run(app): app._mouseIsPressed = False app._lastMousePosn = (-1, -1) app._lastWindowDims = None # set in sizeChangedWrapper app._afterIdMap = dict() # create the singleton root window if App._theRoot is None: App._theRoot = Tk() App._theRoot.createcommand( "exit", lambda: "" ) # when user enters cmd-q, ignore here (handled in keyPressed) App._theRoot.protocol( "WM_DELETE_WINDOW", lambda: App._theRoot.app.quit() ) # when user presses 'x' in title bar App._theRoot.bind( "<Button-1>", lambda event: App._theRoot.app._mousePressedWrapper(event), ) App._theRoot.bind( "<B1-ButtonRelease>", lambda event: App._theRoot.app._mouseReleasedWrapper(event), ) App._theRoot.bind( "<KeyPress>", lambda event: App._theRoot.app._keyPressedWrapper(event), ) App._theRoot.bind( "<KeyRelease>", lambda event: App._theRoot.app._keyReleasedWrapper(event), ) App._theRoot.bind( "<Configure>", lambda event: App._theRoot.app._sizeChangedWrapper(event), ) else: App._theRoot.canvas.destroy() app._root = root = App._theRoot # singleton root! root.app = app root.geometry(f"{app.width}x{app.height}+{app.winx}+{app.winy}") app.updateTitle() # create the canvas root.canvas = app._canvas = WrappedCanvas(app) app._canvas.pack(fill=BOTH, expand=YES) # initialize, start the timer, and launch the app app._running = True app._paused = False app._ignoredFields = set(app.__dict__.keys()) | {"_ignoredFields"} app._appStartedWrapper() app._timerFiredWrapper() app._mouseMotionWrapper() app._showRootWindow() root.mainloop() app._hideRootWindow() app._running = False for afterId in app._afterIdMap: app._root.after_cancel(app._afterIdMap[afterId]) app._afterIdMap.clear() # for safety app.appStopped() print(app.getQuitMessage()) #################################### # TopLevelApp: # (with top-level functions not subclassses and methods) #################################### class TopLevelApp(App): _apps = dict() # maps fnPrefix to app def __init__(app, fnPrefix="", **kwargs): if fnPrefix in TopLevelApp._apps: print(f"Quitting previous version of {fnPrefix} TopLevelApp.") TopLevelApp._apps[fnPrefix].quit() if (fnPrefix != "") and ("title" not in kwargs): kwargs["title"] = f"TopLevelApp '{fnPrefix}'" TopLevelApp._apps[fnPrefix] = app app._fnPrefix = fnPrefix app._callersGlobals = inspect.stack()[1][0].f_globals app.mode = None super().__init__(**kwargs) def _callFn(app, fn, *args): if (app.mode is not None) and (app.mode != ""): fn = app.mode + "_" + fn fn = app._fnPrefix + fn if fn in app._callersGlobals: app._callersGlobals[fn](*args) def redrawAll(app, canvas): app._callFn("redrawAll", app, canvas) def appStarted(app): app._callFn("appStarted", app) def appStopped(app): app._callFn("appStopped", app) def keyPressed(app, event): app._callFn("keyPressed", app, event) def keyReleased(app, event): app._callFn("keyReleased", app, event) def mousePressed(app, event): app._callFn("mousePressed", app, event) def mouseReleased(app, event): app._callFn("mouseReleased", app, event) def mouseMoved(app, event): app._callFn("mouseMoved", app, event) def mouseDragged(app, event): app._callFn("mouseDragged", app, event) def timerFired(app): app._callFn("timerFired", app) def sizeChanged(app): app._callFn("sizeChanged", app) #################################### # ModalApp + Mode: #################################### """ # For now, only include modes in top-level apps (see above). class Mode(object): def __repr__(self): return f'<{self.__class__.__name__} object>' class ModalApp(App): def __init__(app, *args, **kwargs): app._mode = None super().__init__(*args, **kwargs) def setMode(app, mode): if (not isinstance(mode, Mode)): raise Exception('mode must be an instance of Mode') app._mode = mode def _callFn(app, fn, *args): if (app._mode == None): raise Exception('ModalApp must have a mode (use app.setMode())') mode = app._mode # method = getattr(mode, fn, None) method = mode.__class__.__dict__.get(fn) # get method as fn if (method != None): method(*args) def redrawAll(app, canvas): app._callFn('redrawAll', app, canvas) #def appStarted(app): app._callFn('appStarted', app) #def appStopped(app): app._callFn('appStopped', app) def keyPressed(app, event): app._callFn('keyPressed', app, event) def keyReleased(app, event): app._callFn('keyReleased', app, event) def mousePressed(app, event): app._callFn('mousePressed', app, event) def mouseReleased(app, event): app._callFn('mouseReleased', app, event) def mouseMoved(app, event): app._callFn('mouseMoved', app, event) def mouseDragged(app, event): app._callFn('mouseDragged', app, event) def timerFired(app): app._callFn('timerFired', app) def sizeChanged(app): app._callFn('sizeChanged', app) """ #################################### # runApp() #################################### """ def showGraphics(drawFn, **kwargs): class GraphicsApp(App): def __init__(app, **kwargs): if ('title' not in kwargs): kwargs['title'] = drawFn.__name__ super().__init__(**kwargs) def redrawAll(app, canvas): drawFn(app, canvas) app = GraphicsApp(**kwargs) """ runApp = TopLevelApp print( f"Loaded cmu_112_graphics version {App.version} (last updated {App.lastUpdated})" ) if __name__ == "__main__": try: import cmu_112_graphics_tests except: pass
# cmu_112_graphics.py # version 0.9.0 # Pre-release for CMU 15-112-s21 # Require Python 3.6 or later import sys if (sys.version_info[0] != 3) or (sys.version_info[1] < 6): raise Exception("cmu_112_graphics.py requires Python version 3.6 or later.") # Track version and file update timestamp import datetime MAJOR_VERSION = 0 MINOR_VERSION = 9.0 # version 0.9.0 LAST_UPDATED = datetime.date(year=2021, month=4, day=12) # Pending changes: # * Fix Windows-only bug: Position popup dialog box over app window (already works fine on Macs) # * Add documentation # * integrate sounds (probably from pyGame) # * Improved methodIsOverridden to TopLevelApp and ModalApp # * Save to animated gif and/or mp4 (with audio capture?) # Deferred changes: # * replace/augment tkinter canvas with PIL/Pillow imageDraw (perhaps with our own fn names) # Changes in v0.9.0 # * added simpler top-level modes implementation that does not include mode objects # * added ImageDraw and ImageFont to PIL imports # Changes in v0.8.8 # * added __repr__ methods so: # * print(event) works and prints event.key or event.x + event.y # * print(app) works and prints just the user defined app fields # Changes in v0.8.7 # * removed modes (for now) # Changes in v0.8.6 # * s21 # Changes in v0.8.5 # * Support loadImage from Modes # Changes in v0.8.3 + v0.8.4 # * Use default empty Mode if none is provided # * Add KeyRelease event binding # * Drop user32.SetProcessDPIAware (caused window to be really tiny on some Windows machines) # Changes in v0.8.1 + v0.8.2 # * print version number and last-updated date on load # * restrict modifiers to just control key (was confusing with NumLock, etc) # * replace hasModifiers with 'control-' prefix, as in 'control-A' # * replace app._paused with app.paused, etc (use app._ for private variables) # * use improved ImageGrabber import for linux # Changes in v0.8.0 # * suppress more modifier keys (Super_L, Super_R, ...) # * raise exception on event.keysym or event.char + works with key = 'Enter' # * remove tryToInstall # Changes in v0.7.4 # * renamed drawAll back to redrawAll :-) # Changes in v0.7.3 # * Ignore mousepress-drag-release and defer configure events for drags in titlebar # * Extend deferredRedrawAll to 100ms with replace=True and do not draw while deferred # (together these hopefully fix Windows-only bug: file dialog makes window not moveable) # * changed sizeChanged to not take event (use app.width and app.height) # Changes in v0.7.2 # * Singleton App._theRoot instance (hopefully fixes all those pesky Tkinter errors-on-exit) # * Use user32.SetProcessDPIAware to get resolution of screen grabs right on Windows-only (fine on Macs) # * Replaces showGraphics() with runApp(...), which is a veneer for App(...) [more intuitive for pre-OOP part of course] # * Fixes/updates images: # * disallows loading images in redrawAll (raises exception) # * eliminates cache from loadImage # * eliminates app.getTkinterImage, so user now directly calls ImageTk.PhotoImage(image)) # * also create_image allows magic pilImage=image instead of image=ImageTk.PhotoImage(app.image) # Changes in v0.7.1 # * Added keyboard shortcut: # * cmd/ctrl/alt-x: hard exit (uses os._exit() to exit shell without tkinter error messages) # * Fixed bug: shortcut keys stopped working after an MVC violation (or other exception) # * In app.saveSnapshot(), add .png to path if missing # * Added: Print scripts to copy-paste into shell to install missing modules (more automated approaches proved too brittle) # Changes in v0.7 # * Added some image handling (requires PIL (retained) and pyscreenshot (later removed): # * app.loadImage() # loads PIL/Pillow image from file, with file dialog, or from URL (http or https) # * app.scaleImage() # scales a PIL/Pillow image # * app.getTkinterImage() # converts PIL/Pillow image to Tkinter PhotoImage for use in create_image(...) # * app.getSnapshot() # get a snapshot of the canvas as a PIL/Pillow image # * app.saveSnapshot() # get and save a snapshot # * Added app._paused, app.togglePaused(), and paused highlighting (red outline around canvas when paused) # * Added keyboard shortcuts: # * cmd/ctrl/alt-s: save a snapshot # * cmd/ctrl/alt-p: pause/unpause # * cmd/ctrl/alt-q: quit # Changes in v0.6: # * Added fnPrefix option to TopLevelApp (so multiple TopLevelApp's can be in one file) # * Added showGraphics(drawFn) (for graphics-only drawings before we introduce animations) # Changes in v0.5: # * Added: # * app.winx and app.winy (and add winx,winy parameters to app.__init__, and sets these on configure events) # * app.setSize(width, height) # * app.setPosition(x, y) # * app.quit() # * app.showMessage(message) # * app.getUserInput(prompt) # * App.lastUpdated (instance of datetime.date) # * Show popup dialog box on all exceptions (not just for MVC violations) # * Draw (in canvas) "Exception! App Stopped! (See console for details)" for any exception # * Replace callUserMethod() with more-general @_safeMethod decorator (also handles exceptions outside user methods) # * Only include lines from user's code (and not our framework nor tkinter) in stack traces # * Require Python version (3.6 or greater) # Changes in v0.4: # * Added __setattr__ to enforce Type 1A MVC Violations (setting app.x in redrawAll) with better stack trace # * Added app._deferredRedrawAll() (avoids resizing drawing/crashing bug on some platforms) # * Added deferredMethodCall() and app._afterIdMap to generalize afterId handling # * Use (_ is None) instead of (_ == None) # Changes in v0.3: # * Fixed "event not defined" bug in sizeChanged handlers. # * draw "MVC Violation" on Type 2 violation (calling draw methods outside redrawAll) # Changes in v0.2: # * Handles another MVC violation (now detects drawing on canvas outside of redrawAll) # * App stops running when an exception occurs (in user code) (stops cascading errors) # Changes in v0.1: # * OOPy + supports inheritance + supports multiple apps in one file + etc # * uses import instead of copy-paste-edit starter code + no "do not edit code below here!" # * no longer uses Struct (which was non-Pythonic and a confusing way to sort-of use OOP) # * Includes an early version of MVC violation handling (detects model changes in redrawAll) # * added events: # * appStarted (no init-vs-__init__ confusion) # * appStopped (for cleanup) # * keyReleased (well, sort of works) + mouseReleased # * mouseMoved + mouseDragged # * sizeChanged (when resizing window) # * improved key names (just use event.key instead of event.char and/or event.keysym + use names for 'Enter', 'Escape', ...) # * improved function names (renamed redrawAll to drawAll) # * improved (if not perfect) exiting without that irksome Tkinter error/bug # * app has a title in the titlebar (also shows window's dimensions) # * supports Modes and ModalApp (see ModalApp and Mode, and also see TestModalApp example) # * supports TopLevelApp (using top-level functions instead of subclasses and methods) # * supports version checking with App.majorVersion, App.minorVersion, and App.version # * logs drawing calls to support autograding views (still must write that autograder, but this is a very helpful first step) from tkinter import * from tkinter import messagebox, simpledialog, filedialog import inspect, traceback import sys, os from io import BytesIO def failedImport(importName, installName=None): installName = installName or importName print("**********************************************************") print( f"** Cannot import {importName} -- it seems you need to install {installName}" ) print( f"** This may result in limited functionality or even a runtime error." ) print("**********************************************************") print() try: from PIL import Image, ImageTk, ImageDraw, ImageFont except ModuleNotFoundError: failedImport("PIL", "pillow") if sys.platform.startswith("linux"): try: import pyscreenshot as ImageGrabber except ModuleNotFoundError: failedImport("pyscreenshot") else: try: from PIL import ImageGrab as ImageGrabber except ModuleNotFoundError: pass # Our PIL warning is already printed above try: import requests except ModuleNotFoundError: failedImport("requests") def getHash(obj): # This is used to detect MVC violations in redrawAll # @TODO: Make this more robust and efficient try: return getHash(obj.__dict__) except: if isinstance(obj, list): return getHash(tuple([getHash(v) for v in obj])) elif isinstance(obj, set): return getHash(sorted(obj)) elif isinstance(obj, dict): return getHash(tuple([obj[key] for key in sorted(obj)])) else: try: return hash(obj) except: return getHash(repr(obj)) class WrappedCanvas(Canvas): # Enforces MVC: no drawing outside calls to redrawAll # Logs draw calls (for autograder) in canvas.loggedDrawingCalls def __init__(wrappedCanvas, app): wrappedCanvas.loggedDrawingCalls = [] wrappedCanvas.logDrawingCalls = True wrappedCanvas.inRedrawAll = False wrappedCanvas.app = app super().__init__(app._root, width=app.width, height=app.height) def log(self, methodName, args, kwargs): if not self.inRedrawAll: self.app._mvcViolation( "you may not use the canvas (the view) outside of redrawAll" ) if self.logDrawingCalls: self.loggedDrawingCalls.append((methodName, args, kwargs)) def create_arc(self, *args, **kwargs): self.log("create_arc", args, kwargs) return super().create_arc(*args, **kwargs) def create_bitmap(self, *args, **kwargs): self.log("create_bitmap", args, kwargs) return super().create_bitmap(*args, **kwargs) def create_line(self, *args, **kwargs): self.log("create_line", args, kwargs) return super().create_line(*args, **kwargs) def create_oval(self, *args, **kwargs): self.log("create_oval", args, kwargs) return super().create_oval(*args, **kwargs) def create_polygon(self, *args, **kwargs): self.log("create_polygon", args, kwargs) return super().create_polygon(*args, **kwargs) def create_rectangle(self, *args, **kwargs): self.log("create_rectangle", args, kwargs) return super().create_rectangle(*args, **kwargs) def create_text(self, *args, **kwargs): self.log("create_text", args, kwargs) return super().create_text(*args, **kwargs) def create_window(self, *args, **kwargs): self.log("create_window", args, kwargs) return super().create_window(*args, **kwargs) def create_image(self, *args, **kwargs): self.log("create_image", args, kwargs) usesImage = "image" in kwargs usesPilImage = "pilImage" in kwargs if (not usesImage) and (not usesPilImage): raise Exception("create_image requires an image to draw") elif usesImage and usesPilImage: raise Exception( "create_image cannot use both an image and a pilImage" ) elif usesPilImage: pilImage = kwargs["pilImage"] del kwargs["pilImage"] if not isinstance(pilImage, Image.Image): raise Exception( "create_image: pilImage value is not an instance of a PIL/Pillow image" ) image = ImageTk.PhotoImage(pilImage) else: image = kwargs["image"] if isinstance(image, Image.Image): raise Exception( "create_image: image must not be an instance of a PIL/Pillow image\n" + "You perhaps meant to convert from PIL to Tkinter, like so:\n" + " canvas.create_image(x, y, image=ImageTk.PhotoImage(image))" ) kwargs["image"] = image return super().create_image(*args, **kwargs) class App(object): majorVersion = MAJOR_VERSION minorVersion = MINOR_VERSION version = f"{majorVersion}.{minorVersion}" lastUpdated = LAST_UPDATED _theRoot = None # singleton Tkinter root object #################################### # User Methods: #################################### def redrawAll(app, canvas): pass # draw (view) the model in the canvas def appStarted(app): pass # initialize the model (app.xyz) def appStopped(app): pass # cleanup after app is done running def keyPressed(app, event): pass # use event.key def keyReleased(app, event): pass # use event.key def mousePressed(app, event): pass # use event.x and event.y def mouseReleased(app, event): pass # use event.x and event.y def mouseMoved(app, event): pass # use event.x and event.y def mouseDragged(app, event): pass # use event.x and event.y def timerFired(app): pass # respond to timer events def sizeChanged(app): pass # respond to window size changes #################################### # Implementation: #################################### def __init__( app, width=300, height=300, x=0, y=0, title=None, autorun=True, mvcCheck=True, logDrawingCalls=True, ): app.winx, app.winy, app.width, app.height = x, y, width, height app.timerDelay = 100 # milliseconds app.mouseMovedDelay = 50 # ditto app._title = title app._mvcCheck = mvcCheck app._logDrawingCalls = logDrawingCalls app._running = app._paused = False app._mousePressedOutsideWindow = False if autorun: app.run() def __repr__(app): keys = set(app.__dict__.keys()) keyValues = [] for key in sorted(keys - app._ignoredFields): keyValues.append(f"{key}={app.__dict__[key]}") return f'App({", ".join(keyValues)})' def setSize(app, width, height): app._root.geometry(f"{width}x{height}") def setPosition(app, x, y): app._root.geometry(f"+{x}+{y}") def showMessage(app, message): messagebox.showinfo("showMessage", message, parent=app._root) def getUserInput(app, prompt): return simpledialog.askstring("getUserInput", prompt) def loadImage(app, path=None): if app._canvas.inRedrawAll: raise Exception("Cannot call loadImage in redrawAll") if path is None: path = filedialog.askopenfilename( initialdir=os.getcwd(), title="Select file: ", filetypes=( ("Image files", "*.png *.gif *.jpg"), ("all files", "*.*"), ), ) if not path: return None if path.startswith("http"): response = requests.request("GET", path) # path is a URL! image = Image.open(BytesIO(response.content)) else: image = Image.open(path) return image def scaleImage(app, image, scale, antialias=False): # antialiasing is higher-quality but slower resample = Image.ANTIALIAS if antialias else Image.NEAREST return image.resize( (round(image.width * scale), round(image.height * scale)), resample=resample, ) def getSnapshot(app): app._showRootWindow() x0 = app._root.winfo_rootx() + app._canvas.winfo_x() y0 = app._root.winfo_rooty() + app._canvas.winfo_y() result = ImageGrabber.grab((x0, y0, x0 + app.width, y0 + app.height)) return result def saveSnapshot(app): path = filedialog.asksaveasfilename( initialdir=os.getcwd(), title="Select file: ", filetypes=(("png files", "*.png"), ("all files", "*.*")), ) if path: # defer call to let filedialog close (and not grab those pixels) if not path.endswith(".png"): path += ".png" app._deferredMethodCall( afterId="saveSnapshot", afterDelay=0, afterFn=lambda: app.getSnapshot().save(path), ) def _togglePaused(app): app._paused = not app._paused def quit(app): app._running = False app._root.quit() # break out of root.mainloop() without closing window! def __setattr__(app, attr, val): d = app.__dict__ d[attr] = val canvas = d.get("_canvas", None) if ( d.get("running", False) and d.get("mvcCheck", False) and (canvas is not None) and canvas.inRedrawAll ): app._mvcViolation( f"you may not change app.{attr} in the model while in redrawAll (the view)" ) def _printUserTraceback(app, exception, tb): stack = traceback.extract_tb(tb) lines = traceback.format_list(stack) inRedrawAllWrapper = False printLines = [] for line in lines: if ( ('"cmu_112_graphics.py"' not in line) and ("/cmu_112_graphics.py" not in line) and ("\\cmu_112_graphics.py" not in line) and ("/tkinter/" not in line) and ("\\tkinter\\" not in line) ): printLines.append(line) if "redrawAllWrapper" in line: inRedrawAllWrapper = True if len(printLines) == 0: # No user code in trace, so we have to use all the code (bummer), # but not if we are in a redrawAllWrapper... if inRedrawAllWrapper: printLines = [ " No traceback available. Error occurred in redrawAll.\n" ] else: printLines = lines print("Traceback (most recent call last):") for line in printLines: print(line, end="") print(f"Exception: {exception}") def _safeMethod(appMethod): def m(*args, **kwargs): app = args[0] try: return appMethod(*args, **kwargs) except Exception as e: app._running = False app._printUserTraceback(e, sys.exc_info()[2]) if "_canvas" in app.__dict__: app._canvas.inRedrawAll = ( True # not really, but stops recursive MVC Violations! ) app._canvas.create_rectangle( 0, 0, app.width, app.height, fill=None, width=10, outline="red", ) app._canvas.create_rectangle( 10, app.height - 50, app.width - 10, app.height - 10, fill="white", outline="red", width=4, ) app._canvas.create_text( app.width / 2, app.height - 40, text=f"Exception! App Stopped!", fill="red", font="Arial 12 bold", ) app._canvas.create_text( app.width / 2, app.height - 20, text=f"See console for details", fill="red", font="Arial 12 bold", ) app._canvas.update() app.showMessage( f"Exception: {e}\nClick ok then see console for details." ) return m def _methodIsOverridden(app, methodName): return getattr(type(app), methodName) is not getattr(App, methodName) def _mvcViolation(app, errMsg): app._running = False raise Exception("MVC Violation: " + errMsg) @_safeMethod def _redrawAllWrapper(app): if not app._running: return if "deferredRedrawAll" in app._afterIdMap: return # wait for pending call app._canvas.inRedrawAll = True app._canvas.delete(ALL) width, outline = (10, "red") if app._paused else (0, "white") app._canvas.create_rectangle( 0, 0, app.width, app.height, fill="white", width=width, outline=outline, ) app._canvas.loggedDrawingCalls = [] app._canvas.logDrawingCalls = app._logDrawingCalls hash1 = getHash(app) if app._mvcCheck else None try: app.redrawAll(app._canvas) hash2 = getHash(app) if app._mvcCheck else None if hash1 != hash2: app._mvcViolation( "you may not change the app state (the model) in redrawAll (the view)" ) finally: app._canvas.inRedrawAll = False app._canvas.update() def _deferredMethodCall(app, afterId, afterDelay, afterFn, replace=False): def afterFnWrapper(): app._afterIdMap.pop(afterId, None) afterFn() id = app._afterIdMap.get(afterId, None) if (id is None) or replace: if id: app._root.after_cancel(id) app._afterIdMap[afterId] = app._root.after( afterDelay, afterFnWrapper ) def _deferredRedrawAll(app): app._deferredMethodCall( afterId="deferredRedrawAll", afterDelay=100, afterFn=app._redrawAllWrapper, replace=True, ) @_safeMethod def _appStartedWrapper(app): app.appStarted() app._redrawAllWrapper() _keyNameMap = { "\t": "Tab", "\n": "Enter", "\r": "Enter", "\b": "Backspace", chr(127): "Delete", chr(27): "Escape", " ": "Space", } @staticmethod def _useEventKey(attr): raise Exception(f"Use event.key instead of event.{attr}") @staticmethod def _getEventKeyInfo(event, keysym, char): key = c = char hasControlKey = event.state & 0x4 != 0 if (c in [None, ""]) or (len(c) > 1) or (ord(c) > 255): key = keysym if ( key.endswith("_L") or key.endswith("_R") or key.endswith("_Lock") ): key = "Modifier_Key" elif c in App._keyNameMap: key = App._keyNameMap[c] elif (len(c) == 1) and (1 <= ord(c) <= 26): key = chr(ord("a") - 1 + ord(c)) hasControlKey = True if hasControlKey and (len(key) == 1): # don't add control- prefix to Enter, Tab, Escape, ... key = "control-" + key return key class EventWrapper(Event): def __init__(self, event): for key in event.__dict__: if not key.startswith("__"): self.__dict__[key] = event.__dict__[key] class MouseEventWrapper(EventWrapper): def __repr__(self): return f"Event(x={self.x}, y={self.y})" class KeyEventWrapper(EventWrapper): def __init__(self, event): keysym, char = event.keysym, event.char del event.keysym del event.char super().__init__(event) self.key = App._getEventKeyInfo(event, keysym, char) def __repr__(self): return f"Event(key={repr(self.key)})" keysym = property( lambda *args: App._useEventKey("keysym"), lambda *args: App._useEventKey("keysym"), ) char = property( lambda *args: App._useEventKey("char"), lambda *args: App._useEventKey("char"), ) @_safeMethod def _keyPressedWrapper(app, event): event = App.KeyEventWrapper(event) if event.key == "control-s": app.saveSnapshot() elif event.key == "control-p": app._togglePaused() app._redrawAllWrapper() elif event.key == "control-q": app.quit() elif event.key == "control-x": os._exit(0) # hard exit avoids tkinter error messages elif ( app._running and (not app._paused) and app._methodIsOverridden("keyPressed") and (not event.key == "Modifier_Key") ): app.keyPressed(event) app._redrawAllWrapper() @_safeMethod def _keyReleasedWrapper(app, event): if ( (not app._running) or app._paused or (not app._methodIsOverridden("keyReleased")) ): return event = App.KeyEventWrapper(event) if not event.key == "Modifier_Key": app.keyReleased(event) app._redrawAllWrapper() @_safeMethod def _mousePressedWrapper(app, event): if (not app._running) or app._paused: return if ( (event.x < 0) or (event.x > app.width) or (event.y < 0) or (event.y > app.height) ): app._mousePressedOutsideWindow = True else: app._mousePressedOutsideWindow = False app._mouseIsPressed = True app._lastMousePosn = (event.x, event.y) if app._methodIsOverridden("mousePressed"): event = App.MouseEventWrapper(event) app.mousePressed(event) app._redrawAllWrapper() @_safeMethod def _mouseReleasedWrapper(app, event): if (not app._running) or app._paused: return app._mouseIsPressed = False if app._mousePressedOutsideWindow: app._mousePressedOutsideWindow = False app._sizeChangedWrapper() else: app._lastMousePosn = (event.x, event.y) if app._methodIsOverridden("mouseReleased"): event = App.MouseEventWrapper(event) app.mouseReleased(event) app._redrawAllWrapper() @_safeMethod def _timerFiredWrapper(app): if (not app._running) or (not app._methodIsOverridden("timerFired")): return if not app._paused: app.timerFired() app._redrawAllWrapper() app._deferredMethodCall( afterId="_timerFiredWrapper", afterDelay=app.timerDelay, afterFn=app._timerFiredWrapper, ) @_safeMethod def _sizeChangedWrapper(app, event=None): if not app._running: return if event and ((event.width < 2) or (event.height < 2)): return if app._mousePressedOutsideWindow: return app.width, app.height, app.winx, app.winy = [ int(v) for v in app._root.winfo_geometry().replace("x", "+").split("+") ] if app._lastWindowDims is None: app._lastWindowDims = (app.width, app.height, app.winx, app.winy) else: newDims = (app.width, app.height, app.winx, app.winy) if app._lastWindowDims != newDims: app._lastWindowDims = newDims app.updateTitle() app.sizeChanged() app._deferredRedrawAll() # avoid resize crashing on some platforms @_safeMethod def _mouseMotionWrapper(app): if not app._running: return mouseMovedExists = app._methodIsOverridden("mouseMoved") mouseDraggedExists = app._methodIsOverridden("mouseDragged") if ( (not app._paused) and (not app._mousePressedOutsideWindow) and ( ((not app._mouseIsPressed) and mouseMovedExists) or (app._mouseIsPressed and mouseDraggedExists) ) ): class MouseMotionEvent(object): pass event = MouseMotionEvent() root = app._root event.x = root.winfo_pointerx() - root.winfo_rootx() event.y = root.winfo_pointery() - root.winfo_rooty() event = App.MouseEventWrapper(event) if ( (app._lastMousePosn != (event.x, event.y)) and (event.x >= 0) and (event.x <= app.width) and (event.y >= 0) and (event.y <= app.height) ): if app._mouseIsPressed: app.mouseDragged(event) else: app.mouseMoved(event) app._lastMousePosn = (event.x, event.y) app._redrawAllWrapper() if mouseMovedExists or mouseDraggedExists: app._deferredMethodCall( afterId="mouseMotionWrapper", afterDelay=app.mouseMovedDelay, afterFn=app._mouseMotionWrapper, ) def updateTitle(app): app._title = app._title or type(app).__name__ app._root.title(f"{app._title} ({app.width} x {app.height})") def getQuitMessage(app): appLabel = type(app).__name__ if app._title != appLabel: if app._title.startswith(appLabel): appLabel = app._title else: appLabel += f" '{app._title}'" return f"*** Closing {appLabel}. Bye! ***\n" def _showRootWindow(app): root = app._root root.update() root.deiconify() root.lift() root.focus() def _hideRootWindow(app): root = app._root root.withdraw() @_safeMethod def run(app): app._mouseIsPressed = False app._lastMousePosn = (-1, -1) app._lastWindowDims = None # set in sizeChangedWrapper app._afterIdMap = dict() # create the singleton root window if App._theRoot is None: App._theRoot = Tk() App._theRoot.createcommand( "exit", lambda: "" ) # when user enters cmd-q, ignore here (handled in keyPressed) App._theRoot.protocol( "WM_DELETE_WINDOW", lambda: App._theRoot.app.quit() ) # when user presses 'x' in title bar App._theRoot.bind( "<Button-1>", lambda event: App._theRoot.app._mousePressedWrapper(event), ) App._theRoot.bind( "<B1-ButtonRelease>", lambda event: App._theRoot.app._mouseReleasedWrapper(event), ) App._theRoot.bind( "<KeyPress>", lambda event: App._theRoot.app._keyPressedWrapper(event), ) App._theRoot.bind( "<KeyRelease>", lambda event: App._theRoot.app._keyReleasedWrapper(event), ) App._theRoot.bind( "<Configure>", lambda event: App._theRoot.app._sizeChangedWrapper(event), ) else: App._theRoot.canvas.destroy() app._root = root = App._theRoot # singleton root! root.app = app root.geometry(f"{app.width}x{app.height}+{app.winx}+{app.winy}") app.updateTitle() # create the canvas root.canvas = app._canvas = WrappedCanvas(app) app._canvas.pack(fill=BOTH, expand=YES) # initialize, start the timer, and launch the app app._running = True app._paused = False app._ignoredFields = set(app.__dict__.keys()) | {"_ignoredFields"} app._appStartedWrapper() app._timerFiredWrapper() app._mouseMotionWrapper() app._showRootWindow() root.mainloop() app._hideRootWindow() app._running = False for afterId in app._afterIdMap: app._root.after_cancel(app._afterIdMap[afterId]) app._afterIdMap.clear() # for safety app.appStopped() print(app.getQuitMessage()) #################################### # TopLevelApp: # (with top-level functions not subclassses and methods) #################################### class TopLevelApp(App): _apps = dict() # maps fnPrefix to app def __init__(app, fnPrefix="", **kwargs): if fnPrefix in TopLevelApp._apps: print(f"Quitting previous version of {fnPrefix} TopLevelApp.") TopLevelApp._apps[fnPrefix].quit() if (fnPrefix != "") and ("title" not in kwargs): kwargs["title"] = f"TopLevelApp '{fnPrefix}'" TopLevelApp._apps[fnPrefix] = app app._fnPrefix = fnPrefix app._callersGlobals = inspect.stack()[1][0].f_globals app.mode = None super().__init__(**kwargs) def _callFn(app, fn, *args): if (app.mode is not None) and (app.mode != ""): fn = app.mode + "_" + fn fn = app._fnPrefix + fn if fn in app._callersGlobals: app._callersGlobals[fn](*args) def redrawAll(app, canvas): app._callFn("redrawAll", app, canvas) def appStarted(app): app._callFn("appStarted", app) def appStopped(app): app._callFn("appStopped", app) def keyPressed(app, event): app._callFn("keyPressed", app, event) def keyReleased(app, event): app._callFn("keyReleased", app, event) def mousePressed(app, event): app._callFn("mousePressed", app, event) def mouseReleased(app, event): app._callFn("mouseReleased", app, event) def mouseMoved(app, event): app._callFn("mouseMoved", app, event) def mouseDragged(app, event): app._callFn("mouseDragged", app, event) def timerFired(app): app._callFn("timerFired", app) def sizeChanged(app): app._callFn("sizeChanged", app) #################################### # ModalApp + Mode: #################################### """ # For now, only include modes in top-level apps (see above). class Mode(object): def __repr__(self): return f'<{self.__class__.__name__} object>' class ModalApp(App): def __init__(app, *args, **kwargs): app._mode = None super().__init__(*args, **kwargs) def setMode(app, mode): if (not isinstance(mode, Mode)): raise Exception('mode must be an instance of Mode') app._mode = mode def _callFn(app, fn, *args): if (app._mode == None): raise Exception('ModalApp must have a mode (use app.setMode())') mode = app._mode # method = getattr(mode, fn, None) method = mode.__class__.__dict__.get(fn) # get method as fn if (method != None): method(*args) def redrawAll(app, canvas): app._callFn('redrawAll', app, canvas) #def appStarted(app): app._callFn('appStarted', app) #def appStopped(app): app._callFn('appStopped', app) def keyPressed(app, event): app._callFn('keyPressed', app, event) def keyReleased(app, event): app._callFn('keyReleased', app, event) def mousePressed(app, event): app._callFn('mousePressed', app, event) def mouseReleased(app, event): app._callFn('mouseReleased', app, event) def mouseMoved(app, event): app._callFn('mouseMoved', app, event) def mouseDragged(app, event): app._callFn('mouseDragged', app, event) def timerFired(app): app._callFn('timerFired', app) def sizeChanged(app): app._callFn('sizeChanged', app) """ #################################### # runApp() #################################### """ def showGraphics(drawFn, **kwargs): class GraphicsApp(App): def __init__(app, **kwargs): if ('title' not in kwargs): kwargs['title'] = drawFn.__name__ super().__init__(**kwargs) def redrawAll(app, canvas): drawFn(app, canvas) app = GraphicsApp(**kwargs) """ runApp = TopLevelApp print( f"Loaded cmu_112_graphics version {App.version} (last updated {App.lastUpdated})" ) if __name__ == "__main__": try: import cmu_112_graphics_tests except: pass
from datetime import datetime from airflow.models import DAG from airflow.providers.apache.spark.operators.spark_jdbc import SparkJDBCOperator from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator import os with DAG( dag_id='spark_test', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['FreeUni'], ) as dag: # [START howto_operator_spark_submit] submit_job = SparkSubmitOperator( application="/airflow/jobs/test_job.py", task_id="submit_job" ) # [END howto_operator_spark_submit] submit_job_2 = SparkSubmitOperator( application=f"{os.getenv("SPARK_HOME")}/examples/src/main/python/pi.py", task_id="submit_job_2" ) submit_job_3 = SparkSubmitOperator( application=f"/airflow/jobs/breaking_news.py", task_id="breaking_news" ) [submit_job, submit_job_2] >> submit_job_3
from datetime import datetime from airflow.models import DAG from airflow.providers.apache.spark.operators.spark_jdbc import SparkJDBCOperator from airflow.providers.apache.spark.operators.spark_sql import SparkSqlOperator from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator import os with DAG( dag_id='spark_test', schedule_interval=None, start_date=datetime(2021, 1, 1), catchup=False, tags=['FreeUni'], ) as dag: # [START howto_operator_spark_submit] submit_job = SparkSubmitOperator( application="/airflow/jobs/test_job.py", task_id="submit_job" ) # [END howto_operator_spark_submit] submit_job_2 = SparkSubmitOperator( application=f"{os.getenv('SPARK_HOME')}/examples/src/main/python/pi.py", task_id="submit_job_2" ) submit_job_3 = SparkSubmitOperator( application=f"/airflow/jobs/breaking_news.py", task_id="breaking_news" ) [submit_job, submit_job_2] >> submit_job_3
import os import asyncio import logging import configparser from contextlib import suppress from eventkit import Event from ib_insync.objects import Object from ib_insync.contract import Forex from ib_insync.ib import IB import ib_insync.util as util __all__ = ['IBC', 'IBController', 'Watchdog'] class IBC(Object): """ Programmatic control over starting and stopping TWS/Gateway using IBC (https://github.com/IbcAlpha/IBC). Args: twsVersion (int): (required) The major version number for TWS or gateway. gateway (bool): * True = gateway * False = TWS tradingMode (str): 'live' or 'paper'. userid (str): IB account username. It is recommended to set the real username/password in a secured IBC config file. password (str): IB account password. twsPath (str): Path to the TWS installation folder. Defaults: * Linux: ~/Jts * OS X: ~/Applications * Windows: C:\\\\Jts twsSettingsPath (str): Path to the TWS settings folder. Defaults: * Linux: ~/Jts * OS X: ~/Jts * Windows: Not available ibcPath (str): Path to the IBC installation folder. Defaults: * Linux: /opt/ibc * OS X: /opt/ibc * Windows: C:\\\\IBC ibcIni (str): Path to the IBC configuration file. Defaults: * Linux: ~/ibc/config.ini * OS X: ~/ibc/config.ini * Windows: %%HOMEPATH%%\\\\Documents\\\\IBC\\\\config.ini javaPath (str): Path to Java executable. Default is to use the Java VM included with TWS/gateway. fixuserid (str): FIX account user id (gateway only). fixpassword (str): FIX account password (gateway only). This is not intended to be run in a notebook. To use IBC on Windows, the proactor (or quamash) event loop must have been set: .. code-block:: python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) Example usage: .. code-block:: python ibc = IBC(974, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() """ IbcLogLevel = logging.DEBUG _Args = dict( # key=(Default, UnixArg, WindowsArg) twsVersion=(None, '', ''), gateway=(None, '--gateway', '/Gateway'), tradingMode=(None, '--mode=', '/Mode:'), twsPath=(None, '--tws-path=', '/TwsPath:'), twsSettingsPath=(None, '--tws-settings-path=', ''), ibcPath=(None, '--ibc-path=', '/IbcPath:'), ibcIni=(None, '--ibc-ini=', '/Config:'), javaPath=(None, '--java-path=', '/JavaPath:'), userid=(None, '--user=', '/User:'), password=(None, '--pw=', '/PW:'), fixuserid=(None, '--fix-user=', '/FIXUser:'), fixpassword=(None, '--fix-pw=', '/FIXPW:')) defaults = {k: v[0] for k, v in _Args.items()} __slots__ = list(defaults) + ['_proc', '_logger', '_monitor'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) if not self.ibcPath: self.ibcPath = '/opt/ibc' if os.sys.platform != 'win32' \ else 'C:\\IBC' self._proc = None self._monitor = None self._logger = logging.getLogger('ib_insync.IBC') def __enter__(self): self.start() return self def __exit__(self, *_exc): self.terminate() def start(self): """ Launch TWS/IBG. """ util.run(self.startAsync()) def terminate(self): """ Terminate TWS/IBG. """ util.run(self.terminateAsync()) async def startAsync(self): if self._proc: return self._logger.info('Starting') # create shell command win32 = os.sys.platform == 'win32' cmd = [ f'{self.ibcPath}\\scripts\\StartIBC.bat' if win32 else #TODO: add 'runIncontainer' option to class f'/usr/bin/xvfb-run', f'-a', f'{self.ibcPath}/scripts/ibcstart.sh'] for k, v in self.dict().items(): arg = IBC._Args[k][2 if win32 else 1] if v: if arg.endswith('=') or arg.endswith(':'): cmd.append(f'{arg}{v}') elif arg: cmd.append(arg) else: cmd.append(str(v)) # run shell command self._proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE) self._monitor = asyncio.ensure_future(self.monitorAsync()) async def terminateAsync(self): if not self._proc: return self._logger.info('Terminating') if self._monitor: self._monitor.cancel() self._monitor = None if os.sys.platform == 'win32': import subprocess subprocess.call( ['taskkill', '/F', '/T', '/PID', str(self._proc.pid)]) else: with suppress(ProcessLookupError): self._proc.terminate() await self._proc.wait() self._proc = None async def monitorAsync(self): while self._proc: line = await self._proc.stdout.readline() if not line: break self._logger.log(IBC.IbcLogLevel, line.strip().decode()) class IBController(Object): """ For new installations it is recommended to use IBC instead. Programmatic control over starting and stopping TWS/Gateway using IBController (https://github.com/ib-controller/ib-controller). On Windows the the proactor (or quamash) event loop must have been set: .. code-block:: python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) This is not intended to be run in a notebook. """ defaults = dict( APP='TWS', # 'TWS' or 'GATEWAY' TWS_MAJOR_VRSN='969', TRADING_MODE='live', # 'live' or 'paper' IBC_INI='~/IBController/IBController.ini', IBC_PATH='~/IBController', TWS_PATH='~/Jts', LOG_PATH='~/IBController/Logs', TWSUSERID='', TWSPASSWORD='', JAVA_PATH='', TWS_CONFIG_PATH='') __slots__ = list(defaults) + ['_proc', '_logger', '_monitor'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) self._proc = None self._monitor = None self._logger = logging.getLogger('ib_insync.IBController') def __enter__(self): self.start() return self def __exit__(self, *_exc): self.terminate() def start(self): """ Launch TWS/IBG. """ util.run(self.startAsync()) def stop(self): """ Cleanly shutdown TWS/IBG. """ util.run(self.stopAsync()) def terminate(self): """ Terminate TWS/IBG. """ util.run(self.terminateAsync()) async def startAsync(self): if self._proc: return self._logger.info('Starting') # expand paths d = self.dict() for k, v in d.items(): if k.endswith('_PATH') or k.endswith('_INI'): d[k] = os.path.expanduser(v) if not d['TWS_CONFIG_PATH']: d['TWS_CONFIG_PATH'] = d['TWS_PATH'] self.update(**d) # run shell command ext = 'bat' if os.sys.platform == 'win32' else 'sh' cmd = f'{d['IBC_PATH']}/Scripts/DisplayBannerAndLaunch.{ext}' env = {**os.environ, **d} self._proc = await asyncio.create_subprocess_exec( cmd, env=env, stdout=asyncio.subprocess.PIPE) self._monitor = asyncio.ensure_future(self.monitorAsync()) async def stopAsync(self): if not self._proc: return self._logger.info('Stopping') # read ibcontroller ini file to get controller port txt = '[section]' + open(self.IBC_INI).read() config = configparser.ConfigParser() config.read_string(txt) contrPort = config.getint('section', 'IbControllerPort') _reader, writer = await asyncio.open_connection('127.0.0.1', contrPort) writer.write(b'STOP') await writer.drain() writer.close() await self._proc.wait() self._proc = None self._monitor.cancel() self._monitor = None async def terminateAsync(self): if not self._proc: return self._logger.info('Terminating') self._monitor.cancel() self._monitor = None with suppress(ProcessLookupError): self._proc.terminate() await self._proc.wait() self._proc = None async def monitorAsync(self): while self._proc: line = await self._proc.stdout.readline() if not line: break self._logger.info(line.strip().decode()) class Watchdog(Object): """ Start, connect and watch over the TWS or gateway app and try to keep it up and running. It is intended to be used in an event-driven application that properly initializes itself upon (re-)connect. It is not intended to be used in a notebook or in imperative-style code. Do not expect Watchdog to magically shield you from reality. Do not use Watchdog unless you understand what it does and doesn't do. Args: controller (Union[IBC, IBController]): (required) IBC or IBController instance. ib (IB): (required) IB instance to be used. Do no connect this instance as Watchdog takes care of that. host (str): Used for connecting IB instance. port (int): Used for connecting IB instance. clientId (int): Used for connecting IB instance. connectTimeout (float): Used for connecting IB instance. appStartupTime (float): Time (in seconds) that the app is given to start up. Make sure that it is given ample time. appTimeout (float): Timeout (in seconds) for network traffic idle time. retryDelay (float): Time (in seconds) to restart app after a previous failure. The idea is to wait until there is no traffic coming from the app for a certain amount of time (the ``appTimeout`` parameter). This triggers a historical request to be placed just to see if the app is still alive and well. If yes, then continue, if no then restart the whole app and reconnect. Restarting will also occur directly on error 1100. Example usage: .. code-block:: python def onConnected(): print(ib.accountValues()) ibc = IBC(974, gateway=True, tradingMode='paper') ib = IB() ib.connectedEvent += onConnected watchdog = Watchdog(ibc, ib, port=4002) watchdog.start() IB.run() Events: * ``startingEvent`` (watchdog: :class:`.Watchdog`) * ``startedEvent`` (watchdog: :class:`.Watchdog`) * ``stoppingEvent`` (watchdog: :class:`.Watchdog`) * ``stoppedEvent`` (watchdog: :class:`.Watchdog`) * ``softTimeoutEvent`` (watchdog: :class:`.Watchdog`) * ``hardTimeoutEvent`` (watchdog: :class:`.Watchdog`) """ events = [ 'startingEvent', 'startedEvent', 'stoppingEvent', 'stoppedEvent', 'softTimeoutEvent', 'hardTimeoutEvent'] defaults = dict( controller=None, ib=None, host='127.0.0.1', port='7497', clientId=1, connectTimeout=2, appStartupTime=30, appTimeout=20, retryDelay=2) __slots__ = list(defaults.keys()) + events + ['_runner', '_logger'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) Event.init(self, Watchdog.events) if not self.controller: raise ValueError('No controller supplied') if not self.ib: raise ValueError('No IB instance supplied') if self.ib.isConnected(): raise ValueError('IB instance must not be connected') assert 0 < self.appTimeout < 60 assert self.retryDelay > 0 self._runner = None self._logger = logging.getLogger('ib_insync.Watchdog') def start(self): self._logger.info('Starting') self.startingEvent.emit(self) self._runner = asyncio.ensure_future(self.runAsync()) def stop(self): self._logger.info('Stopping') self.stoppingEvent.emit(self) self.ib.disconnect() self._runner = None async def runAsync(self): def onTimeout(idlePeriod): if not waiter.done(): waiter.set_result(None) def onError(reqId, errorCode, errorString, contract): if errorCode == 1100 and not waiter.done(): waiter.set_exception(Warning('Error 1100')) def onDisconnected(): if not waiter.done(): waiter.set_exception(Warning('Disconnected')) while self._runner: try: await self.controller.startAsync() await asyncio.sleep(self.appStartupTime) await self.ib.connectAsync( self.host, self.port, self.clientId, self.connectTimeout) self.startedEvent.emit(self) self.ib.setTimeout(self.appTimeout) self.ib.timeoutEvent += onTimeout self.ib.errorEvent += onError self.ib.disconnectedEvent += onDisconnected while self._runner: waiter = asyncio.Future() await waiter # soft timeout, probe the app with a historical request self._logger.debug('Soft timeout') self.softTimeoutEvent.emit(self) probe = self.ib.reqHistoricalDataAsync( Forex('EURUSD'), '', '30 S', '5 secs', 'MIDPOINT', False) bars = None with suppress(asyncio.TimeoutError): bars = await asyncio.wait_for(probe, 4) if not bars: self.hardTimeoutEvent.emit(self) raise Warning('Hard timeout') self.ib.setTimeout(self.appTimeout) except ConnectionRefusedError: pass except Warning as w: self._logger.warning(w) except Exception as e: self._logger.exception(e) finally: self.ib.timeoutEvent -= onTimeout self.ib.errorEvent -= onError self.ib.disconnectedEvent -= onDisconnected await self.controller.terminateAsync() self.stoppedEvent.emit(self) if self._runner: await asyncio.sleep(self.retryDelay) if __name__ == '__main__': asyncio.get_event_loop().set_debug(True) util.logToConsole(logging.DEBUG) ibc = IBC(974, gateway=True, tradingMode='paper') # userid='edemo', password='demouser') ib = IB() app = Watchdog(ibc, ib, port=4002, appStartupTime=15, appTimeout=10) app.start() IB.run()
import os import asyncio import logging import configparser from contextlib import suppress from eventkit import Event from ib_insync.objects import Object from ib_insync.contract import Forex from ib_insync.ib import IB import ib_insync.util as util __all__ = ['IBC', 'IBController', 'Watchdog'] class IBC(Object): """ Programmatic control over starting and stopping TWS/Gateway using IBC (https://github.com/IbcAlpha/IBC). Args: twsVersion (int): (required) The major version number for TWS or gateway. gateway (bool): * True = gateway * False = TWS tradingMode (str): 'live' or 'paper'. userid (str): IB account username. It is recommended to set the real username/password in a secured IBC config file. password (str): IB account password. twsPath (str): Path to the TWS installation folder. Defaults: * Linux: ~/Jts * OS X: ~/Applications * Windows: C:\\\\Jts twsSettingsPath (str): Path to the TWS settings folder. Defaults: * Linux: ~/Jts * OS X: ~/Jts * Windows: Not available ibcPath (str): Path to the IBC installation folder. Defaults: * Linux: /opt/ibc * OS X: /opt/ibc * Windows: C:\\\\IBC ibcIni (str): Path to the IBC configuration file. Defaults: * Linux: ~/ibc/config.ini * OS X: ~/ibc/config.ini * Windows: %%HOMEPATH%%\\\\Documents\\\\IBC\\\\config.ini javaPath (str): Path to Java executable. Default is to use the Java VM included with TWS/gateway. fixuserid (str): FIX account user id (gateway only). fixpassword (str): FIX account password (gateway only). This is not intended to be run in a notebook. To use IBC on Windows, the proactor (or quamash) event loop must have been set: .. code-block:: python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) Example usage: .. code-block:: python ibc = IBC(974, gateway=True, tradingMode='live', userid='edemo', password='demouser') ibc.start() IB.run() """ IbcLogLevel = logging.DEBUG _Args = dict( # key=(Default, UnixArg, WindowsArg) twsVersion=(None, '', ''), gateway=(None, '--gateway', '/Gateway'), tradingMode=(None, '--mode=', '/Mode:'), twsPath=(None, '--tws-path=', '/TwsPath:'), twsSettingsPath=(None, '--tws-settings-path=', ''), ibcPath=(None, '--ibc-path=', '/IbcPath:'), ibcIni=(None, '--ibc-ini=', '/Config:'), javaPath=(None, '--java-path=', '/JavaPath:'), userid=(None, '--user=', '/User:'), password=(None, '--pw=', '/PW:'), fixuserid=(None, '--fix-user=', '/FIXUser:'), fixpassword=(None, '--fix-pw=', '/FIXPW:')) defaults = {k: v[0] for k, v in _Args.items()} __slots__ = list(defaults) + ['_proc', '_logger', '_monitor'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) if not self.ibcPath: self.ibcPath = '/opt/ibc' if os.sys.platform != 'win32' \ else 'C:\\IBC' self._proc = None self._monitor = None self._logger = logging.getLogger('ib_insync.IBC') def __enter__(self): self.start() return self def __exit__(self, *_exc): self.terminate() def start(self): """ Launch TWS/IBG. """ util.run(self.startAsync()) def terminate(self): """ Terminate TWS/IBG. """ util.run(self.terminateAsync()) async def startAsync(self): if self._proc: return self._logger.info('Starting') # create shell command win32 = os.sys.platform == 'win32' cmd = [ f'{self.ibcPath}\\scripts\\StartIBC.bat' if win32 else #TODO: add 'runIncontainer' option to class f'/usr/bin/xvfb-run', f'-a', f'{self.ibcPath}/scripts/ibcstart.sh'] for k, v in self.dict().items(): arg = IBC._Args[k][2 if win32 else 1] if v: if arg.endswith('=') or arg.endswith(':'): cmd.append(f'{arg}{v}') elif arg: cmd.append(arg) else: cmd.append(str(v)) # run shell command self._proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE) self._monitor = asyncio.ensure_future(self.monitorAsync()) async def terminateAsync(self): if not self._proc: return self._logger.info('Terminating') if self._monitor: self._monitor.cancel() self._monitor = None if os.sys.platform == 'win32': import subprocess subprocess.call( ['taskkill', '/F', '/T', '/PID', str(self._proc.pid)]) else: with suppress(ProcessLookupError): self._proc.terminate() await self._proc.wait() self._proc = None async def monitorAsync(self): while self._proc: line = await self._proc.stdout.readline() if not line: break self._logger.log(IBC.IbcLogLevel, line.strip().decode()) class IBController(Object): """ For new installations it is recommended to use IBC instead. Programmatic control over starting and stopping TWS/Gateway using IBController (https://github.com/ib-controller/ib-controller). On Windows the the proactor (or quamash) event loop must have been set: .. code-block:: python import asyncio asyncio.set_event_loop(asyncio.ProactorEventLoop()) This is not intended to be run in a notebook. """ defaults = dict( APP='TWS', # 'TWS' or 'GATEWAY' TWS_MAJOR_VRSN='969', TRADING_MODE='live', # 'live' or 'paper' IBC_INI='~/IBController/IBController.ini', IBC_PATH='~/IBController', TWS_PATH='~/Jts', LOG_PATH='~/IBController/Logs', TWSUSERID='', TWSPASSWORD='', JAVA_PATH='', TWS_CONFIG_PATH='') __slots__ = list(defaults) + ['_proc', '_logger', '_monitor'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) self._proc = None self._monitor = None self._logger = logging.getLogger('ib_insync.IBController') def __enter__(self): self.start() return self def __exit__(self, *_exc): self.terminate() def start(self): """ Launch TWS/IBG. """ util.run(self.startAsync()) def stop(self): """ Cleanly shutdown TWS/IBG. """ util.run(self.stopAsync()) def terminate(self): """ Terminate TWS/IBG. """ util.run(self.terminateAsync()) async def startAsync(self): if self._proc: return self._logger.info('Starting') # expand paths d = self.dict() for k, v in d.items(): if k.endswith('_PATH') or k.endswith('_INI'): d[k] = os.path.expanduser(v) if not d['TWS_CONFIG_PATH']: d['TWS_CONFIG_PATH'] = d['TWS_PATH'] self.update(**d) # run shell command ext = 'bat' if os.sys.platform == 'win32' else 'sh' cmd = f'{d["IBC_PATH"]}/Scripts/DisplayBannerAndLaunch.{ext}' env = {**os.environ, **d} self._proc = await asyncio.create_subprocess_exec( cmd, env=env, stdout=asyncio.subprocess.PIPE) self._monitor = asyncio.ensure_future(self.monitorAsync()) async def stopAsync(self): if not self._proc: return self._logger.info('Stopping') # read ibcontroller ini file to get controller port txt = '[section]' + open(self.IBC_INI).read() config = configparser.ConfigParser() config.read_string(txt) contrPort = config.getint('section', 'IbControllerPort') _reader, writer = await asyncio.open_connection('127.0.0.1', contrPort) writer.write(b'STOP') await writer.drain() writer.close() await self._proc.wait() self._proc = None self._monitor.cancel() self._monitor = None async def terminateAsync(self): if not self._proc: return self._logger.info('Terminating') self._monitor.cancel() self._monitor = None with suppress(ProcessLookupError): self._proc.terminate() await self._proc.wait() self._proc = None async def monitorAsync(self): while self._proc: line = await self._proc.stdout.readline() if not line: break self._logger.info(line.strip().decode()) class Watchdog(Object): """ Start, connect and watch over the TWS or gateway app and try to keep it up and running. It is intended to be used in an event-driven application that properly initializes itself upon (re-)connect. It is not intended to be used in a notebook or in imperative-style code. Do not expect Watchdog to magically shield you from reality. Do not use Watchdog unless you understand what it does and doesn't do. Args: controller (Union[IBC, IBController]): (required) IBC or IBController instance. ib (IB): (required) IB instance to be used. Do no connect this instance as Watchdog takes care of that. host (str): Used for connecting IB instance. port (int): Used for connecting IB instance. clientId (int): Used for connecting IB instance. connectTimeout (float): Used for connecting IB instance. appStartupTime (float): Time (in seconds) that the app is given to start up. Make sure that it is given ample time. appTimeout (float): Timeout (in seconds) for network traffic idle time. retryDelay (float): Time (in seconds) to restart app after a previous failure. The idea is to wait until there is no traffic coming from the app for a certain amount of time (the ``appTimeout`` parameter). This triggers a historical request to be placed just to see if the app is still alive and well. If yes, then continue, if no then restart the whole app and reconnect. Restarting will also occur directly on error 1100. Example usage: .. code-block:: python def onConnected(): print(ib.accountValues()) ibc = IBC(974, gateway=True, tradingMode='paper') ib = IB() ib.connectedEvent += onConnected watchdog = Watchdog(ibc, ib, port=4002) watchdog.start() IB.run() Events: * ``startingEvent`` (watchdog: :class:`.Watchdog`) * ``startedEvent`` (watchdog: :class:`.Watchdog`) * ``stoppingEvent`` (watchdog: :class:`.Watchdog`) * ``stoppedEvent`` (watchdog: :class:`.Watchdog`) * ``softTimeoutEvent`` (watchdog: :class:`.Watchdog`) * ``hardTimeoutEvent`` (watchdog: :class:`.Watchdog`) """ events = [ 'startingEvent', 'startedEvent', 'stoppingEvent', 'stoppedEvent', 'softTimeoutEvent', 'hardTimeoutEvent'] defaults = dict( controller=None, ib=None, host='127.0.0.1', port='7497', clientId=1, connectTimeout=2, appStartupTime=30, appTimeout=20, retryDelay=2) __slots__ = list(defaults.keys()) + events + ['_runner', '_logger'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) Event.init(self, Watchdog.events) if not self.controller: raise ValueError('No controller supplied') if not self.ib: raise ValueError('No IB instance supplied') if self.ib.isConnected(): raise ValueError('IB instance must not be connected') assert 0 < self.appTimeout < 60 assert self.retryDelay > 0 self._runner = None self._logger = logging.getLogger('ib_insync.Watchdog') def start(self): self._logger.info('Starting') self.startingEvent.emit(self) self._runner = asyncio.ensure_future(self.runAsync()) def stop(self): self._logger.info('Stopping') self.stoppingEvent.emit(self) self.ib.disconnect() self._runner = None async def runAsync(self): def onTimeout(idlePeriod): if not waiter.done(): waiter.set_result(None) def onError(reqId, errorCode, errorString, contract): if errorCode == 1100 and not waiter.done(): waiter.set_exception(Warning('Error 1100')) def onDisconnected(): if not waiter.done(): waiter.set_exception(Warning('Disconnected')) while self._runner: try: await self.controller.startAsync() await asyncio.sleep(self.appStartupTime) await self.ib.connectAsync( self.host, self.port, self.clientId, self.connectTimeout) self.startedEvent.emit(self) self.ib.setTimeout(self.appTimeout) self.ib.timeoutEvent += onTimeout self.ib.errorEvent += onError self.ib.disconnectedEvent += onDisconnected while self._runner: waiter = asyncio.Future() await waiter # soft timeout, probe the app with a historical request self._logger.debug('Soft timeout') self.softTimeoutEvent.emit(self) probe = self.ib.reqHistoricalDataAsync( Forex('EURUSD'), '', '30 S', '5 secs', 'MIDPOINT', False) bars = None with suppress(asyncio.TimeoutError): bars = await asyncio.wait_for(probe, 4) if not bars: self.hardTimeoutEvent.emit(self) raise Warning('Hard timeout') self.ib.setTimeout(self.appTimeout) except ConnectionRefusedError: pass except Warning as w: self._logger.warning(w) except Exception as e: self._logger.exception(e) finally: self.ib.timeoutEvent -= onTimeout self.ib.errorEvent -= onError self.ib.disconnectedEvent -= onDisconnected await self.controller.terminateAsync() self.stoppedEvent.emit(self) if self._runner: await asyncio.sleep(self.retryDelay) if __name__ == '__main__': asyncio.get_event_loop().set_debug(True) util.logToConsole(logging.DEBUG) ibc = IBC(974, gateway=True, tradingMode='paper') # userid='edemo', password='demouser') ib = IB() app = Watchdog(ibc, ib, port=4002, appStartupTime=15, appTimeout=10) app.start() IB.run()
"""Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ import datetime as dt import dateutil.parser as date_parser from dateutil.relativedelta import relativedelta from regolith.helpers.basehelper import DbHelperBase from regolith.fsclient import _id_key from regolith.tools import ( all_docs_from_collection, get_pi_id, ) from gooey import GooeyParser TARGET_COLL = "projecta" def subparser(subpi): date_kwargs = {} if isinstance(subpi, GooeyParser): date_kwargs['widget'] = 'DateChooser' subpi.add_argument("name", help="A short but unique name for the projectum", default=None) subpi.add_argument("lead", help="id of the group lead or tbd", default=None) subpi.add_argument("-d", "--description", help="Slightly longer description of the projectum" ) subpi.add_argument("-c", "--collaborators", nargs="+", help="list of outside collaborator ids separated by spaces, " "'aeinstein efermi'. Builders will get the full names " "from the contacts collection" ) subpi.add_argument("-m", "--group_members", nargs="+", help="list of group member ids, e.g., 'astudent acolleague'. " "Builders will get full names from people collection." "Do not add the lead or the group" "the pi who are added by default." ) subpi.add_argument("-g", "--grants", nargs="+", help="grant or (occasionally) list of grants that support this work" ) subpi.add_argument("-u", "--due_date", help="proposed due date for the deliverable", **date_kwargs ) subpi.add_argument("--checklist", action='store_true', help="Use this to turn the prum into a paper submission" "checklist." ) # Do not delete --database arg subpi.add_argument("--database", help="The database that will be updated. Defaults to " "first database in the regolithrc.json file." ) # Do not delete --date arg subpi.add_argument("--date", help="The begin_date for the projectum Defaults to " "today's date.", **date_kwargs ) return subpi class ProjectumAdderHelper(DbHelperBase): """Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ # btype must be the same as helper target in helper.py btype = "a_projectum" needed_dbs = [f'{TARGET_COLL}', 'groups', 'people'] def construct_global_ctx(self): """Constructs the global context""" super().construct_global_ctx() gtx = self.gtx rc = self.rc rc.pi_id = get_pi_id(rc) rc.coll = f"{TARGET_COLL}" if not rc.database: rc.database = rc.databases[0]["name"] gtx[rc.coll] = sorted( all_docs_from_collection(rc.client, rc.coll), key=_id_key ) gtx["all_docs_from_collection"] = all_docs_from_collection gtx["float"] = float gtx["str"] = str gtx["zip"] = zip def db_updater(self): rc = self.rc if not rc.date: now = dt.date.today() else: now = date_parser.parse(rc.date).date() if not rc.due_date: due_date = now + relativedelta(years=1) else: due_date = date_parser.parse(rc.due_date).date() key = f"{rc.lead[:2]}_{"".join(rc.name.casefold().split()).strip()}" coll = self.gtx[rc.coll] pdocl = list(filter(lambda doc: doc["_id"] == key, coll)) if len(pdocl) > 0: raise RuntimeError( "This entry appears to already exist in the collection") else: pdoc = {} pdoc.update({ 'begin_date': now, 'log_url': '', 'name': rc.name, 'pi_id': rc.pi_id, 'lead': rc.lead, }) if rc.lead == "tbd": pdoc.update({ 'status': 'proposed' }) else: pdoc.update({ 'status': 'started' }) if rc.description: pdoc.update({ 'description': rc.description, }) if rc.grants: if isinstance(rc.grants, str): rc.grants = [rc.grants] pdoc.update({'grants': rc.grants}) else: pdoc.update({'grants': ["tbd"]}) if rc.group_members: if isinstance(rc.group_members, str): rc.group_members = [rc.group_members] pdoc.update({'group_members': rc.group_members}) else: pdoc.update({'group_members': []}) if rc.collaborators: if isinstance(rc.collaborators, str): rc.collaborators = [rc.collaborators] pdoc.update({ 'collaborators': rc.collaborators, }) else: pdoc.update({ 'collaborators': [], }) pdoc.update({"_id": key}) pdoc.update({"deliverable": { "due_date": due_date, "audience": ["beginning grad in chemistry"], "success_def": "audience is happy", "scope": [ "UCs that are supported or some other scope description if it software", "sketch of science story if it is paper"], "platform": "description of how and where the audience will access the deliverable. journal if it is a paper", "roll_out": [ "steps that the audience will take to access and interact with the deliverable", "not needed for paper submissions"], "status": "proposed"} }) pdoc.update({"kickoff": { "due_date": now + relativedelta(days=7), "audience": ["lead", "pi", "group_members"], "name": "Kick off meeting", "objective": "introduce project to the lead", "status": "proposed" }}) secondm = {'due_date': now + relativedelta(days=21), 'name': 'Project lead presentation', 'objective': 'to act as an example milestone. The date is the date it was finished. delete the field until it is finished. In this case, the lead will present what they think is the project after their reading. Add more milestones as needed.', 'audience': ['lead', 'pi', 'group_members'], 'status': 'proposed', 'type': 'meeting' } pdoc.update({"milestones": [secondm]}) if rc.checklist: pdoc = self.insert_checklists(pdoc, now) rc.client.insert_one(rc.database, rc.coll, pdoc) print(f"{key} has been added in {TARGET_COLL}") return def insert_checklists(self, pdoc, now): """Create manuscript checklist, one item as one milestone.""" presubmission_checklist = [ ("Create slide figures", "Create Inkscape graphics (Inkscape is preferrable over ppt) for the slides and place in a ``figures`` directory in the slides directory. These may then be used either in beamer or ppt. Iterate with Simon to convergence. (to get started with Inkscape download and install it, then run the program and navigate to Help-->Tutorials. The first two ('Basic' and 'Shapes') should probably be enough for someone to get basic functionality.)."), ("Create slides", "Create a 'slides' folder in the paper repo or a Google slides deck for a series of talk slides. Iterate the slide skeleton with Simon to convergence. (For a beamer template: https://gitlab.thebillingegroup.com/talks/beamerTalkTemplate)."), ("Create a highlight slide", "Create a 'highlight' folder in the paper repo. Create a single 'highlight' slide that describes the result following NSF/DOE guidelines. Place it in the 'highlight' folder. Iterate with Simon to convergence (highlight templates and examples can be found in https://gitlab.thebillingegroup.com/papers/highlights)"), ("Create public-summary", "Create a public summary in a text file. Place it in the 'highlight' folder. Iterate with Simon to convergence. (The kudos template and example can be found at https://docs.google.com/document/d/1j4ZsM8zS_nZo03s7T48uwzDbh8xTPksAQM3ZLgJ-g-Y/edit?usp=sharing)."), ] submission_checklist = [ ("Check the author list", "Check the author list. Last chance to check for missing authors. Does each author agree to submit to the specific journal? Make sure all authors have approved submission."), ("Check publisher accounts", "Check that all of the authors have accounts for the publisher you are submitting to (if possible) and that they have their ORCID IDs associated with their accounts (ie. for ACS, authors need to link their Paragon accounts with their ORCID IDs)."), ("Check institution", "Is author's name, institution correct? Last chance to avoid embarrassing typos."), ("Check acknowledgement", "Are beamlines, grants, fundings properly acknowledged at the end of the paper? Double check this with Simon and use the ackno statements in the Group Google group."), ("Check figures and tables", "Are all the figures, tables in the paper correct (the ones you intended)?"), ("Check figure captions", "Check the Figure captions for errors. If they refer to a green line, is the relevant line green, and so on."), ("Check figure axis labels", "Check that the figure axis labels are correctly labeled. Make sure it doesn't say G when F is plotted. Make sure the units are correct. Make sure it says 'G (A^-2)' and NOT 'G(r)' (common mistake)."), ("Check table captions", "Check the table caption is correct. Are all the items in the table properly defined in the caption. If it is a crystal structure, are the space group and special positions mentioned in the caption? Is all the info correct?"), ("Check numbers in the table", "Check all the numbers in the tables for errors."), ("Check any question marks", "Check all the question marks in the text. Is there any 'FIG.???' or unrecognized character?"), ("Check figure references", "Check references to the all figures and tables. Does reference to Figure 4 refer to the right figure for example."), ("Check references", "Go through the references and find all the errors. Correct errors in the bibliographic database (citations.yml, or the Zotero collection, for example), not just in the local bib file. Did all the journal names compile correctly? Are they all consistently in abbreviated form (or full form if that is the style, though that is rare). Volume, year and page numbers appear for all references? Hard to find errors in these numbers, but when you do, definitely correct the database!"), ("Check reference style", "Is reference's style in accordance with journal's requirement?"), ("Check journal submission requirements", "Check the journal submission requirements for cover letters, table of contents pictures, list of referees, etc.."), ("Check arxiv", "Check with Simon; will the paper be submitted to arXiv?"), ("Get approval", "Get final approval from all authors for the final version of the manuscript, cover letter, referees list, etc., submission to arXiv if appropriate."), ("Check cover letter", "In the cover letter, does it contain editor-in-chief's name and institution (usually at the top left of the letter) ? Is the content of letter concise and eye-catching? Are (three) suggested reviewers' information in the letter?"), ("Insert bbl", "If it is LaTeX, insert the .bbl file into the main tex file and comment out the \\thebibliography and \\bibliographystyle lines."), ("Commit and push", "Commit all the changes to your local repo, then push the changes to gitlab."), ("Submit to journal", "Go ahead and make the submission, usually online."), ("Push a tag", "If during the submission process you need to make any changes, do it in your local repo and make another commit and push. When the submission is finalized, tag the repo that points to THIS VERSION IS THE SUBMITTED VERSION. create the submission tag. If the current version of your local repo is the submitted version, type, e.g., `git tag -l` to list previous tags (try and keep the tag name formatting consistent) `git tag -a 20180525PRLsubmitted -m <initial submission to PRL>` `git push origin <tag_name>`."), ("Modify tag if needed", "If you forgot to tag and made some changes to the repo and need to point the tag to an earlier version, or want to view all the different tags, or do some other complicated thing, more info about tagging git repos is here: https://git-scm.com/book/en/v2/Git-Basics-Tagging"), ("Submit to arxiv if needed", "Submit to arxiv if appropriate."), ("Push an arxiv tag", "Make a new tag of the version submitted to arXiv with the name arXivSubmitted20170610."), ("Get arxiv reference", "Wait a day to get the full arXiv reference."), ("If submitted to arxiv, enter in citations collection in rg-db-public", "If submit to arxiv, create an entry of the paper in citations.yml at rg-db-public billingeGroup public github repository. Check, double check, and triple check that the tag for the grant is correct and the tags for the facilities are correct. Fill in the arXiv citation information in citations.yml in the bibliography reference. Any questions, ask Simon. Create a PR to merge to the billingeGroup repository."), ("If not submitted to arxiv, enter in citations collection in rg-db-group", "If not submit to arxiv, create an entry of the paper in citations.yml at rg-db-group billingeGroup private github repository. Check, double check, and triple check that the tag for the grant is correct and the tags for the facilities are correct. Any questions, ask Simon. Create a PR to merge to the billingeGroup repository."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace `lyang` with your own name ID in the group) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually. The complied tex and pdf files are located in the `_build` folder. If any problem about installing regolith and databases, please refer to [rg-db-group wiki](https://github.com/Billingegroup/rg-db-group/wiki/Set-up-regolith-and-databases)."), ("Email coauthors", "Send an email to coauthors letting them know the arXiv citation information."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] resubmission_checklist = [ ("Work on the changes", "Make changes to the manuscript in the repo. You don't need to save it to a new name or anything because we can recover the old version by checking out the tagged version."), ("Write rebuttal letter", "Write a proper rebuttal letter based on reviewers' comments and place in the repo. In this letter address all of the referee's points, one by one. Place a copy of the referee's comments in the repo. Give it a unique filename in case there are more referee comments from later submissions!"), ("Check author list", "This is a good time to check that the author list is correct (don't need to add anyone or remove anyone) and that the acknowledgements have been done correctly, the figures are correct, the figure captions and table captions are correct and all the figures and tables are correctly referenced, and there are no compilation errors. Check all references for errors and update any 'unpublished' references if they have been published."), ("Diff the changes", "create a diff.pdf file that shows changes to the manuscript between the version in the tag of the previous submission and the current version, and include this in the resubmission."), ("Send to coauthors", "Send the final version to your coauthors. Tell them you will 'submit on' where is somewhere around 48 hours later and ask for any final corrections etc. from them. Offer them the chance to extend the deadline if they need more time, i.e., write 'if you need more time, lease let me know.' However, it is assumed that all the authors have been involved in the correction process up to this point so they only have to give it one final thought..."), ("Git commit changes", "Commit all the changes to your local repo, then push the changes to gitlab."), ("Resubmit", "Resubmit following the instructions of the journal."), ("Commit any additional changes", "If during the submission process you need to make any changes, do it in your local repo and make another commit and push."), ("Push a resubmission tag", "Make a new resubmission tag (see above for details)"), ("Check db entry", "Check the entry in citations.yml doesn't need to be updated, and update if it does."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] accepted_checklist = [ ("Share the news", "Congratulations on the acceptance of the paper. Let all coauthors know the great news!"), ("Share with BNL if needed", "If it is a BNL paper (check with Simon, but it should acknowledge BNL funding-not just beamtime), send a pdf copy of the accepted version of the paper from the repo to Arlene at BNL to get a BNL publication number. If you are not sure what this means, ask Simon"), ("Share the proof", "When you receive the proofs, share them quickly with all the authors. Request comments back in 24 hours. Proofs should be responded to within 48 hours in normal circumstances."), ("Respond the editor", "Go through and answer any questions from the editor."), ("Check author names", "Last chance to check that all the authors' names are correct and there are no missing authors."), ("Check institutions", "Check all authors' institutions are correct."), ("Check acknowledgement", "Make sure that all funding and all beamlines used are correctly acknowledged. Usually this is done by the bosses, but more eyes catch more mistakes."), ("Update the db entry", "In citations.yml, (the reference should have been added during the submission step) double check the grants{}, facilities{}, nb{} field entries. Any questions, ask Simon. Put 'to be published' in the note{} section. If it has not been submitted to arxiv before, move the entry from rg-db-group to rg-db-public github repo. Otherwise, it should be at rg-db-public already. Create a PR to merge to the billingeGroup repository for edits if necessary."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace lyang with your name) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually. If any problem about installing regolith and databases, please refer to [rg-db-group wiki](https://github.com/Billingegroup/rg-db-group/wiki/Set-up-regolith-and-databases)."), ("Check figures and tables", "Are all the figures, tables in the paper correct (the ones you intended)?"), ("Check the figure caption", "Check the Figure captions for errors. If they refer to a green line, is the relevant line green, and so on."), ("Check figure axis labels", "Check that the figure axis labels are correctly labeled. Make sure it doesn't say G when F is plotted. Make sure the units are correct. Make sure it says 'G (A^-2)' and NOT 'G(r)' (common mistake)"), ("Check table captions", "Check the table caption is correct. Are all the items in the table properly defined in the caption. If it is a crystal structure, are the space group and special positions mentioned in the caption? Is all the info correct?"), ("Check numbers in the table", "Check all the numbers in the tables for errors."), ("Check figure references", "Check references to the all figures and tables. Does reference to Figure 4 refer to the right figure for example"), ("Check references", "Go through the references and find all the errors. Correct errors in the bibliographic database AS WELL AS on the proofs the manuscript. Did all the journal names compile correctly? Are they all consistently in abbreviated form (or full form if that is the style, though that is rare). Volume, year and page numbers appear for all references? Hard to find errors in these numbers, but when you do, definitely correct the database!"), ("Check unpublished references", "If any references are listed as unpublished, on arXiv or submitted or something, check if they have appeared and give the full reference if at all possible. To do this, update the bibliographic database (e.g., citations.yml) with this information and then recompile the references, then copy paste the new bbl file back into the TeX source."), ("Check reference titles if needed", "If the manuscript style has titles in the references, make sure there are no capitalization or other compilation errors. Again, correct these in the database using {braces} around words where you want to preserve the capitalization as well as on the proof."), ("Read the paper", "Finally, after you have done all these 'mechanical' checks, read through the paper and try and find any typos or other problems. Resist the temptation to do any rewriting here...you are looking for mispellings and missing or extra words and so on."), ("Apply corrections from coauthors", "Collect all the corrections from the other authors and add any additional ones to the proof and return it."), ("Email coauthors", "Send an email to your coauthors that this was successfully resubmitted."), ("Revisit talk slides", "Revisit the set of talk slides that summarize the result in a few slides if they need to be updated. Iterate with Simon to convergence."), ("Revisit the highlight slide", "Create a single 'highlight' slide that describes the result following NSF/DOE guidelines. Place it in the 'highlight' folder. Iterate with Simon to convergence (highlight templates and examples can be found in http://gitlab.thebillingegroup.com/highlights/highlightTemplate)"), ("Create web news", "Create a web news story for thebillingegroup.com site. Place it in the 'highlight' folder. Iterate with Simon to convergence"), ("Revisit kudos", "Revisit the Kudos summary if it needs to be updated. Iterate with Simon to convergence."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] published_checklist = [ ("Congrats", "Phew, it is over! Pat yourself on the back and celebrate!"), ("Let coauthors know", "Let your coauthors know the link to the final paper and the final reference."), ("Update db entry", "Update citations.yml at rg-db-public github repo with the correct reference information. Commit your edited citations.yml and create a PR to merge to the billingeGroup repository."), ("Check db entry", "CAREFULLY double and triple check the meta-data associated with the paper in citations.yml:"), ("Check grants in the db entry", "grant{} lists just the billinge-group grants that appeared in the acknowledgement section. They have standard abbreviations that are listed at the top of the citations.yml file, e.g., fwp, EFRC10, etc.. Use the right standard or the whole system becomes broken! If not sure.....ask Simon. List all grants in a comma-separated list."), ("Check the facility in the db entry", "facility{} is every beamline that was used for data collection. Again, use the standard abbreviations at the top of the file. Use two levels of granularity for each, so X17A would be: 'nsls, x17a', if X17A and X7B were used it would be 'nsls, x17a, x7b' and so on."), ("Check the nb in the db entry", "nb is some other tags, also listed at the top of the file. 'art' for a regular article and 'hilite' if it is one of our top top papers are the most common."), ("Check the tags in the db entry", "tags should reflect the content so we can automatically build reading lists by subject. Most papers are PDF papers, so no need to say pdf, be more targeted."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace lyang with your name) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually."), ("Add/update to Zotero", "Add or update the published reference to the billinge-group-bib folder in our group Zotero account"), ("Finalize the highlight slide", "Make a highlight of your work and put it in gitlab/highlights (if not done already during the accepted paper checklist). Look in there for standards to work from. This is an important activity. Now you have done your great work, this is how you can advertise it to others. Top papers we send these highlights to the funding agencies. Iterate the highlight with Simon till it is converged."), ("Finalize figures and talk slides", "Make figures and talk slides that will be used in talks and place these on gitlab on talks/figures. Iterate this with Simon till it is converged."), ("Update arXiv if necessary", "If the paper was listed on a preprint server like arXiv, submit a note to arXiv that the paper has appeared and give the full reference. If the journal copyright allows you can post the published version here, but normally that is not alllowed! Still, it is important that people who find the paper on arXiv get directed to the correct reference."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] checklistm_list = [] checklist_delay_days = [7]*len(presubmission_checklist) + [14]*len(submission_checklist) + [74]*len(resubmission_checklist) + [134]*len(accepted_checklist) + [194]*len(published_checklist) checklist_names = ["presubmission"]*len(presubmission_checklist) + ["submission"]*len(submission_checklist) + ["resubmission"]*len(resubmission_checklist) + ["accepted"]*len(accepted_checklist) + ["published"]*len(published_checklist) checklists = presubmission_checklist + submission_checklist + accepted_checklist + published_checklist for (name, objective), checklist_name, delay_days in zip(checklists, checklist_names, checklist_delay_days): checklistm = {'due_date': now + relativedelta(days=delay_days), 'name': f"{checklist_name} - {name}", 'objective': objective, 'audience': [], 'notes': [], 'status': 'converged', 'type': 'pr' } checklistm_list.append(checklistm) pdoc.update({"milestones": checklistm_list}) # update the deliverable to fit checklist prum pdoc.update({"deliverable": { "due_date": now + relativedelta(days=checklist_delay_days[-1]), "audience": ["simon"], "success_def": "audience is happy", "scope": [ "checklist", "All publication data and metadata are correct and complete"], "platform": "regolith publication collection in rg-db-public", "roll_out": [ "simon merging PRs"], "status": "converged"} }) # update the kickoff to fit checklist prum pdoc.update({"kickoff": { "due_date": now, "audience": ["lead", "pi", "group_members"], "name": "Kick off meeting", "objective": "introduce project to the lead", "status": "finished" }}) return pdoc
"""Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ import datetime as dt import dateutil.parser as date_parser from dateutil.relativedelta import relativedelta from regolith.helpers.basehelper import DbHelperBase from regolith.fsclient import _id_key from regolith.tools import ( all_docs_from_collection, get_pi_id, ) from gooey import GooeyParser TARGET_COLL = "projecta" def subparser(subpi): date_kwargs = {} if isinstance(subpi, GooeyParser): date_kwargs['widget'] = 'DateChooser' subpi.add_argument("name", help="A short but unique name for the projectum", default=None) subpi.add_argument("lead", help="id of the group lead or tbd", default=None) subpi.add_argument("-d", "--description", help="Slightly longer description of the projectum" ) subpi.add_argument("-c", "--collaborators", nargs="+", help="list of outside collaborator ids separated by spaces, " "'aeinstein efermi'. Builders will get the full names " "from the contacts collection" ) subpi.add_argument("-m", "--group_members", nargs="+", help="list of group member ids, e.g., 'astudent acolleague'. " "Builders will get full names from people collection." "Do not add the lead or the group" "the pi who are added by default." ) subpi.add_argument("-g", "--grants", nargs="+", help="grant or (occasionally) list of grants that support this work" ) subpi.add_argument("-u", "--due_date", help="proposed due date for the deliverable", **date_kwargs ) subpi.add_argument("--checklist", action='store_true', help="Use this to turn the prum into a paper submission" "checklist." ) # Do not delete --database arg subpi.add_argument("--database", help="The database that will be updated. Defaults to " "first database in the regolithrc.json file." ) # Do not delete --date arg subpi.add_argument("--date", help="The begin_date for the projectum Defaults to " "today's date.", **date_kwargs ) return subpi class ProjectumAdderHelper(DbHelperBase): """Helper for adding a projectum to the projecta collection. Projecta are small bite-sized project quanta that typically will result in one manuscript. """ # btype must be the same as helper target in helper.py btype = "a_projectum" needed_dbs = [f'{TARGET_COLL}', 'groups', 'people'] def construct_global_ctx(self): """Constructs the global context""" super().construct_global_ctx() gtx = self.gtx rc = self.rc rc.pi_id = get_pi_id(rc) rc.coll = f"{TARGET_COLL}" if not rc.database: rc.database = rc.databases[0]["name"] gtx[rc.coll] = sorted( all_docs_from_collection(rc.client, rc.coll), key=_id_key ) gtx["all_docs_from_collection"] = all_docs_from_collection gtx["float"] = float gtx["str"] = str gtx["zip"] = zip def db_updater(self): rc = self.rc if not rc.date: now = dt.date.today() else: now = date_parser.parse(rc.date).date() if not rc.due_date: due_date = now + relativedelta(years=1) else: due_date = date_parser.parse(rc.due_date).date() key = f"{rc.lead[:2]}_{''.join(rc.name.casefold().split()).strip()}" coll = self.gtx[rc.coll] pdocl = list(filter(lambda doc: doc["_id"] == key, coll)) if len(pdocl) > 0: raise RuntimeError( "This entry appears to already exist in the collection") else: pdoc = {} pdoc.update({ 'begin_date': now, 'log_url': '', 'name': rc.name, 'pi_id': rc.pi_id, 'lead': rc.lead, }) if rc.lead == "tbd": pdoc.update({ 'status': 'proposed' }) else: pdoc.update({ 'status': 'started' }) if rc.description: pdoc.update({ 'description': rc.description, }) if rc.grants: if isinstance(rc.grants, str): rc.grants = [rc.grants] pdoc.update({'grants': rc.grants}) else: pdoc.update({'grants': ["tbd"]}) if rc.group_members: if isinstance(rc.group_members, str): rc.group_members = [rc.group_members] pdoc.update({'group_members': rc.group_members}) else: pdoc.update({'group_members': []}) if rc.collaborators: if isinstance(rc.collaborators, str): rc.collaborators = [rc.collaborators] pdoc.update({ 'collaborators': rc.collaborators, }) else: pdoc.update({ 'collaborators': [], }) pdoc.update({"_id": key}) pdoc.update({"deliverable": { "due_date": due_date, "audience": ["beginning grad in chemistry"], "success_def": "audience is happy", "scope": [ "UCs that are supported or some other scope description if it software", "sketch of science story if it is paper"], "platform": "description of how and where the audience will access the deliverable. journal if it is a paper", "roll_out": [ "steps that the audience will take to access and interact with the deliverable", "not needed for paper submissions"], "status": "proposed"} }) pdoc.update({"kickoff": { "due_date": now + relativedelta(days=7), "audience": ["lead", "pi", "group_members"], "name": "Kick off meeting", "objective": "introduce project to the lead", "status": "proposed" }}) secondm = {'due_date': now + relativedelta(days=21), 'name': 'Project lead presentation', 'objective': 'to act as an example milestone. The date is the date it was finished. delete the field until it is finished. In this case, the lead will present what they think is the project after their reading. Add more milestones as needed.', 'audience': ['lead', 'pi', 'group_members'], 'status': 'proposed', 'type': 'meeting' } pdoc.update({"milestones": [secondm]}) if rc.checklist: pdoc = self.insert_checklists(pdoc, now) rc.client.insert_one(rc.database, rc.coll, pdoc) print(f"{key} has been added in {TARGET_COLL}") return def insert_checklists(self, pdoc, now): """Create manuscript checklist, one item as one milestone.""" presubmission_checklist = [ ("Create slide figures", "Create Inkscape graphics (Inkscape is preferrable over ppt) for the slides and place in a ``figures`` directory in the slides directory. These may then be used either in beamer or ppt. Iterate with Simon to convergence. (to get started with Inkscape download and install it, then run the program and navigate to Help-->Tutorials. The first two ('Basic' and 'Shapes') should probably be enough for someone to get basic functionality.)."), ("Create slides", "Create a 'slides' folder in the paper repo or a Google slides deck for a series of talk slides. Iterate the slide skeleton with Simon to convergence. (For a beamer template: https://gitlab.thebillingegroup.com/talks/beamerTalkTemplate)."), ("Create a highlight slide", "Create a 'highlight' folder in the paper repo. Create a single 'highlight' slide that describes the result following NSF/DOE guidelines. Place it in the 'highlight' folder. Iterate with Simon to convergence (highlight templates and examples can be found in https://gitlab.thebillingegroup.com/papers/highlights)"), ("Create public-summary", "Create a public summary in a text file. Place it in the 'highlight' folder. Iterate with Simon to convergence. (The kudos template and example can be found at https://docs.google.com/document/d/1j4ZsM8zS_nZo03s7T48uwzDbh8xTPksAQM3ZLgJ-g-Y/edit?usp=sharing)."), ] submission_checklist = [ ("Check the author list", "Check the author list. Last chance to check for missing authors. Does each author agree to submit to the specific journal? Make sure all authors have approved submission."), ("Check publisher accounts", "Check that all of the authors have accounts for the publisher you are submitting to (if possible) and that they have their ORCID IDs associated with their accounts (ie. for ACS, authors need to link their Paragon accounts with their ORCID IDs)."), ("Check institution", "Is author's name, institution correct? Last chance to avoid embarrassing typos."), ("Check acknowledgement", "Are beamlines, grants, fundings properly acknowledged at the end of the paper? Double check this with Simon and use the ackno statements in the Group Google group."), ("Check figures and tables", "Are all the figures, tables in the paper correct (the ones you intended)?"), ("Check figure captions", "Check the Figure captions for errors. If they refer to a green line, is the relevant line green, and so on."), ("Check figure axis labels", "Check that the figure axis labels are correctly labeled. Make sure it doesn't say G when F is plotted. Make sure the units are correct. Make sure it says 'G (A^-2)' and NOT 'G(r)' (common mistake)."), ("Check table captions", "Check the table caption is correct. Are all the items in the table properly defined in the caption. If it is a crystal structure, are the space group and special positions mentioned in the caption? Is all the info correct?"), ("Check numbers in the table", "Check all the numbers in the tables for errors."), ("Check any question marks", "Check all the question marks in the text. Is there any 'FIG.???' or unrecognized character?"), ("Check figure references", "Check references to the all figures and tables. Does reference to Figure 4 refer to the right figure for example."), ("Check references", "Go through the references and find all the errors. Correct errors in the bibliographic database (citations.yml, or the Zotero collection, for example), not just in the local bib file. Did all the journal names compile correctly? Are they all consistently in abbreviated form (or full form if that is the style, though that is rare). Volume, year and page numbers appear for all references? Hard to find errors in these numbers, but when you do, definitely correct the database!"), ("Check reference style", "Is reference's style in accordance with journal's requirement?"), ("Check journal submission requirements", "Check the journal submission requirements for cover letters, table of contents pictures, list of referees, etc.."), ("Check arxiv", "Check with Simon; will the paper be submitted to arXiv?"), ("Get approval", "Get final approval from all authors for the final version of the manuscript, cover letter, referees list, etc., submission to arXiv if appropriate."), ("Check cover letter", "In the cover letter, does it contain editor-in-chief's name and institution (usually at the top left of the letter) ? Is the content of letter concise and eye-catching? Are (three) suggested reviewers' information in the letter?"), ("Insert bbl", "If it is LaTeX, insert the .bbl file into the main tex file and comment out the \\thebibliography and \\bibliographystyle lines."), ("Commit and push", "Commit all the changes to your local repo, then push the changes to gitlab."), ("Submit to journal", "Go ahead and make the submission, usually online."), ("Push a tag", "If during the submission process you need to make any changes, do it in your local repo and make another commit and push. When the submission is finalized, tag the repo that points to THIS VERSION IS THE SUBMITTED VERSION. create the submission tag. If the current version of your local repo is the submitted version, type, e.g., `git tag -l` to list previous tags (try and keep the tag name formatting consistent) `git tag -a 20180525PRLsubmitted -m <initial submission to PRL>` `git push origin <tag_name>`."), ("Modify tag if needed", "If you forgot to tag and made some changes to the repo and need to point the tag to an earlier version, or want to view all the different tags, or do some other complicated thing, more info about tagging git repos is here: https://git-scm.com/book/en/v2/Git-Basics-Tagging"), ("Submit to arxiv if needed", "Submit to arxiv if appropriate."), ("Push an arxiv tag", "Make a new tag of the version submitted to arXiv with the name arXivSubmitted20170610."), ("Get arxiv reference", "Wait a day to get the full arXiv reference."), ("If submitted to arxiv, enter in citations collection in rg-db-public", "If submit to arxiv, create an entry of the paper in citations.yml at rg-db-public billingeGroup public github repository. Check, double check, and triple check that the tag for the grant is correct and the tags for the facilities are correct. Fill in the arXiv citation information in citations.yml in the bibliography reference. Any questions, ask Simon. Create a PR to merge to the billingeGroup repository."), ("If not submitted to arxiv, enter in citations collection in rg-db-group", "If not submit to arxiv, create an entry of the paper in citations.yml at rg-db-group billingeGroup private github repository. Check, double check, and triple check that the tag for the grant is correct and the tags for the facilities are correct. Any questions, ask Simon. Create a PR to merge to the billingeGroup repository."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace `lyang` with your own name ID in the group) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually. The complied tex and pdf files are located in the `_build` folder. If any problem about installing regolith and databases, please refer to [rg-db-group wiki](https://github.com/Billingegroup/rg-db-group/wiki/Set-up-regolith-and-databases)."), ("Email coauthors", "Send an email to coauthors letting them know the arXiv citation information."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] resubmission_checklist = [ ("Work on the changes", "Make changes to the manuscript in the repo. You don't need to save it to a new name or anything because we can recover the old version by checking out the tagged version."), ("Write rebuttal letter", "Write a proper rebuttal letter based on reviewers' comments and place in the repo. In this letter address all of the referee's points, one by one. Place a copy of the referee's comments in the repo. Give it a unique filename in case there are more referee comments from later submissions!"), ("Check author list", "This is a good time to check that the author list is correct (don't need to add anyone or remove anyone) and that the acknowledgements have been done correctly, the figures are correct, the figure captions and table captions are correct and all the figures and tables are correctly referenced, and there are no compilation errors. Check all references for errors and update any 'unpublished' references if they have been published."), ("Diff the changes", "create a diff.pdf file that shows changes to the manuscript between the version in the tag of the previous submission and the current version, and include this in the resubmission."), ("Send to coauthors", "Send the final version to your coauthors. Tell them you will 'submit on' where is somewhere around 48 hours later and ask for any final corrections etc. from them. Offer them the chance to extend the deadline if they need more time, i.e., write 'if you need more time, lease let me know.' However, it is assumed that all the authors have been involved in the correction process up to this point so they only have to give it one final thought..."), ("Git commit changes", "Commit all the changes to your local repo, then push the changes to gitlab."), ("Resubmit", "Resubmit following the instructions of the journal."), ("Commit any additional changes", "If during the submission process you need to make any changes, do it in your local repo and make another commit and push."), ("Push a resubmission tag", "Make a new resubmission tag (see above for details)"), ("Check db entry", "Check the entry in citations.yml doesn't need to be updated, and update if it does."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] accepted_checklist = [ ("Share the news", "Congratulations on the acceptance of the paper. Let all coauthors know the great news!"), ("Share with BNL if needed", "If it is a BNL paper (check with Simon, but it should acknowledge BNL funding-not just beamtime), send a pdf copy of the accepted version of the paper from the repo to Arlene at BNL to get a BNL publication number. If you are not sure what this means, ask Simon"), ("Share the proof", "When you receive the proofs, share them quickly with all the authors. Request comments back in 24 hours. Proofs should be responded to within 48 hours in normal circumstances."), ("Respond the editor", "Go through and answer any questions from the editor."), ("Check author names", "Last chance to check that all the authors' names are correct and there are no missing authors."), ("Check institutions", "Check all authors' institutions are correct."), ("Check acknowledgement", "Make sure that all funding and all beamlines used are correctly acknowledged. Usually this is done by the bosses, but more eyes catch more mistakes."), ("Update the db entry", "In citations.yml, (the reference should have been added during the submission step) double check the grants{}, facilities{}, nb{} field entries. Any questions, ask Simon. Put 'to be published' in the note{} section. If it has not been submitted to arxiv before, move the entry from rg-db-group to rg-db-public github repo. Otherwise, it should be at rg-db-public already. Create a PR to merge to the billingeGroup repository for edits if necessary."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace lyang with your name) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually. If any problem about installing regolith and databases, please refer to [rg-db-group wiki](https://github.com/Billingegroup/rg-db-group/wiki/Set-up-regolith-and-databases)."), ("Check figures and tables", "Are all the figures, tables in the paper correct (the ones you intended)?"), ("Check the figure caption", "Check the Figure captions for errors. If they refer to a green line, is the relevant line green, and so on."), ("Check figure axis labels", "Check that the figure axis labels are correctly labeled. Make sure it doesn't say G when F is plotted. Make sure the units are correct. Make sure it says 'G (A^-2)' and NOT 'G(r)' (common mistake)"), ("Check table captions", "Check the table caption is correct. Are all the items in the table properly defined in the caption. If it is a crystal structure, are the space group and special positions mentioned in the caption? Is all the info correct?"), ("Check numbers in the table", "Check all the numbers in the tables for errors."), ("Check figure references", "Check references to the all figures and tables. Does reference to Figure 4 refer to the right figure for example"), ("Check references", "Go through the references and find all the errors. Correct errors in the bibliographic database AS WELL AS on the proofs the manuscript. Did all the journal names compile correctly? Are they all consistently in abbreviated form (or full form if that is the style, though that is rare). Volume, year and page numbers appear for all references? Hard to find errors in these numbers, but when you do, definitely correct the database!"), ("Check unpublished references", "If any references are listed as unpublished, on arXiv or submitted or something, check if they have appeared and give the full reference if at all possible. To do this, update the bibliographic database (e.g., citations.yml) with this information and then recompile the references, then copy paste the new bbl file back into the TeX source."), ("Check reference titles if needed", "If the manuscript style has titles in the references, make sure there are no capitalization or other compilation errors. Again, correct these in the database using {braces} around words where you want to preserve the capitalization as well as on the proof."), ("Read the paper", "Finally, after you have done all these 'mechanical' checks, read through the paper and try and find any typos or other problems. Resist the temptation to do any rewriting here...you are looking for mispellings and missing or extra words and so on."), ("Apply corrections from coauthors", "Collect all the corrections from the other authors and add any additional ones to the proof and return it."), ("Email coauthors", "Send an email to your coauthors that this was successfully resubmitted."), ("Revisit talk slides", "Revisit the set of talk slides that summarize the result in a few slides if they need to be updated. Iterate with Simon to convergence."), ("Revisit the highlight slide", "Create a single 'highlight' slide that describes the result following NSF/DOE guidelines. Place it in the 'highlight' folder. Iterate with Simon to convergence (highlight templates and examples can be found in http://gitlab.thebillingegroup.com/highlights/highlightTemplate)"), ("Create web news", "Create a web news story for thebillingegroup.com site. Place it in the 'highlight' folder. Iterate with Simon to convergence"), ("Revisit kudos", "Revisit the Kudos summary if it needs to be updated. Iterate with Simon to convergence."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] published_checklist = [ ("Congrats", "Phew, it is over! Pat yourself on the back and celebrate!"), ("Let coauthors know", "Let your coauthors know the link to the final paper and the final reference."), ("Update db entry", "Update citations.yml at rg-db-public github repo with the correct reference information. Commit your edited citations.yml and create a PR to merge to the billingeGroup repository."), ("Check db entry", "CAREFULLY double and triple check the meta-data associated with the paper in citations.yml:"), ("Check grants in the db entry", "grant{} lists just the billinge-group grants that appeared in the acknowledgement section. They have standard abbreviations that are listed at the top of the citations.yml file, e.g., fwp, EFRC10, etc.. Use the right standard or the whole system becomes broken! If not sure.....ask Simon. List all grants in a comma-separated list."), ("Check the facility in the db entry", "facility{} is every beamline that was used for data collection. Again, use the standard abbreviations at the top of the file. Use two levels of granularity for each, so X17A would be: 'nsls, x17a', if X17A and X7B were used it would be 'nsls, x17a, x7b' and so on."), ("Check the nb in the db entry", "nb is some other tags, also listed at the top of the file. 'art' for a regular article and 'hilite' if it is one of our top top papers are the most common."), ("Check the tags in the db entry", "tags should reflect the content so we can automatically build reading lists by subject. Most papers are PDF papers, so no need to say pdf, be more targeted."), ("Check db errors", "In your rg-db-public/local directory, run `regolith build publist --people lyang` (replace lyang with your name) to make sure that you publist is building properly. Make sure that the publication appears correctly with no errors and fix anything. If there are problems with the latex building, run the commands with --no-pdf, which yields the latex source but doesn't build it, then build the latex manually."), ("Add/update to Zotero", "Add or update the published reference to the billinge-group-bib folder in our group Zotero account"), ("Finalize the highlight slide", "Make a highlight of your work and put it in gitlab/highlights (if not done already during the accepted paper checklist). Look in there for standards to work from. This is an important activity. Now you have done your great work, this is how you can advertise it to others. Top papers we send these highlights to the funding agencies. Iterate the highlight with Simon till it is converged."), ("Finalize figures and talk slides", "Make figures and talk slides that will be used in talks and place these on gitlab on talks/figures. Iterate this with Simon till it is converged."), ("Update arXiv if necessary", "If the paper was listed on a preprint server like arXiv, submit a note to arXiv that the paper has appeared and give the full reference. If the journal copyright allows you can post the published version here, but normally that is not alllowed! Still, it is important that people who find the paper on arXiv get directed to the correct reference."), ("Ask Simon if anything unfinished", "Ask Simon about any items unfinished."), ("Email Simon", "Email Simon if finish the above."), ] checklistm_list = [] checklist_delay_days = [7]*len(presubmission_checklist) + [14]*len(submission_checklist) + [74]*len(resubmission_checklist) + [134]*len(accepted_checklist) + [194]*len(published_checklist) checklist_names = ["presubmission"]*len(presubmission_checklist) + ["submission"]*len(submission_checklist) + ["resubmission"]*len(resubmission_checklist) + ["accepted"]*len(accepted_checklist) + ["published"]*len(published_checklist) checklists = presubmission_checklist + submission_checklist + accepted_checklist + published_checklist for (name, objective), checklist_name, delay_days in zip(checklists, checklist_names, checklist_delay_days): checklistm = {'due_date': now + relativedelta(days=delay_days), 'name': f"{checklist_name} - {name}", 'objective': objective, 'audience': [], 'notes': [], 'status': 'converged', 'type': 'pr' } checklistm_list.append(checklistm) pdoc.update({"milestones": checklistm_list}) # update the deliverable to fit checklist prum pdoc.update({"deliverable": { "due_date": now + relativedelta(days=checklist_delay_days[-1]), "audience": ["simon"], "success_def": "audience is happy", "scope": [ "checklist", "All publication data and metadata are correct and complete"], "platform": "regolith publication collection in rg-db-public", "roll_out": [ "simon merging PRs"], "status": "converged"} }) # update the kickoff to fit checklist prum pdoc.update({"kickoff": { "due_date": now, "audience": ["lead", "pi", "group_members"], "name": "Kick off meeting", "objective": "introduce project to the lead", "status": "finished" }}) return pdoc
from bilibili import bilibili from statistics import Statistics import printer from printer import Printer import rafflehandler from configloader import ConfigLoader import utils import asyncio import struct import json import sys import aiohttp class BaseDanmu(): __slots__ = ('ws', 'roomid', 'area_id', 'client') structer = struct.Struct('!I2H2I') def __init__(self, roomid=None, area_id=None): self.client = aiohttp.ClientSession() if roomid is None: self.roomid = ConfigLoader().dic_user['other_control']['default_monitor_roomid'] self.area_id = 0 else: self.roomid = roomid self.area_id = area_id # 待确认 async def close_connection(self): try: await self.ws.close() except: print('请联系开发者', sys.exc_info()[0], sys.exc_info()[1]) printer.info([f'{self.area_id}号弹幕收尾模块状态{self.ws.closed}'], True) async def CheckArea(self): try: while True: area_id = await asyncio.shield(utils.FetchRoomArea(self.roomid)) if area_id != self.area_id: printer.info([f'{self.roomid}更换分区{self.area_id}为{area_id},即将切换房间'], True) return await asyncio.sleep(300) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控分区检测模块主动取消'], True) async def connectServer(self): try: url = 'wss://broadcastlv.chat.bilibili.com:443/sub' self.ws = await asyncio.wait_for(self.client.ws_connect(url), timeout=3) except: print("# 连接无法建立,请检查本地网络状况") print(sys.exc_info()[0], sys.exc_info()[1]) return False printer.info([f'{self.area_id}号弹幕监控已连接b站服务器'], True) body = f'{{'uid':0,'roomid':{self.roomid},"protover":1,"platform":"web","clientver":"1.3.3"}}' return (await self.SendSocketData(opt=7, body=body)) async def HeartbeatLoop(self): printer.info([f'{self.area_id}号弹幕监控开始心跳(心跳间隔30s,后续不再提示)'], True) try: while True: if not (await self.SendSocketData(opt=2, body='')): return await asyncio.sleep(30) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控心跳模块主动取消'], True) async def SendSocketData(self, opt, body, len_header=16, ver=1, seq=1): remain_data = body.encode('utf-8') len_data = len(remain_data) + len_header header = self.structer.pack(len_data, len_header, ver, opt, seq) data = header + remain_data try: await self.ws.send_bytes(data) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控发送模块主动取消'], True) return False except: print(sys.exc_info()[0], sys.exc_info()[1]) return False return True async def ReadSocketData(self): bytes_data = None try: msg = await asyncio.wait_for(self.ws.receive(), timeout=35.0) bytes_data = msg.data except asyncio.TimeoutError: print('# 由于心跳包30s一次,但是发现35内没有收到任何包,说明已经悄悄失联了,主动断开') return None except: print(sys.exc_info()[0], sys.exc_info()[1]) print('请联系开发者') return None return bytes_data async def ReceiveMessageLoop(self): while True: bytes_datas = await self.ReadSocketData() if bytes_datas is None: break len_read = 0 len_bytes_datas = len(bytes_datas) loop_time = 0 while len_read != len_bytes_datas: loop_time += 1 if loop_time > 100: print('请联系作者', bytes_datas) state = None split_header = self.structer.unpack(bytes_datas[len_read:16+len_read]) len_data, len_header, ver, opt, seq = split_header remain_data = bytes_datas[len_read+16:len_read+len_data] # 人气值/心跳 3s间隔 if opt == 3: # self._UserCount, = struct.unpack('!I', remain_data) printer.debug(f'弹幕心跳检测{self.area_id}') # cmd elif opt == 5: messages = remain_data.decode('utf-8') dic = json.loads(messages) state = await self.handle_danmu(dic) # 握手确认 elif opt == 8: printer.info([f'{self.area_id}号弹幕监控进入房间({self.roomid})'], True) else: printer.warn(bytes_datas[len_read:len_read + len_data]) if state is not None and not state: return len_read += len_data async def handle_danmu(self, dic): await asyncio.sleep(0) return True class DanmuPrinter(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': # print(dic) Printer().print_danmu(dic) return class DanmuRaffleHandler(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] if cmd == 'PREPARING': printer.info([f'{self.area_id}号弹幕监控房间下播({self.roomid})'], True) return False elif cmd == 'SYS_GIFT': if 'giftId' in dic: if dic['giftId'] == 39: printer.info(["节奏风暴"], True) roomid = dic['roomid'] rafflehandler.Rafflehandler.Put2Queue((roomid,), rafflehandler.handle_1_room_storm) Statistics.append2pushed_raffle('节奏风暴', area_id=self.area_id) else: text1 = dic['real_roomid'] text2 = dic['url'] printer.info([dic, "请联系开发者"]) try: giftId = dic['giftId'] printer.info(["检测到房间{:^9}的{}活动抽奖".format(text1, bilibili.get_giftids_raffle(str(giftId)))], True) rafflehandler.Rafflehandler.Put2Queue((giftId, text1, text2), rafflehandler.handle_1_room_activity) Statistics.append2pushed_raffle('活动', area_id=self.area_id) except: printer.info([dic, "请联系开发者"]) else: printer.info(['普通送礼提示', dic['msg_text']]) return elif cmd == 'SYS_MSG': if 'real_roomid' in dic: real_roomid = dic['real_roomid'] type_text = (dic['msg'].split(':?')[-1]).split(',')[0][2:] printer.info([f'{self.area_id}号弹幕监控检测到{real_roomid:^9}的{type_text}'], True) rafflehandler.Rafflehandler.Put2Queue((real_roomid,), rafflehandler.handle_1_room_TV) rafflehandler.Rafflehandler.Put2Queue((real_roomid,), rafflehandler.handle_1_room_activity) Statistics.append2pushed_raffle(type_text, area_id=self.area_id) elif cmd == 'GUARD_MSG': if 'buy_type' in dic and dic['buy_type'] == 1: roomid = dic['roomid'] printer.info([f'{self.area_id}号弹幕监控检测到{roomid:^9}的总督'], True) rafflehandler.Rafflehandler.Put2Queue((roomid,), rafflehandler.handle_1_room_guard) Statistics.append2pushed_raffle('总督', area_id=self.area_id) if 'buy_type' in dic and dic['buy_type'] != 1: print(dic) # roomid = dic['roomid'] printer.info([f'{self.area_id}号弹幕监控检测到{self.roomid:^9}的提督/舰长'], True) rafflehandler.Rafflehandler.Put2Queue((self.roomid,), rafflehandler.handle_1_room_guard) Statistics.append2pushed_raffle('提督/舰长', area_id=self.area_id) class YjMonitorHandler(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': msg = dic['info'][1] if '-' in msg: list_word = msg.split('-') try: roomid = int(list_word[0]) raffleid = int(list_word[1]) printer.info([f'弹幕监控检测到{roomid:^9}的提督/舰长{raffleid}'], True) rafflehandler.Rafflehandler.Put2Queue((1, roomid, raffleid), rafflehandler.handle_1_guard_raffle) Statistics.append2pushed_raffle('提督/舰长', area_id=1) except ValueError: print(msg) Printer().print_danmu(dic)
from bilibili import bilibili from statistics import Statistics import printer from printer import Printer import rafflehandler from configloader import ConfigLoader import utils import asyncio import struct import json import sys import aiohttp class BaseDanmu(): __slots__ = ('ws', 'roomid', 'area_id', 'client') structer = struct.Struct('!I2H2I') def __init__(self, roomid=None, area_id=None): self.client = aiohttp.ClientSession() if roomid is None: self.roomid = ConfigLoader().dic_user['other_control']['default_monitor_roomid'] self.area_id = 0 else: self.roomid = roomid self.area_id = area_id # 待确认 async def close_connection(self): try: await self.ws.close() except: print('请联系开发者', sys.exc_info()[0], sys.exc_info()[1]) printer.info([f'{self.area_id}号弹幕收尾模块状态{self.ws.closed}'], True) async def CheckArea(self): try: while True: area_id = await asyncio.shield(utils.FetchRoomArea(self.roomid)) if area_id != self.area_id: printer.info([f'{self.roomid}更换分区{self.area_id}为{area_id},即将切换房间'], True) return await asyncio.sleep(300) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控分区检测模块主动取消'], True) async def connectServer(self): try: url = 'wss://broadcastlv.chat.bilibili.com:443/sub' self.ws = await asyncio.wait_for(self.client.ws_connect(url), timeout=3) except: print("# 连接无法建立,请检查本地网络状况") print(sys.exc_info()[0], sys.exc_info()[1]) return False printer.info([f'{self.area_id}号弹幕监控已连接b站服务器'], True) body = f'{{"uid":0,"roomid":{self.roomid},"protover":1,"platform":"web","clientver":"1.3.3"}}' return (await self.SendSocketData(opt=7, body=body)) async def HeartbeatLoop(self): printer.info([f'{self.area_id}号弹幕监控开始心跳(心跳间隔30s,后续不再提示)'], True) try: while True: if not (await self.SendSocketData(opt=2, body='')): return await asyncio.sleep(30) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控心跳模块主动取消'], True) async def SendSocketData(self, opt, body, len_header=16, ver=1, seq=1): remain_data = body.encode('utf-8') len_data = len(remain_data) + len_header header = self.structer.pack(len_data, len_header, ver, opt, seq) data = header + remain_data try: await self.ws.send_bytes(data) except asyncio.CancelledError: printer.info([f'{self.area_id}号弹幕监控发送模块主动取消'], True) return False except: print(sys.exc_info()[0], sys.exc_info()[1]) return False return True async def ReadSocketData(self): bytes_data = None try: msg = await asyncio.wait_for(self.ws.receive(), timeout=35.0) bytes_data = msg.data except asyncio.TimeoutError: print('# 由于心跳包30s一次,但是发现35内没有收到任何包,说明已经悄悄失联了,主动断开') return None except: print(sys.exc_info()[0], sys.exc_info()[1]) print('请联系开发者') return None return bytes_data async def ReceiveMessageLoop(self): while True: bytes_datas = await self.ReadSocketData() if bytes_datas is None: break len_read = 0 len_bytes_datas = len(bytes_datas) loop_time = 0 while len_read != len_bytes_datas: loop_time += 1 if loop_time > 100: print('请联系作者', bytes_datas) state = None split_header = self.structer.unpack(bytes_datas[len_read:16+len_read]) len_data, len_header, ver, opt, seq = split_header remain_data = bytes_datas[len_read+16:len_read+len_data] # 人气值/心跳 3s间隔 if opt == 3: # self._UserCount, = struct.unpack('!I', remain_data) printer.debug(f'弹幕心跳检测{self.area_id}') # cmd elif opt == 5: messages = remain_data.decode('utf-8') dic = json.loads(messages) state = await self.handle_danmu(dic) # 握手确认 elif opt == 8: printer.info([f'{self.area_id}号弹幕监控进入房间({self.roomid})'], True) else: printer.warn(bytes_datas[len_read:len_read + len_data]) if state is not None and not state: return len_read += len_data async def handle_danmu(self, dic): await asyncio.sleep(0) return True class DanmuPrinter(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': # print(dic) Printer().print_danmu(dic) return class DanmuRaffleHandler(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] if cmd == 'PREPARING': printer.info([f'{self.area_id}号弹幕监控房间下播({self.roomid})'], True) return False elif cmd == 'SYS_GIFT': if 'giftId' in dic: if dic['giftId'] == 39: printer.info(["节奏风暴"], True) roomid = dic['roomid'] rafflehandler.Rafflehandler.Put2Queue((roomid,), rafflehandler.handle_1_room_storm) Statistics.append2pushed_raffle('节奏风暴', area_id=self.area_id) else: text1 = dic['real_roomid'] text2 = dic['url'] printer.info([dic, "请联系开发者"]) try: giftId = dic['giftId'] printer.info(["检测到房间{:^9}的{}活动抽奖".format(text1, bilibili.get_giftids_raffle(str(giftId)))], True) rafflehandler.Rafflehandler.Put2Queue((giftId, text1, text2), rafflehandler.handle_1_room_activity) Statistics.append2pushed_raffle('活动', area_id=self.area_id) except: printer.info([dic, "请联系开发者"]) else: printer.info(['普通送礼提示', dic['msg_text']]) return elif cmd == 'SYS_MSG': if 'real_roomid' in dic: real_roomid = dic['real_roomid'] type_text = (dic['msg'].split(':?')[-1]).split(',')[0][2:] printer.info([f'{self.area_id}号弹幕监控检测到{real_roomid:^9}的{type_text}'], True) rafflehandler.Rafflehandler.Put2Queue((real_roomid,), rafflehandler.handle_1_room_TV) rafflehandler.Rafflehandler.Put2Queue((real_roomid,), rafflehandler.handle_1_room_activity) Statistics.append2pushed_raffle(type_text, area_id=self.area_id) elif cmd == 'GUARD_MSG': if 'buy_type' in dic and dic['buy_type'] == 1: roomid = dic['roomid'] printer.info([f'{self.area_id}号弹幕监控检测到{roomid:^9}的总督'], True) rafflehandler.Rafflehandler.Put2Queue((roomid,), rafflehandler.handle_1_room_guard) Statistics.append2pushed_raffle('总督', area_id=self.area_id) if 'buy_type' in dic and dic['buy_type'] != 1: print(dic) # roomid = dic['roomid'] printer.info([f'{self.area_id}号弹幕监控检测到{self.roomid:^9}的提督/舰长'], True) rafflehandler.Rafflehandler.Put2Queue((self.roomid,), rafflehandler.handle_1_room_guard) Statistics.append2pushed_raffle('提督/舰长', area_id=self.area_id) class YjMonitorHandler(BaseDanmu): def handle_danmu(self, dic): cmd = dic['cmd'] # print(cmd) if cmd == 'DANMU_MSG': msg = dic['info'][1] if '-' in msg: list_word = msg.split('-') try: roomid = int(list_word[0]) raffleid = int(list_word[1]) printer.info([f'弹幕监控检测到{roomid:^9}的提督/舰长{raffleid}'], True) rafflehandler.Rafflehandler.Put2Queue((1, roomid, raffleid), rafflehandler.handle_1_guard_raffle) Statistics.append2pushed_raffle('提督/舰长', area_id=1) except ValueError: print(msg) Printer().print_danmu(dic)
import datetime import discord from discord.ext import commands from discord.ext.commands import Bot, Context from tortoise.functions import Sum import config from db.models.stats import Stats from db.models.user import User from db.redis import RedisDB from models.command import CommandInfo from rpc.client import RPCClient from util.discord.channel import ChannelUtil from util.discord.messages import Messages from util.env import Env ## Command documentation TIPSTATS_INFO = CommandInfo( triggers = ["tipstats"], overview = "Display your personal tipping stats for a specific server.", details = f"This will display your personal tipping statistics from the server you send the command from. This command can't be used in DM" ) TOPTIPS_INFO = CommandInfo( triggers = ["toptips"], overview = "Display biggest tips for a specific server.", details = f"This will display the biggest tip of all time, of the current month, and of the day for the current server. This command can't be used in DM" ) LEADERBOARD_INFO = CommandInfo( triggers = ["ballers", "leaderboard"], overview = "Show a list of the top 15 tippers this year.", details = f"This will display a list of the top 15 tippers on the current server. This command can't be used in DM\n" + f"These stats are reset once a year - for all time stats use `{config.Config.instance().command_prefix}legacyboard`" ) LEGACYBOARD_INFO = CommandInfo( triggers = ["legacyboard", "oldballs"], overview = "Show a list of the top 15 tippers all time.", details = f"This will display a list of the top 15 tippers of all time on the current server. This command can't be used in DM" ) class StatsCog(commands.Cog): def __init__(self, bot: Bot): self.bot = bot async def cog_before_invoke(self, ctx: Context): ctx.error = False # Only allow tip commands in public channels msg = ctx.message if ChannelUtil.is_private(msg.channel) and ctx.command.name != 'blocks_cmd': await Messages.send_error_dm(msg.author, "You can only view statistics in a server, not via DM.") ctx.error = True return else: # Determine if user is admin ctx.god = msg.author.id in config.Config.instance().get_admin_ids() if not ctx.god: ctx.admin = False for g in self.bot.guilds: member = g.get_member(msg.author.id) if member is not None: for role in member.roles: if role.id in config.Config.instance().get_admin_roles(): ctx.admin = True break if ctx.admin: break else: ctx.admin = True # Can't spam stats commands if msg.channel.id in config.Config.instance().get_no_spam_channels(): ctx.error = True await Messages.send_error_dm(msg.author, "I can't post stats in that channel.") return if ctx.command.name in ['tipstats_cmd']: # Make sure user exists in DB user = await User.get_user(msg.author) if user is None: ctx.error = True await Messages.send_error_dm(msg.author, f"You should create an account with me first, send me `{config.Config.instance().command_prefix}help` to get started.") return # Update name, if applicable await user.update_name(msg.author.name) ctx.user = user @commands.command(aliases=TIPSTATS_INFO.triggers) async def tipstats_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message user: User = ctx.user if not ctx.god and await RedisDB.instance().exists(f"tipstatsspam{msg.author.id}{msg.guild.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before trying to get your tipstats again") return stats: Stats = await user.get_stats(server_id=msg.guild.id) if stats.banned: await Messages.add_x_reaction(msg) await Messages.send_error_dm(msg.author, "You are stats banned, contact an admin if you want to be unbanned") return response = "" if stats is None or stats.total_tips == 0: response = f"<@{msg.author.id}> You haven't sent any tips in this server yet, tip some people and then check your stats later" else: response = f"<@{msg.author.id}> You have sent **{stats.total_tips}** tips totaling **{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}**. Your biggest tip of all time is **{Env.format_float(stats.top_tip)} {Env.currency_symbol()}**" await msg.channel.send(response) await RedisDB.instance().set(f"tipstatsspam{msg.author.id}{msg.guild.id}", "as", expires=300) @commands.command(aliases=TOPTIPS_INFO.triggers) async def toptips_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"toptipsspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) return # This would be better to be 1 query but, i'm not proficient enough with tortoise-orm top_tip = await Stats.filter( server_id=msg.guild.id, banned=False ).order_by('-top_tip').prefetch_related('user').limit(1).first() if top_tip is None: await RedisDB.instance().set(f"toptipsspam{msg.channel.id}", "as", expires=300) await msg.channel.send("There are no stats for this server yet. Send some tips first!") return # Get datetime object representing first day of this month now = datetime.datetime.utcnow() month = str(now.month).zfill(2) year = now.year first_day_of_month = datetime.datetime.strptime(f'{month}/01/{year} 00:00:00', '%m/%d/%Y %H:%M:%S') # Find top tip of the month top_tip_month = await Stats.filter( server_id=msg.guild.id, top_tip_month_at__gte=first_day_of_month, banned=False ).order_by('-top_tip_month').prefetch_related('user').limit(1).first() # Get datetime object representing 24 hours ago past_24h = now - datetime.timedelta(hours=24) # Find top tip of the month top_tip_day = await Stats.filter( server_id=msg.guild.id, top_tip_day_at__gte=past_24h, banned=False ).order_by('-top_tip_day').prefetch_related('user').limit(1).first() embed = discord.Embed(colour=0xC6E459) embed.set_author(name='Biggest Tips', icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") new_line = '\n' # Can't use this directly inside f-expression, so store it in a variable if top_tip_day is not None: embed.description = f"**Last 24 Hours**\n```{Env.format_float(top_tip_day.top_tip_day)} {Env.currency_symbol()} - by {top_tip_day.user.name}```" if top_tip_month is not None: embed.description += f"{new_line if top_tip_day is not None else ""}**In {now.strftime("%B")}**\n```{Env.format_float(top_tip_month.top_tip_month)} {Env.currency_symbol()} - by {top_tip_month.user.name}```" embed.description += f"{new_line if top_tip_day is not None or top_tip_month is not None else ""}**All Time**\n```{Env.format_float(top_tip.top_tip)} {Env.currency_symbol()} - by {top_tip.user.name}```" # No spam await RedisDB.instance().set(f"toptipsspam{msg.channel.id}", "as", expires=300) await msg.channel.send(embed=embed) @commands.command(aliases=LEADERBOARD_INFO.triggers) async def leaderboard_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"ballerspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the ballers list again") return # Get list ballers = await Stats.filter(server_id=msg.guild.id, banned=False).order_by('-total_tipped_amount').prefetch_related('user').limit(15).all() if len(ballers) == 0: await msg.channel.send(f"<@{msg.author.id}> There are no stats for this server yet, send some tips!") return response_msg = "```" # Get biggest tip to adjust the padding biggest_num = 0 for stats in ballers: length = len(f"{Env.format_float(stats.total_tipped_amount)} {Env.currency_symbol()}") if length > biggest_num: biggest_num = length for rank, stats in enumerate(ballers, start=1): adj_rank = str(rank) if rank >= 10 else f" {rank}" user_name = stats.user.name amount_str = f"{Env.format_float(stats.total_tipped_amount)} {Env.currency_symbol()}" response_msg += f"{adj_rank}. {amount_str.ljust(biggest_num)} - by {user_name}\n" response_msg += "```" embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here are the top {len(ballers)} tippers \U0001F44F", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = response_msg embed.set_footer(text=f"Use {config.Config.instance().command_prefix}legacyboard for all-time stats") await RedisDB.instance().set(f"ballerspam{msg.channel.id}", "as", expires=300) await msg.channel.send(f"<@{msg.author.id}>", embed=embed) @commands.command(aliases=LEGACYBOARD_INFO.triggers) async def legacyboard_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"ballerspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the ballers list again") return # Get list ballers = await Stats.filter(server_id=msg.guild.id, banned=False).order_by('-legacy_total_tipped_amount').prefetch_related('user').limit(15).all() if len(ballers) == 0: await msg.channel.send(f"<@{msg.author.id}> There are no stats for this server yet, send some tips!") return response_msg = "```" # Get biggest tip to adjust the padding biggest_num = 0 for stats in ballers: # TODO change to stats.tip_sum length = len(f"{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}") if length > biggest_num: biggest_num = length for rank, stats in enumerate(ballers, start=1): adj_rank = str(rank) if rank >= 10 else f" {rank}" user_name = stats.user.name amount_str = f"{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}" response_msg += f"{adj_rank}. {amount_str.ljust(biggest_num)} - by {user_name}\n" response_msg += "```" embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here are the top {len(ballers)} tippers of all time\U0001F44F", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = response_msg await RedisDB.instance().set(f"ballerspam{msg.channel.id}", "as", expires=300) await msg.channel.send(f"<@{msg.author.id}>", embed=embed) @commands.command(aliases=["blocks"]) async def blocks_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message is_private = ChannelUtil.is_private(msg.channel) if not ctx.god and await RedisDB.instance().exists(f"blocksspam{msg.channel.id if not is_private else msg.author.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the block count again?") return count, unchecked = await RPCClient.instance().block_count() if count is None or unchecked is None: await Messages.send_error_dm(msg.author, "I couldn't retrieve the current block count") return embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here's how many blocks I have", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = f"```Count: {count:,}\nUnchecked: {unchecked:,}```" await RedisDB.instance().set(f"blocksspam{msg.channel.id if not is_private else msg.author.id}", "as", expires=120) if is_private: await msg.author.send(embed=embed) else: await msg.channel.send(f"<@{msg.author.id}>", embed=embed)
import datetime import discord from discord.ext import commands from discord.ext.commands import Bot, Context from tortoise.functions import Sum import config from db.models.stats import Stats from db.models.user import User from db.redis import RedisDB from models.command import CommandInfo from rpc.client import RPCClient from util.discord.channel import ChannelUtil from util.discord.messages import Messages from util.env import Env ## Command documentation TIPSTATS_INFO = CommandInfo( triggers = ["tipstats"], overview = "Display your personal tipping stats for a specific server.", details = f"This will display your personal tipping statistics from the server you send the command from. This command can't be used in DM" ) TOPTIPS_INFO = CommandInfo( triggers = ["toptips"], overview = "Display biggest tips for a specific server.", details = f"This will display the biggest tip of all time, of the current month, and of the day for the current server. This command can't be used in DM" ) LEADERBOARD_INFO = CommandInfo( triggers = ["ballers", "leaderboard"], overview = "Show a list of the top 15 tippers this year.", details = f"This will display a list of the top 15 tippers on the current server. This command can't be used in DM\n" + f"These stats are reset once a year - for all time stats use `{config.Config.instance().command_prefix}legacyboard`" ) LEGACYBOARD_INFO = CommandInfo( triggers = ["legacyboard", "oldballs"], overview = "Show a list of the top 15 tippers all time.", details = f"This will display a list of the top 15 tippers of all time on the current server. This command can't be used in DM" ) class StatsCog(commands.Cog): def __init__(self, bot: Bot): self.bot = bot async def cog_before_invoke(self, ctx: Context): ctx.error = False # Only allow tip commands in public channels msg = ctx.message if ChannelUtil.is_private(msg.channel) and ctx.command.name != 'blocks_cmd': await Messages.send_error_dm(msg.author, "You can only view statistics in a server, not via DM.") ctx.error = True return else: # Determine if user is admin ctx.god = msg.author.id in config.Config.instance().get_admin_ids() if not ctx.god: ctx.admin = False for g in self.bot.guilds: member = g.get_member(msg.author.id) if member is not None: for role in member.roles: if role.id in config.Config.instance().get_admin_roles(): ctx.admin = True break if ctx.admin: break else: ctx.admin = True # Can't spam stats commands if msg.channel.id in config.Config.instance().get_no_spam_channels(): ctx.error = True await Messages.send_error_dm(msg.author, "I can't post stats in that channel.") return if ctx.command.name in ['tipstats_cmd']: # Make sure user exists in DB user = await User.get_user(msg.author) if user is None: ctx.error = True await Messages.send_error_dm(msg.author, f"You should create an account with me first, send me `{config.Config.instance().command_prefix}help` to get started.") return # Update name, if applicable await user.update_name(msg.author.name) ctx.user = user @commands.command(aliases=TIPSTATS_INFO.triggers) async def tipstats_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message user: User = ctx.user if not ctx.god and await RedisDB.instance().exists(f"tipstatsspam{msg.author.id}{msg.guild.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before trying to get your tipstats again") return stats: Stats = await user.get_stats(server_id=msg.guild.id) if stats.banned: await Messages.add_x_reaction(msg) await Messages.send_error_dm(msg.author, "You are stats banned, contact an admin if you want to be unbanned") return response = "" if stats is None or stats.total_tips == 0: response = f"<@{msg.author.id}> You haven't sent any tips in this server yet, tip some people and then check your stats later" else: response = f"<@{msg.author.id}> You have sent **{stats.total_tips}** tips totaling **{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}**. Your biggest tip of all time is **{Env.format_float(stats.top_tip)} {Env.currency_symbol()}**" await msg.channel.send(response) await RedisDB.instance().set(f"tipstatsspam{msg.author.id}{msg.guild.id}", "as", expires=300) @commands.command(aliases=TOPTIPS_INFO.triggers) async def toptips_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"toptipsspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) return # This would be better to be 1 query but, i'm not proficient enough with tortoise-orm top_tip = await Stats.filter( server_id=msg.guild.id, banned=False ).order_by('-top_tip').prefetch_related('user').limit(1).first() if top_tip is None: await RedisDB.instance().set(f"toptipsspam{msg.channel.id}", "as", expires=300) await msg.channel.send("There are no stats for this server yet. Send some tips first!") return # Get datetime object representing first day of this month now = datetime.datetime.utcnow() month = str(now.month).zfill(2) year = now.year first_day_of_month = datetime.datetime.strptime(f'{month}/01/{year} 00:00:00', '%m/%d/%Y %H:%M:%S') # Find top tip of the month top_tip_month = await Stats.filter( server_id=msg.guild.id, top_tip_month_at__gte=first_day_of_month, banned=False ).order_by('-top_tip_month').prefetch_related('user').limit(1).first() # Get datetime object representing 24 hours ago past_24h = now - datetime.timedelta(hours=24) # Find top tip of the month top_tip_day = await Stats.filter( server_id=msg.guild.id, top_tip_day_at__gte=past_24h, banned=False ).order_by('-top_tip_day').prefetch_related('user').limit(1).first() embed = discord.Embed(colour=0xC6E459) embed.set_author(name='Biggest Tips', icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") new_line = '\n' # Can't use this directly inside f-expression, so store it in a variable if top_tip_day is not None: embed.description = f"**Last 24 Hours**\n```{Env.format_float(top_tip_day.top_tip_day)} {Env.currency_symbol()} - by {top_tip_day.user.name}```" if top_tip_month is not None: embed.description += f"{new_line if top_tip_day is not None else ''}**In {now.strftime('%B')}**\n```{Env.format_float(top_tip_month.top_tip_month)} {Env.currency_symbol()} - by {top_tip_month.user.name}```" embed.description += f"{new_line if top_tip_day is not None or top_tip_month is not None else ''}**All Time**\n```{Env.format_float(top_tip.top_tip)} {Env.currency_symbol()} - by {top_tip.user.name}```" # No spam await RedisDB.instance().set(f"toptipsspam{msg.channel.id}", "as", expires=300) await msg.channel.send(embed=embed) @commands.command(aliases=LEADERBOARD_INFO.triggers) async def leaderboard_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"ballerspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the ballers list again") return # Get list ballers = await Stats.filter(server_id=msg.guild.id, banned=False).order_by('-total_tipped_amount').prefetch_related('user').limit(15).all() if len(ballers) == 0: await msg.channel.send(f"<@{msg.author.id}> There are no stats for this server yet, send some tips!") return response_msg = "```" # Get biggest tip to adjust the padding biggest_num = 0 for stats in ballers: length = len(f"{Env.format_float(stats.total_tipped_amount)} {Env.currency_symbol()}") if length > biggest_num: biggest_num = length for rank, stats in enumerate(ballers, start=1): adj_rank = str(rank) if rank >= 10 else f" {rank}" user_name = stats.user.name amount_str = f"{Env.format_float(stats.total_tipped_amount)} {Env.currency_symbol()}" response_msg += f"{adj_rank}. {amount_str.ljust(biggest_num)} - by {user_name}\n" response_msg += "```" embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here are the top {len(ballers)} tippers \U0001F44F", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = response_msg embed.set_footer(text=f"Use {config.Config.instance().command_prefix}legacyboard for all-time stats") await RedisDB.instance().set(f"ballerspam{msg.channel.id}", "as", expires=300) await msg.channel.send(f"<@{msg.author.id}>", embed=embed) @commands.command(aliases=LEGACYBOARD_INFO.triggers) async def legacyboard_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message if not ctx.god and await RedisDB.instance().exists(f"ballerspam{msg.channel.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the ballers list again") return # Get list ballers = await Stats.filter(server_id=msg.guild.id, banned=False).order_by('-legacy_total_tipped_amount').prefetch_related('user').limit(15).all() if len(ballers) == 0: await msg.channel.send(f"<@{msg.author.id}> There are no stats for this server yet, send some tips!") return response_msg = "```" # Get biggest tip to adjust the padding biggest_num = 0 for stats in ballers: # TODO change to stats.tip_sum length = len(f"{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}") if length > biggest_num: biggest_num = length for rank, stats in enumerate(ballers, start=1): adj_rank = str(rank) if rank >= 10 else f" {rank}" user_name = stats.user.name amount_str = f"{Env.format_float(stats.legacy_total_tipped_amount)} {Env.currency_symbol()}" response_msg += f"{adj_rank}. {amount_str.ljust(biggest_num)} - by {user_name}\n" response_msg += "```" embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here are the top {len(ballers)} tippers of all time\U0001F44F", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = response_msg await RedisDB.instance().set(f"ballerspam{msg.channel.id}", "as", expires=300) await msg.channel.send(f"<@{msg.author.id}>", embed=embed) @commands.command(aliases=["blocks"]) async def blocks_cmd(self, ctx: Context): if ctx.error: await Messages.add_x_reaction(ctx.message) return msg = ctx.message is_private = ChannelUtil.is_private(msg.channel) if not ctx.god and await RedisDB.instance().exists(f"blocksspam{msg.channel.id if not is_private else msg.author.id}"): await Messages.add_timer_reaction(msg) await Messages.send_error_dm(msg.author, "Why don't you wait awhile before checking the block count again?") return count, unchecked = await RPCClient.instance().block_count() if count is None or unchecked is None: await Messages.send_error_dm(msg.author, "I couldn't retrieve the current block count") return embed = discord.Embed(colour=0xC6E459) embed.set_author(name=f"Here's how many blocks I have", icon_url="https://github.com/AnanosCommunity/graham_discord_bot/raw/master/assets/ananos_logo.png") embed.description = f"```Count: {count:,}\nUnchecked: {unchecked:,}```" await RedisDB.instance().set(f"blocksspam{msg.channel.id if not is_private else msg.author.id}", "as", expires=120) if is_private: await msg.author.send(embed=embed) else: await msg.channel.send(f"<@{msg.author.id}>", embed=embed)
def topla(a, b): return a + b print(topla(2, 3)) topla2 = lambda a, b: a + b print(topla2(2, 3)) def listeyiGoster(liste, gosteriFonksiyonu): for i in liste: print(gosteriFonksiyonu(i)) list = [ {"id": 1, "ad": "Alper", "soyad": "Konuralp" }, {"id": 2, "ad": "Burcu", "soyad": "Konuralp"}, {"id": 3, "ad": "Yağmur", "soyad": "Konuralp"}, ] listeyiGoster(list, lambda satir: f"{satir["ad"]} {satir["soyad"]}")
def topla(a, b): return a + b print(topla(2, 3)) topla2 = lambda a, b: a + b print(topla2(2, 3)) def listeyiGoster(liste, gosteriFonksiyonu): for i in liste: print(gosteriFonksiyonu(i)) list = [ {"id": 1, "ad": "Alper", "soyad": "Konuralp" }, {"id": 2, "ad": "Burcu", "soyad": "Konuralp"}, {"id": 3, "ad": "Yağmur", "soyad": "Konuralp"}, ] listeyiGoster(list, lambda satir: f"{satir['ad']} {satir['soyad']}")
from contextlib import closing import json import logging import boto3 from lambda_logs import JSONFormatter, custom_lambda_logs logger = logging.getLogger() logger.setLevel(logging.INFO) logger.handlers[0].setFormatter(JSONFormatter()) class QCFailed(Exception): def __init__(self, message: str): self.message = message def lambda_handler(event: dict, context: object): with custom_lambda_logs(**event["logging"]): logger.info(f"event: {str(event)}") s3_path = f"{event["repo"]}/{event["qc_result_file"]}" bucket, key = s3_path.split("/", 3)[2:] s3 = boto3.client("s3") response = s3.get_object(Bucket=bucket, Key=key) with closing(response["Body"]) as fp: qc_object = json.load(fp) logger.info(f"input: {str(qc_object)}") result = eval(event["qc_expression"], globals(), qc_object) if result: logger.warning("failed QC check") sfn = boto3.client("stepfunctions") sfn.stop_execution( executionArn=event["execution_id"], error=f"Job {event["logging"]["job_file_key"]} failed QC check at step {event["logging"]["step_name"]}", cause=f"failed condition: {event["qc_expression"]}" ) raise QCFailed(f"QC check failed ({event["qc_expression"]})") else: logger.info("passed QC check")
from contextlib import closing import json import logging import boto3 from lambda_logs import JSONFormatter, custom_lambda_logs logger = logging.getLogger() logger.setLevel(logging.INFO) logger.handlers[0].setFormatter(JSONFormatter()) class QCFailed(Exception): def __init__(self, message: str): self.message = message def lambda_handler(event: dict, context: object): with custom_lambda_logs(**event["logging"]): logger.info(f"event: {str(event)}") s3_path = f"{event['repo']}/{event['qc_result_file']}" bucket, key = s3_path.split("/", 3)[2:] s3 = boto3.client("s3") response = s3.get_object(Bucket=bucket, Key=key) with closing(response["Body"]) as fp: qc_object = json.load(fp) logger.info(f"input: {str(qc_object)}") result = eval(event["qc_expression"], globals(), qc_object) if result: logger.warning("failed QC check") sfn = boto3.client("stepfunctions") sfn.stop_execution( executionArn=event["execution_id"], error=f"Job {event['logging']['job_file_key']} failed QC check at step {event['logging']['step_name']}", cause=f"failed condition: {event['qc_expression']}" ) raise QCFailed(f"QC check failed ({event['qc_expression']})") else: logger.info("passed QC check")
#!/usr/bin/env python3 import copy import difflib import logging from pathlib import Path from typing import Dict, Optional, Union import click import requests import rich import toml from packaging.specifiers import Specifier from packaging.version import Version from rich.logging import RichHandler from rich.syntax import Syntax from cibuildwheel.extra import InlineArrayDictEncoder from cibuildwheel.typing import Final, Literal, TypedDict log = logging.getLogger("cibw") # Looking up the dir instead of using utils.resources_dir # since we want to write to it. DIR: Final[Path] = Path(__file__).parent.parent.resolve() RESOURCES_DIR: Final[Path] = DIR / "cibuildwheel/resources" ArchStr = Literal["32", "64"] class ConfigWinCP(TypedDict): identifier: str version: str arch: str class ConfigWinPP(TypedDict): identifier: str version: str arch: str url: str class ConfigMacOS(TypedDict): identifier: str version: str url: str AnyConfig = Union[ConfigWinCP, ConfigWinPP, ConfigMacOS] # The following set of "Versions" classes allow the initial call to the APIs to # be cached and reused in the `update_version_*` methods. class WindowsVersions: def __init__(self, arch_str: ArchStr) -> None: response = requests.get("https://api.nuget.org/v3/index.json") response.raise_for_status() api_info = response.json() for resource in api_info["resources"]: if resource["@type"] == "PackageBaseAddress/3.0.0": endpoint = resource["@id"] ARCH_DICT = {"32": "win32", "64": "win_amd64"} PACKAGE_DICT = {"32": "pythonx86", "64": "python"} self.arch_str = arch_str self.arch = ARCH_DICT[arch_str] package = PACKAGE_DICT[arch_str] response = requests.get(f"{endpoint}{package}/index.json") response.raise_for_status() cp_info = response.json() versions = (Version(v) for v in cp_info["versions"]) self.versions = sorted(v for v in versions if not v.is_devrelease) def update_version_windows(self, spec: Specifier) -> Optional[ConfigWinCP]: versions = sorted(v for v in self.versions if spec.contains(v)) if not all(v.is_prerelease for v in versions): versions = [v for v in versions if not v.is_prerelease] log.debug(f"Windows {self.arch} {spec} has {", ".join(str(v) for v in versions)}") if not versions: return None version = versions[-1] identifier = f"cp{version.major}{version.minor}-{self.arch}" result = ConfigWinCP( identifier=identifier, version=str(version), arch=self.arch_str, ) return result class PyPyVersions: def __init__(self, arch_str: ArchStr): response = requests.get("https://downloads.python.org/pypy/versions.json") response.raise_for_status() releases = [r for r in response.json() if r["pypy_version"] != "nightly"] for release in releases: release["pypy_version"] = Version(release["pypy_version"]) release["python_version"] = Version(release["python_version"]) self.releases = [ r for r in releases if not r["pypy_version"].is_prerelease and not r["pypy_version"].is_devrelease ] self.arch = arch_str def update_version_windows(self, spec: Specifier) -> ConfigWinCP: if self.arch != "32": raise RuntimeError("64 bit releases not supported yet on Windows") releases = [r for r in self.releases if spec.contains(r["python_version"])] releases = sorted(releases, key=lambda r: r["pypy_version"]) if not releases: raise RuntimeError(f"PyPy Win {self.arch} not found for {spec}! {self.releases}") release = releases[-1] version = release["python_version"] identifier = f"pp{version.major}{version.minor}-win32" (url,) = [rf["download_url"] for rf in release["files"] if "" in rf["platform"] == "win32"] return ConfigWinPP( identifier=identifier, version=f"{version.major}.{version.minor}", arch="32", url=url, ) def update_version_macos(self, spec: Specifier) -> ConfigMacOS: if self.arch != "64": raise RuntimeError("Other archs not supported yet on macOS") releases = [r for r in self.releases if spec.contains(r["python_version"])] releases = sorted(releases, key=lambda r: r["pypy_version"]) if not releases: raise RuntimeError(f"PyPy macOS {self.arch} not found for {spec}!") release = releases[-1] version = release["python_version"] identifier = f"pp{version.major}{version.minor}-macosx_x86_64" (url,) = [ rf["download_url"] for rf in release["files"] if "" in rf["platform"] == "darwin" and rf["arch"] == "x64" ] return ConfigMacOS( identifier=identifier, version=f"{version.major}.{version.minor}", url=url, ) class CPythonVersions: def __init__(self) -> None: response = requests.get("https://www.python.org/api/v2/downloads/release/?is_published=true") response.raise_for_status() releases_info = response.json() self.versions_dict: Dict[Version, int] = {} for release in releases_info: # Removing the prefix, Python 3.9 would use: release["name"].removeprefix("Python ") version = Version(release["name"][7:]) if not version.is_prerelease and not version.is_devrelease: uri = int(release["resource_uri"].rstrip("/").split("/")[-1]) self.versions_dict[version] = uri def update_version_macos(self, identifier: str, spec: Specifier) -> Optional[ConfigMacOS]: file_idents = ("macos11.0.pkg", "macosx10.9.pkg", "macosx10.6.pkg") sorted_versions = sorted(v for v in self.versions_dict if spec.contains(v)) for version in reversed(sorted_versions): # Find the first patch version that contains the requested file uri = self.versions_dict[version] response = requests.get(f"https://www.python.org/api/v2/downloads/release_file/?release={uri}") response.raise_for_status() file_info = response.json() for file_ident in file_idents: urls = [rf["url"] for rf in file_info if file_ident in rf["url"]] if urls: return ConfigMacOS( identifier=identifier, version=f"{version.major}.{version.minor}", url=urls[0], ) return None # This is a universal interface to all the above Versions classes. Given an # identifier, it updates a config dict. class AllVersions: def __init__(self) -> None: self.windows_32 = WindowsVersions("32") self.windows_64 = WindowsVersions("64") self.windows_pypy = PyPyVersions("32") self.macos_cpython = CPythonVersions() self.macos_pypy = PyPyVersions("64") def update_config(self, config: Dict[str, str]) -> None: identifier = config["identifier"] version = Version(config["version"]) spec = Specifier(f"=={version.major}.{version.minor}.*") log.info(f"Reading in '{identifier}' -> {spec} @ {version}") orig_config = copy.copy(config) config_update: Optional[AnyConfig] # We need to use ** in update due to MyPy (probably a bug) if "macos" in identifier: if identifier.startswith("pp"): config_update = self.macos_pypy.update_version_macos(spec) else: config_update = self.macos_cpython.update_version_macos(identifier, spec) assert config_update is not None, f"MacOS {spec} not found!" config.update(**config_update) elif "win32" in identifier: if identifier.startswith("pp"): config.update(**self.windows_pypy.update_version_windows(spec)) else: config_update = self.windows_32.update_version_windows(spec) if config_update: config.update(**config_update) elif "win_amd64" in identifier: config_update = self.windows_64.update_version_windows(spec) if config_update: config.update(**config_update) if config != orig_config: log.info(f" Updated {orig_config} to {config}") @click.command() @click.option("--force", is_flag=True) @click.option("--level", default="INFO", type=click.Choice(["INFO", "DEBUG", "TRACE"], case_sensitive=False)) def update_pythons(force: bool, level: str) -> None: logging.basicConfig( level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, markup=True)], ) log.setLevel(level) all_versions = AllVersions() toml_file_path = RESOURCES_DIR / "build-platforms.toml" original_toml = toml_file_path.read_text() configs = toml.loads(original_toml) for config in configs["windows"]["python_configurations"]: all_versions.update_config(config) for config in configs["macos"]["python_configurations"]: all_versions.update_config(config) result_toml = toml.dumps(configs, encoder=InlineArrayDictEncoder()) # type: ignore rich.print() # spacer if original_toml == result_toml: rich.print("[green]Check complete, Python configurations unchanged.") return rich.print("Python configurations updated.") rich.print("Changes:") rich.print() toml_relpath = toml_file_path.relative_to(DIR).as_posix() diff_lines = difflib.unified_diff( original_toml.splitlines(keepends=True), result_toml.splitlines(keepends=True), fromfile=toml_relpath, tofile=toml_relpath, ) rich.print(Syntax("".join(diff_lines), "diff", theme="ansi_light")) rich.print() if force: toml_file_path.write_text(result_toml) rich.print("[green]TOML file updated.") else: rich.print("[yellow]File left unchanged. Use --force flag to update.") if __name__ == "__main__": update_pythons()
#!/usr/bin/env python3 import copy import difflib import logging from pathlib import Path from typing import Dict, Optional, Union import click import requests import rich import toml from packaging.specifiers import Specifier from packaging.version import Version from rich.logging import RichHandler from rich.syntax import Syntax from cibuildwheel.extra import InlineArrayDictEncoder from cibuildwheel.typing import Final, Literal, TypedDict log = logging.getLogger("cibw") # Looking up the dir instead of using utils.resources_dir # since we want to write to it. DIR: Final[Path] = Path(__file__).parent.parent.resolve() RESOURCES_DIR: Final[Path] = DIR / "cibuildwheel/resources" ArchStr = Literal["32", "64"] class ConfigWinCP(TypedDict): identifier: str version: str arch: str class ConfigWinPP(TypedDict): identifier: str version: str arch: str url: str class ConfigMacOS(TypedDict): identifier: str version: str url: str AnyConfig = Union[ConfigWinCP, ConfigWinPP, ConfigMacOS] # The following set of "Versions" classes allow the initial call to the APIs to # be cached and reused in the `update_version_*` methods. class WindowsVersions: def __init__(self, arch_str: ArchStr) -> None: response = requests.get("https://api.nuget.org/v3/index.json") response.raise_for_status() api_info = response.json() for resource in api_info["resources"]: if resource["@type"] == "PackageBaseAddress/3.0.0": endpoint = resource["@id"] ARCH_DICT = {"32": "win32", "64": "win_amd64"} PACKAGE_DICT = {"32": "pythonx86", "64": "python"} self.arch_str = arch_str self.arch = ARCH_DICT[arch_str] package = PACKAGE_DICT[arch_str] response = requests.get(f"{endpoint}{package}/index.json") response.raise_for_status() cp_info = response.json() versions = (Version(v) for v in cp_info["versions"]) self.versions = sorted(v for v in versions if not v.is_devrelease) def update_version_windows(self, spec: Specifier) -> Optional[ConfigWinCP]: versions = sorted(v for v in self.versions if spec.contains(v)) if not all(v.is_prerelease for v in versions): versions = [v for v in versions if not v.is_prerelease] log.debug(f"Windows {self.arch} {spec} has {', '.join(str(v) for v in versions)}") if not versions: return None version = versions[-1] identifier = f"cp{version.major}{version.minor}-{self.arch}" result = ConfigWinCP( identifier=identifier, version=str(version), arch=self.arch_str, ) return result class PyPyVersions: def __init__(self, arch_str: ArchStr): response = requests.get("https://downloads.python.org/pypy/versions.json") response.raise_for_status() releases = [r for r in response.json() if r["pypy_version"] != "nightly"] for release in releases: release["pypy_version"] = Version(release["pypy_version"]) release["python_version"] = Version(release["python_version"]) self.releases = [ r for r in releases if not r["pypy_version"].is_prerelease and not r["pypy_version"].is_devrelease ] self.arch = arch_str def update_version_windows(self, spec: Specifier) -> ConfigWinCP: if self.arch != "32": raise RuntimeError("64 bit releases not supported yet on Windows") releases = [r for r in self.releases if spec.contains(r["python_version"])] releases = sorted(releases, key=lambda r: r["pypy_version"]) if not releases: raise RuntimeError(f"PyPy Win {self.arch} not found for {spec}! {self.releases}") release = releases[-1] version = release["python_version"] identifier = f"pp{version.major}{version.minor}-win32" (url,) = [rf["download_url"] for rf in release["files"] if "" in rf["platform"] == "win32"] return ConfigWinPP( identifier=identifier, version=f"{version.major}.{version.minor}", arch="32", url=url, ) def update_version_macos(self, spec: Specifier) -> ConfigMacOS: if self.arch != "64": raise RuntimeError("Other archs not supported yet on macOS") releases = [r for r in self.releases if spec.contains(r["python_version"])] releases = sorted(releases, key=lambda r: r["pypy_version"]) if not releases: raise RuntimeError(f"PyPy macOS {self.arch} not found for {spec}!") release = releases[-1] version = release["python_version"] identifier = f"pp{version.major}{version.minor}-macosx_x86_64" (url,) = [ rf["download_url"] for rf in release["files"] if "" in rf["platform"] == "darwin" and rf["arch"] == "x64" ] return ConfigMacOS( identifier=identifier, version=f"{version.major}.{version.minor}", url=url, ) class CPythonVersions: def __init__(self) -> None: response = requests.get("https://www.python.org/api/v2/downloads/release/?is_published=true") response.raise_for_status() releases_info = response.json() self.versions_dict: Dict[Version, int] = {} for release in releases_info: # Removing the prefix, Python 3.9 would use: release["name"].removeprefix("Python ") version = Version(release["name"][7:]) if not version.is_prerelease and not version.is_devrelease: uri = int(release["resource_uri"].rstrip("/").split("/")[-1]) self.versions_dict[version] = uri def update_version_macos(self, identifier: str, spec: Specifier) -> Optional[ConfigMacOS]: file_idents = ("macos11.0.pkg", "macosx10.9.pkg", "macosx10.6.pkg") sorted_versions = sorted(v for v in self.versions_dict if spec.contains(v)) for version in reversed(sorted_versions): # Find the first patch version that contains the requested file uri = self.versions_dict[version] response = requests.get(f"https://www.python.org/api/v2/downloads/release_file/?release={uri}") response.raise_for_status() file_info = response.json() for file_ident in file_idents: urls = [rf["url"] for rf in file_info if file_ident in rf["url"]] if urls: return ConfigMacOS( identifier=identifier, version=f"{version.major}.{version.minor}", url=urls[0], ) return None # This is a universal interface to all the above Versions classes. Given an # identifier, it updates a config dict. class AllVersions: def __init__(self) -> None: self.windows_32 = WindowsVersions("32") self.windows_64 = WindowsVersions("64") self.windows_pypy = PyPyVersions("32") self.macos_cpython = CPythonVersions() self.macos_pypy = PyPyVersions("64") def update_config(self, config: Dict[str, str]) -> None: identifier = config["identifier"] version = Version(config["version"]) spec = Specifier(f"=={version.major}.{version.minor}.*") log.info(f"Reading in '{identifier}' -> {spec} @ {version}") orig_config = copy.copy(config) config_update: Optional[AnyConfig] # We need to use ** in update due to MyPy (probably a bug) if "macos" in identifier: if identifier.startswith("pp"): config_update = self.macos_pypy.update_version_macos(spec) else: config_update = self.macos_cpython.update_version_macos(identifier, spec) assert config_update is not None, f"MacOS {spec} not found!" config.update(**config_update) elif "win32" in identifier: if identifier.startswith("pp"): config.update(**self.windows_pypy.update_version_windows(spec)) else: config_update = self.windows_32.update_version_windows(spec) if config_update: config.update(**config_update) elif "win_amd64" in identifier: config_update = self.windows_64.update_version_windows(spec) if config_update: config.update(**config_update) if config != orig_config: log.info(f" Updated {orig_config} to {config}") @click.command() @click.option("--force", is_flag=True) @click.option("--level", default="INFO", type=click.Choice(["INFO", "DEBUG", "TRACE"], case_sensitive=False)) def update_pythons(force: bool, level: str) -> None: logging.basicConfig( level="INFO", format="%(message)s", datefmt="[%X]", handlers=[RichHandler(rich_tracebacks=True, markup=True)], ) log.setLevel(level) all_versions = AllVersions() toml_file_path = RESOURCES_DIR / "build-platforms.toml" original_toml = toml_file_path.read_text() configs = toml.loads(original_toml) for config in configs["windows"]["python_configurations"]: all_versions.update_config(config) for config in configs["macos"]["python_configurations"]: all_versions.update_config(config) result_toml = toml.dumps(configs, encoder=InlineArrayDictEncoder()) # type: ignore rich.print() # spacer if original_toml == result_toml: rich.print("[green]Check complete, Python configurations unchanged.") return rich.print("Python configurations updated.") rich.print("Changes:") rich.print() toml_relpath = toml_file_path.relative_to(DIR).as_posix() diff_lines = difflib.unified_diff( original_toml.splitlines(keepends=True), result_toml.splitlines(keepends=True), fromfile=toml_relpath, tofile=toml_relpath, ) rich.print(Syntax("".join(diff_lines), "diff", theme="ansi_light")) rich.print() if force: toml_file_path.write_text(result_toml) rich.print("[green]TOML file updated.") else: rich.print("[yellow]File left unchanged. Use --force flag to update.") if __name__ == "__main__": update_pythons()
import logging from binascii import hexlify from pprint import pformat from lntenna.bitcoin import AuthServiceProxy, SATOSHIS, make_service_url try: from lntenna.server.bitcoind_password import BITCOIND_PW except ModuleNotFoundError: pass from lntenna.database import ( mesh_add_verify_quote, orders_get_network, mesh_get_refund_addr, ) from lntenna.gotenna.utilities import log from lntenna.lightning.lnaddr import lndecode from lntenna.server.config import CONFIG from lntenna.swap.verify_redeemscript import verify_redeem_script logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format=CONFIG["logging"]["FORMAT"]) def auto_swap_verify_quote(message, cli=False): result = {} if cli: log("\n---------------------------------------\n\n", cli) log(f"Your lntenna UUID for this order is: {message["u"]}", cli) log( f"You can use this to re-send swap_tx message to GATEWAY and to query " f"status of interrupted swaps.", cli, ) log("\n\n---------------------------------------\n", cli) # decode the invoice, raise value error if signature mismatch decoded_inv = lndecode(message["i"]) log(f"Decoded invoice: {decoded_inv}", cli) log(f"Redeem script: {message["rs"]}", cli) # Check the Pubkey from the invoice matches hardcoded keys log("Checking decoded pubkey matches known blockstream pubkeys...", cli) pubkey = hexlify(decoded_inv.pubkey.serialize()).decode("utf-8") if pubkey in CONFIG["blocksat_pubkeys"].values(): log( f"Pubkey {pubkey} successfully matched to hardcoded keys in config.ini!", cli, ) else: log(f"Pubkey {pubkey} not matched to hardcoded keys in config.ini!", cli) return False # check the redeem_script matches the invoice payment_hash and P2SH address log("Checking swap redeem script matches lightning invoice payment hash...", cli) payment_hash = decoded_inv.paymenthash.hex() # get refund address from db refund_addr = mesh_get_refund_addr(message["u"]) if verify_redeem_script(payment_hash, message["rs"], message["ad"], refund_addr): log( "Redeem script verified and matched to P2SH address provided by swap server", cli, ) else: log( "Redeem script NOT verified and matched to P2SH address provided by swap server", cli, ) return False # lookup network using UUID from db network = orders_get_network(message["u"]) # calculate amount the bitcoin transaction and require user confirmation amount = f'{message['am'] / SATOSHIS:.8f}' if cli: log( f"\nAre you happy to proceed with creating the below transaction to fulfill" f" swap request:\n" f"\tNETWORK: {network}\n" f"\tAMOUNT: {amount}\n", cli, ) res = input("Enter 'y' to continue\t") or "y" if res.lower() != "y": log("satellite message payment cancelled", cli) return # setup the transaction proxy = AuthServiceProxy(service_url=make_service_url(network)) try: result["tx_hash"] = proxy.sendtoaddress(message["ad"], amount) except Exception as e1: if BITCOIND_PW: try: proxy.walletpassphrase(BITCOIND_PW, 60) result["tx_hash"] = proxy.sendtoaddress(message["ad"], amount) proxy.walletlock() except Exception as e2: log( f"raised errors during transaction construction: \n {e1}\n {e2}", cli, ) tx_hash = proxy.gettransaction(result["tx_hash"]) result["tx_hex"] = tx_hash["hex"] # TODO: for separate machines should change to getrawtransaction as per below # result["tx_hex"] = proxy.getrawtransaction(result["tx_hash"]) result["uuid"] = message["u"] # write to db as we don't have it on our side yet.: mesh_add_verify_quote( message["u"], message["i"], message["am"], message["ad"], message["rs"], pubkey, payment_hash, tx_hash["txid"], tx_hash["hex"], ) log(f"Returning swap tx to GATEWAY:\n{pformat(result)}", cli) return {"swap_tx": result}
import logging from binascii import hexlify from pprint import pformat from lntenna.bitcoin import AuthServiceProxy, SATOSHIS, make_service_url try: from lntenna.server.bitcoind_password import BITCOIND_PW except ModuleNotFoundError: pass from lntenna.database import ( mesh_add_verify_quote, orders_get_network, mesh_get_refund_addr, ) from lntenna.gotenna.utilities import log from lntenna.lightning.lnaddr import lndecode from lntenna.server.config import CONFIG from lntenna.swap.verify_redeemscript import verify_redeem_script logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format=CONFIG["logging"]["FORMAT"]) def auto_swap_verify_quote(message, cli=False): result = {} if cli: log("\n---------------------------------------\n\n", cli) log(f"Your lntenna UUID for this order is: {message['u']}", cli) log( f"You can use this to re-send swap_tx message to GATEWAY and to query " f"status of interrupted swaps.", cli, ) log("\n\n---------------------------------------\n", cli) # decode the invoice, raise value error if signature mismatch decoded_inv = lndecode(message["i"]) log(f"Decoded invoice: {decoded_inv}", cli) log(f"Redeem script: {message['rs']}", cli) # Check the Pubkey from the invoice matches hardcoded keys log("Checking decoded pubkey matches known blockstream pubkeys...", cli) pubkey = hexlify(decoded_inv.pubkey.serialize()).decode("utf-8") if pubkey in CONFIG["blocksat_pubkeys"].values(): log( f"Pubkey {pubkey} successfully matched to hardcoded keys in config.ini!", cli, ) else: log(f"Pubkey {pubkey} not matched to hardcoded keys in config.ini!", cli) return False # check the redeem_script matches the invoice payment_hash and P2SH address log("Checking swap redeem script matches lightning invoice payment hash...", cli) payment_hash = decoded_inv.paymenthash.hex() # get refund address from db refund_addr = mesh_get_refund_addr(message["u"]) if verify_redeem_script(payment_hash, message["rs"], message["ad"], refund_addr): log( "Redeem script verified and matched to P2SH address provided by swap server", cli, ) else: log( "Redeem script NOT verified and matched to P2SH address provided by swap server", cli, ) return False # lookup network using UUID from db network = orders_get_network(message["u"]) # calculate amount the bitcoin transaction and require user confirmation amount = f'{message["am"] / SATOSHIS:.8f}' if cli: log( f"\nAre you happy to proceed with creating the below transaction to fulfill" f" swap request:\n" f"\tNETWORK: {network}\n" f"\tAMOUNT: {amount}\n", cli, ) res = input("Enter 'y' to continue\t") or "y" if res.lower() != "y": log("satellite message payment cancelled", cli) return # setup the transaction proxy = AuthServiceProxy(service_url=make_service_url(network)) try: result["tx_hash"] = proxy.sendtoaddress(message["ad"], amount) except Exception as e1: if BITCOIND_PW: try: proxy.walletpassphrase(BITCOIND_PW, 60) result["tx_hash"] = proxy.sendtoaddress(message["ad"], amount) proxy.walletlock() except Exception as e2: log( f"raised errors during transaction construction: \n {e1}\n {e2}", cli, ) tx_hash = proxy.gettransaction(result["tx_hash"]) result["tx_hex"] = tx_hash["hex"] # TODO: for separate machines should change to getrawtransaction as per below # result["tx_hex"] = proxy.getrawtransaction(result["tx_hash"]) result["uuid"] = message["u"] # write to db as we don't have it on our side yet.: mesh_add_verify_quote( message["u"], message["i"], message["am"], message["ad"], message["rs"], pubkey, payment_hash, tx_hash["txid"], tx_hash["hex"], ) log(f"Returning swap tx to GATEWAY:\n{pformat(result)}", cli) return {"swap_tx": result}
#!/usr/bin/env python # Copyright 2022 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Creates a new branch that bumps the llvm-project commit. # Typical usage (from the iree/ repository): # /path/to/here/bump_llvm.py # # In the default configuration, it will create a new branch # "bump-llvm-YYYYMMDD" # This will fail if the branch already exists, in which case, you can: # * Specify an explicit branch name with --branch-name=my-integrate # * Pass "--reuse-branch" if you are sure that you want to lose the current # branch state. This is largely meant for developing this script or YOLO # use. # # In order to not interfere with your personal preferences, a remote named # 'UPSTREAM_AUTOMATION' is used (and setup if needed). Sorry if you use that # name for your daily work. # # This then reverts any changes to the llvm-project submodule setup (i.e. # resets it to llvm-project's repository and disables branch tracking) and # resets the submodule to the curren HEAD commit, generating a nice commit # message. # # The branch is then pushed to the main repository. GitHub will print the usual # message to create a pull request, which you should do to kick off pre-merge # checks. You should land changes to this branch until green (or get other # people to do so). # # When satisfied, Squash and Merge, opting to delete the branch to keep things # tidy. import argparse from datetime import date import os import sys import iree_modules import iree_utils def main(args): if not args.disable_setup_remote: iree_utils.git_setup_remote(args.upstream_remote, args.upstream_repository) iree_utils.git_check_porcelain() print(f"Fetching remote repository: {args.upstream_remote}") iree_utils.git_fetch(repository=args.upstream_remote) # If re-using a branch, make sure we are not on that branch. if args.reuse_branch: iree_utils.git_checkout("main") # Create branch. branch_name = args.branch_name if not branch_name: branch_name = f"bump-llvm-{date.today().strftime("%Y%m%d")}" print(f"Creating branch {branch_name} (override with --branch-name=)") iree_utils.git_create_branch(branch_name, checkout=True, ref=f"{args.upstream_remote}/main", force=args.reuse_branch) # Reset the llvm-project submodule to track upstream. # This will discard any cherrypicks that may have been committed locally, # but the assumption is that if doing a main llvm version bump, the # cherrypicks will be incorporated at the new commit. If not, well, ymmv # and you will find out. iree_utils.git_submodule_set_origin( "third_party/llvm-project", url="https://github.com/llvm/llvm-project.git", branch="--default") # Remove the branch pin file, reverting us to pure upstream. branch_pin_file = os.path.join( iree_utils.get_repo_root(), iree_modules.MODULE_INFOS["llvm-project"].branch_pin_file) if os.path.exists(branch_pin_file): os.remove(branch_pin_file) # Update the LLVM submodule. llvm_commit = args.llvm_commit print(f"Updating LLVM submodule to {llvm_commit}") llvm_root = iree_utils.get_submodule_root("llvm-project") iree_utils.git_fetch(repo_dir=llvm_root) if llvm_commit == "HEAD": llvm_commit = "origin/main" iree_utils.git_reset(llvm_commit, repo_dir=llvm_root) llvm_commit, llvm_summary = iree_utils.git_current_commit( repo_dir=llvm_root) print(f"LLVM submodule reset to:\n {llvm_summary}\n") # Create a commit. print("Create commit...") iree_utils.git_create_commit( message=(f"Integrate llvm-project at {llvm_commit}\n\n" f"* Reset third_party/llvm-project: {llvm_summary}"), add_all=True) # Push. print("Pushing...") iree_utils.git_push_branch(args.upstream_remote, branch_name) def parse_arguments(argv): parser = argparse.ArgumentParser(description="IREE LLVM-bump-inator") parser.add_argument("--upstream-remote", help="Upstream remote", default="UPSTREAM_AUTOMATION") parser.add_argument("--upstream-repository", help="Upstream repository URL", default="git@github.com:google/iree.git") parser.add_argument("--disable-setup-remote", help="Disable remote setup", action="store_true", default=False) parser.add_argument("--llvm-commit", help="LLVM commit sha", default="HEAD") parser.add_argument("--branch-name", help="Integrate branch to create", default=None) parser.add_argument("--reuse-branch", help="Allow re-use of an existing branch", action="store_true", default=False) args = parser.parse_args(argv) return args if __name__ == "__main__": main(parse_arguments(sys.argv[1:]))
#!/usr/bin/env python # Copyright 2022 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # Creates a new branch that bumps the llvm-project commit. # Typical usage (from the iree/ repository): # /path/to/here/bump_llvm.py # # In the default configuration, it will create a new branch # "bump-llvm-YYYYMMDD" # This will fail if the branch already exists, in which case, you can: # * Specify an explicit branch name with --branch-name=my-integrate # * Pass "--reuse-branch" if you are sure that you want to lose the current # branch state. This is largely meant for developing this script or YOLO # use. # # In order to not interfere with your personal preferences, a remote named # 'UPSTREAM_AUTOMATION' is used (and setup if needed). Sorry if you use that # name for your daily work. # # This then reverts any changes to the llvm-project submodule setup (i.e. # resets it to llvm-project's repository and disables branch tracking) and # resets the submodule to the curren HEAD commit, generating a nice commit # message. # # The branch is then pushed to the main repository. GitHub will print the usual # message to create a pull request, which you should do to kick off pre-merge # checks. You should land changes to this branch until green (or get other # people to do so). # # When satisfied, Squash and Merge, opting to delete the branch to keep things # tidy. import argparse from datetime import date import os import sys import iree_modules import iree_utils def main(args): if not args.disable_setup_remote: iree_utils.git_setup_remote(args.upstream_remote, args.upstream_repository) iree_utils.git_check_porcelain() print(f"Fetching remote repository: {args.upstream_remote}") iree_utils.git_fetch(repository=args.upstream_remote) # If re-using a branch, make sure we are not on that branch. if args.reuse_branch: iree_utils.git_checkout("main") # Create branch. branch_name = args.branch_name if not branch_name: branch_name = f"bump-llvm-{date.today().strftime('%Y%m%d')}" print(f"Creating branch {branch_name} (override with --branch-name=)") iree_utils.git_create_branch(branch_name, checkout=True, ref=f"{args.upstream_remote}/main", force=args.reuse_branch) # Reset the llvm-project submodule to track upstream. # This will discard any cherrypicks that may have been committed locally, # but the assumption is that if doing a main llvm version bump, the # cherrypicks will be incorporated at the new commit. If not, well, ymmv # and you will find out. iree_utils.git_submodule_set_origin( "third_party/llvm-project", url="https://github.com/llvm/llvm-project.git", branch="--default") # Remove the branch pin file, reverting us to pure upstream. branch_pin_file = os.path.join( iree_utils.get_repo_root(), iree_modules.MODULE_INFOS["llvm-project"].branch_pin_file) if os.path.exists(branch_pin_file): os.remove(branch_pin_file) # Update the LLVM submodule. llvm_commit = args.llvm_commit print(f"Updating LLVM submodule to {llvm_commit}") llvm_root = iree_utils.get_submodule_root("llvm-project") iree_utils.git_fetch(repo_dir=llvm_root) if llvm_commit == "HEAD": llvm_commit = "origin/main" iree_utils.git_reset(llvm_commit, repo_dir=llvm_root) llvm_commit, llvm_summary = iree_utils.git_current_commit( repo_dir=llvm_root) print(f"LLVM submodule reset to:\n {llvm_summary}\n") # Create a commit. print("Create commit...") iree_utils.git_create_commit( message=(f"Integrate llvm-project at {llvm_commit}\n\n" f"* Reset third_party/llvm-project: {llvm_summary}"), add_all=True) # Push. print("Pushing...") iree_utils.git_push_branch(args.upstream_remote, branch_name) def parse_arguments(argv): parser = argparse.ArgumentParser(description="IREE LLVM-bump-inator") parser.add_argument("--upstream-remote", help="Upstream remote", default="UPSTREAM_AUTOMATION") parser.add_argument("--upstream-repository", help="Upstream repository URL", default="git@github.com:google/iree.git") parser.add_argument("--disable-setup-remote", help="Disable remote setup", action="store_true", default=False) parser.add_argument("--llvm-commit", help="LLVM commit sha", default="HEAD") parser.add_argument("--branch-name", help="Integrate branch to create", default=None) parser.add_argument("--reuse-branch", help="Allow re-use of an existing branch", action="store_true", default=False) args = parser.parse_args(argv) return args if __name__ == "__main__": main(parse_arguments(sys.argv[1:]))
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1156371286.47dzzz0': {'Type': 'Building Interior','Name': '','Instanced': False,'Objects': {'1165344228.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(2.145, 0.0, 0.0),'Pos': Point3(-1.873, -5.288, -0.154),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.76, 0.63, 0.63, 1.0),'Model': 'models/props/table_shanty_2'}},'1165344324.52kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-45.131, 3.722, -3.619),'Pos': Point3(-1.364, 0.471, -0.116),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8500000238418579, 0.8899999856948853, 1.0),'Model': 'models/props/chair_shanty'}},'1165344556.34kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(88.434, 0.0, 0.0),'Objects': {'1257796843.25caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(0.746, 0.0, 41.101),'Pos': Point3(5.953, 0.347, 7.885),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.72caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(2.188, 2.043, 40.716),'Pos': Point3(5.951, 0.341, 7.887),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}},'Pos': Point3(-18.325, -5.523, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.800000011920929, 0.6899999976158142, 0.6200000047683716, 1.0),'Model': 'models/props/bench_shanty_1'}},'1165344792.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(87.026, 0.0, 0.0),'Pos': Point3(3.702, -5.822, -0.059),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.85, 0.89, 1.0),'Model': 'models/props/bench_shanty_2'}},'1166055838.34kmuller': {'Type': 'Wall_Hangings','DisableCollision': False,'Hpr': VBase3(89.83, 0.0, 0.0),'Pos': Point3(-19.983, -6.616, 8.019),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/Map_01_unframed'}},'1166130817.64kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(87.026, 0.0, 0.0),'Pos': Point3(-4.754, -5.382, -0.154),'Scale': VBase3(1.001, 1.001, 1.001),'Visual': {'Color': (0.85, 0.74, 0.79, 1.0),'Model': 'models/props/bench_shanty_2'}},'1166130858.42kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(96.22, 0.235, 0.509),'Pos': Point3(-0.609, -10.763, 0.332),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7599999904632568, 0.7599999904632568, 0.699999988079071, 1.0),'Model': 'models/props/chair_shanty'}},'1166130963.4kmuller': {'Type': 'LaundryRope','DisableCollision': False,'Hpr': VBase3(-24.584, 0.0, 0.0),'Pos': Point3(12.688, 24.692, -5.477),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/LaundryRope'}},'1166131071.71kmuller': {'Type': 'Bucket','DisableCollision': False,'Hpr': VBase3(35.24, 3.466, -2.446),'Pos': Point3(18.515, 20.409, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/washtub'}},'1166131830.51kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(-0.376, -4.662, 4.742),'Pos': Point3(-6.011, 11.734, 0.168),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7699999809265137, 0.75, 0.7300000190734863, 1.0),'Model': 'models/props/broom'}},'1166132516.06kmuller': {'Type': 'Baskets','DisableCollision': True,'Hpr': VBase3(-43.987, 0.0, 0.0),'Pos': Point3(19.041, -5.375, 0.0),'Scale': VBase3(1.775, 1.775, 1.775),'Visual': {'Model': 'models/props/crab_pot'}},'1166132600.56kmuller': {'Type': 'Bucket','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(8.542, -25.98, 0.093),'Scale': VBase3(0.676, 0.676, 0.676),'Visual': {'Model': 'models/props/bucket_handles'}},'1166132865.18kmuller': {'Type': 'ChickenCage','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-17.673, -13.339, 0.034),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/ChickenCage'}},'1166132969.78kmuller': {'Type': 'Animal','Hpr': VBase3(0.0, 0.0, 0.0),'Patrol Radius': '1.0000','Pos': Point3(-17.559, -13.569, 0.406),'PoseAnim': '','PoseFrame': '','Respawns': True,'Scale': VBase3(1.0, 1.0, 1.0),'Species': 'Chicken','Start State': 'Idle','StartFrame': '0'},'1166133856.57kmuller': {'Type': 'Prop_Groups','DisableCollision': False,'Hpr': VBase3(89.351, 0.0, 0.0),'Pos': Point3(-15.962, -20.852, 0.106),'Scale': VBase3(0.855, 0.855, 0.855),'Visual': {'Model': 'models/props/prop_group_B'}},'1166135474.96kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(180.0, 6.596, 171.649),'Pos': Point3(19.924, -2.215, 4.423),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/rake'}},'1166135589.98kmuller': {'Type': 'Ship_Props','DisableCollision': False,'Hpr': VBase3(88.476, 0.0, 0.0),'Pos': Point3(20.013, -8.183, 10.185),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/wheel_wallprop'}},'1166135667.84kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-102.146, 0.0, 0.0),'Pos': Point3(18.702, -11.07, 0.051),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.81, 1.0, 1.0, 1.0),'Model': 'models/props/Trunk_square'}},'1166135716.21kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-88.289, 0.0, 0.0),'Pos': Point3(18.576, -7.985, 0.046),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8500000238418579, 0.8199999928474426, 0.7300000190734863, 1.0),'Model': 'models/props/Trunk_square'}},'1166135765.92kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-88.289, -0.186, 0.0),'Pos': Point3(18.839, -8.919, 2.025),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 1.0, 0.6000000238418579, 1.0),'Model': 'models/props/Trunk_rounded_2'}},'1166137677.04kmuller': {'Type': 'Prop_Groups','DisableCollision': False,'Hpr': VBase3(-133.683, 0.0, 0.0),'Pos': Point3(12.789, -20.122, 0.003),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/prop_group01'}},'1166137745.73kmuller': {'Type': 'Crate','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(16.748, -24.76, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.83, 0.7, 0.72, 1.0),'Model': 'models/props/crates_group_1'}},'1167157033.71kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(92.24, 0.0, 0.0),'Pos': Point3(-18.473, 8.266, 0.054),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0),'Model': 'models/props/cabinet_shanty_low'}},'1167157096.42kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-18.763, 7.381, 2.94),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/bottle_green'}},'1167157149.32kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': VBase3(73.306, 0.0, 0.0),'Pos': Point3(-17.99, 9.746, 2.775),'Scale': VBase3(0.501, 0.501, 0.501),'Visual': {'Model': 'models/props/jug_hanging'}},'1167157231.2kmuller': {'Type': 'Paddle','DisableCollision': False,'Hpr': VBase3(89.285, -9.349, -0.054),'Pos': Point3(-18.83, -1.243, -0.228),'Scale': VBase3(1.858, 1.858, 1.858),'Visual': {'Model': 'models/props/paddle_A'}},'1167159781.48kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-91.038, 0.0, 0.0),'Pos': Point3(18.734, 4.197, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7900000214576721, 0.7799999713897705, 0.699999988079071, 1.0),'Model': 'models/props/cabinet_shanty'}},'1167970188.36kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Holiday': '','Hpr': VBase3(90.015, 0.0, 0.0),'Pos': Point3(-14.562, 11.977, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/interior_wall_shanty'}},'1167970378.72kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-9.971, 10.411, 0.0),'Scale': VBase3(1.193, 1.193, 1.193),'Visual': {'Model': 'models/props/stove_potbelly'}},'1167970427.75kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(90.056, 0.0, 0.0),'Pos': Point3(-1.713, 12.461, 8.5),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1167970512.58kmuller': {'Type': 'Log_Stack','DisableCollision': True,'Hpr': VBase3(-92.49, 0.0, 0.0),'Pos': Point3(-18.174, 4.799, 0.0),'Scale': VBase3(0.691, 0.691, 0.691),'Visual': {'Color': (0.44999998807907104, 0.46000000834465027, 0.5099999904632568, 1.0),'Model': 'models/props/Log_stack_a'}},'1167970583.19kmuller': {'Type': 'Sack','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(3.195, 27.599, -0.059),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/sack_6stack'}},'1167970625.67kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(89.713, 0.0, 0.0),'Pos': Point3(-17.681, -0.615, 10.943),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1167970646.1kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(-90.851, 0.0, 0.0),'Pos': Point3(17.9, -0.195, 9.695),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1174674177.41dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '19.0909','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(91.213, -27.127, -179.178),'Intensity': '1.2121','LightType': 'SPOT','Pos': Point3(25.675, -19.784, 8.777),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8700000047683716, 0.7200000286102295, 1.0),'Model': 'models/props/light_tool_bulb'}},'1174674352.51dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '16.3636','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(85.549, -31.672, -178.789),'Intensity': '1.4545','LightType': 'SPOT','Pos': Point3(29.78, 9.456, 12.447),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8700000047683716, 0.7200000286102295, 1.0),'Model': 'models/props/light_tool_bulb'}},'1174674462.48dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '0.0000','FlickRate': 0.5,'Flickering': True,'Hpr': VBase3(0.0, 0.0, -2.275),'Intensity': '0.0303','LightType': 'AMBIENT','Pos': Point3(-6.678, 17.878, 7.237),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1, 1, 1, 1),'Model': 'models/props/light_tool_bulb'}},'1176403754.48dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '118.4091','DropOff': '2.7273','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(141.547, -88.295, -49.746),'Intensity': '0.9091','LightType': 'SPOT','Pos': Point3(3.216, -0.263, 31.117),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0),'Model': 'models/props/light_tool_bulb'}},'1176403947.28dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '0.0000','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Intensity': '0.1515','LightType': 'AMBIENT','Pos': Point3(-4.351, -5.826, 8.832),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.6200000047683716, 0.7400000095367432, 0.6299999952316284, 1.0),'Model': 'models/props/light_tool_bulb'}},'1185407971.87kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-19.137, 6.054, -0.358),'Scale': VBase3(1.0, 2.336, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408052.75kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(111.084, 0.0, 0.0),'Pos': Point3(-6.823, -28.771, -0.224),'Scale': VBase3(0.526, 1.0, 1.585),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408099.87kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-18.311, -14.725, -1.321),'Scale': VBase3(1.0, 1.0, 2.18),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408199.58kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-0.132, 0.0, 0.0),'Pos': Point3(-15.564, 25.579, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/bed_shantyB'}},'1185408310.17kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-179.994, 0.0, 0.0),'Objects': {'1185408375.03kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': VBase3(-158.871, 0.0, 0.0),'Pos': Point3(-1.358, -0.677, 2.799),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/waterpitcher'}}},'Pos': Point3(11.833, -28.694, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.3499999940395355, 0.3499999940395355, 0.4099999964237213, 1.0),'Model': 'models/props/cabinet_shanty_low'}},'1185408420.62kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(18.533, -20.381, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/butter_churn'}},'1185408515.58kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-176.748, 0.0, 0.0),'Pos': Point3(20.144, -15.07, -0.631),'Scale': VBase3(0.36, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408562.87kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(0.0, 35.595, -10.598),'Pos': Point3(8.462, -27.124, 0.029),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/broom'}},'1185408657.03kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-98.007, 0.0, 0.0),'Pos': Point3(7.73, -27.364, -0.101),'Scale': VBase3(0.551, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408806.71kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(19.554, 3.666, -0.165),'Scale': VBase3(1.0, 1.295, 1.769),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408860.26kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(20.074, -8.558, 0.0),'Scale': VBase3(1.0, 1.667, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408961.95kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-16.736, 25.815, -0.715),'Scale': VBase3(1.361, 1.803, 2.095),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185409015.65kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-1.604, 28.25, -0.328),'Scale': VBase3(3.068, 1.263, 1.734),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1205367433.42kmuller': {'Type': 'Door Locator Node','Name': 'door_locator','Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(0.047, -29.861, 0.067),'Scale': VBase3(1.0, 1.0, 1.0)},'1228170667.7kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-147.374, 1.702, 0.0),'Pos': Point3(-8.78, 12.025, 7.516),'Scale': VBase3(1.386, 1.386, 1.386),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking03_winter09'}},'1228170701.94kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-26.747, -2.266, 0.0),'Pos': Point3(-11.617, 11.993, 7.771),'Scale': VBase3(1.386, 1.386, 1.386),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking02_winter09'}},'1228170770.86kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(18.422, 5.597, 5.548),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Color': (0.6000000238418579, 0.800000011920929, 1.0, 1.0),'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}},'1228170797.78kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-14.653, 0.0, 0.0),'Pos': Point3(18.294, 3.195, 2.632),'Scale': VBase3(0.793, 0.793, 0.793),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}},'1228170869.25kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(37.436, 0.0, 0.0),'Pos': Point3(18.492, 4.583, 2.593),'Scale': VBase3(1.049, 1.049, 1.049),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift02_winter08'}},'1257372614.06caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-91.661, 0.0, 0.0),'Pos': Point3(19.574, -8.163, 7.634),'Scale': VBase3(1.526, 1.526, 1.526),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257796806.06caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-87.122, 2.043, 40.716),'Pos': Point3(18.72, -0.841, 8.143),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797083.57caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.79, 0.0, 0.0),'Pos': Point3(18.638, -0.171, 7.708),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797129.54caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(88.954, 0.0, 0.0),'Pos': Point3(-18.447, -0.237, 7.451),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797143.12caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(93.614, 0.0, 39.463),'Pos': Point3(18.631, 0.367, 8.109),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797208.82caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.642, 0.0, 39.463),'Pos': Point3(-18.461, -0.775, 7.853),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.76caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.642, 0.0, 39.463),'Pos': Point3(-18.461, -0.775, 7.853),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.77caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(88.954, 0.0, 0.0),'Pos': Point3(-18.447, -0.237, 7.451),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797342.72caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-1.881, 2.043, 40.716),'Pos': Point3(-2.685, 11.691, 7.305),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797342.74caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(178.855, 0.0, 39.463),'Pos': Point3(-3.896, 11.702, 7.271),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797342.75caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-3.548, 0.0, 0.0),'Pos': Point3(-3.359, 11.664, 6.869),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}},'Visual': {'Model': 'models/buildings/interior_shanty_npc_house'}}},'Node Links': [],'Layers': {},'ObjectIds': {'1156371286.47dzzz0': '["Objects"]["1156371286.47dzzz0"]','1165344228.45kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344228.45kmuller"]','1165344324.52kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344324.52kmuller"]','1165344556.34kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]','1165344792.45kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344792.45kmuller"]','1166055838.34kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166055838.34kmuller"]','1166130817.64kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130817.64kmuller"]','1166130858.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130858.42kmuller"]','1166130963.4kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130963.4kmuller"]','1166131071.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166131071.71kmuller"]','1166131830.51kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166131830.51kmuller"]','1166132516.06kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132516.06kmuller"]','1166132600.56kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132600.56kmuller"]','1166132865.18kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132865.18kmuller"]','1166132969.78kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132969.78kmuller"]','1166133856.57kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166133856.57kmuller"]','1166135474.96kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135474.96kmuller"]','1166135589.98kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135589.98kmuller"]','1166135667.84kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135667.84kmuller"]','1166135716.21kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135716.21kmuller"]','1166135765.92kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135765.92kmuller"]','1166137677.04kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166137677.04kmuller"]','1166137745.73kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166137745.73kmuller"]','1167157033.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157033.71kmuller"]','1167157096.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157096.42kmuller"]','1167157149.32kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157149.32kmuller"]','1167157231.2kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157231.2kmuller"]','1167159781.48kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167159781.48kmuller"]','1167970188.36kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970188.36kmuller"]','1167970378.72kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970378.72kmuller"]','1167970427.75kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970427.75kmuller"]','1167970512.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970512.58kmuller"]','1167970583.19kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970583.19kmuller"]','1167970625.67kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970625.67kmuller"]','1167970646.1kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970646.1kmuller"]','1174674177.41dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674177.41dzlu"]','1174674352.51dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674352.51dzlu"]','1174674462.48dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674462.48dzlu"]','1176403754.48dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1176403754.48dzlu"]','1176403947.28dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1176403947.28dzlu"]','1185407971.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185407971.87kmuller"]','1185408052.75kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408052.75kmuller"]','1185408099.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408099.87kmuller"]','1185408199.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408199.58kmuller"]','1185408310.17kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408310.17kmuller"]','1185408375.03kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408310.17kmuller"]["Objects"]["1185408375.03kmuller"]','1185408420.62kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408420.62kmuller"]','1185408515.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408515.58kmuller"]','1185408562.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408562.87kmuller"]','1185408657.03kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408657.03kmuller"]','1185408806.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408806.71kmuller"]','1185408860.26kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408860.26kmuller"]','1185408961.95kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408961.95kmuller"]','1185409015.65kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185409015.65kmuller"]','1205367433.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1205367433.42kmuller"]','1228170667.7kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170667.7kmuller"]','1228170701.94kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170701.94kmuller"]','1228170770.86kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170770.86kmuller"]','1228170797.78kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170797.78kmuller"]','1228170869.25kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170869.25kmuller"]','1257372614.06caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257372614.06caoconno"]','1257796806.06caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257796806.06caoconno"]','1257796843.25caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]["Objects"]["1257796843.25caoconno"]','1257797083.57caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797083.57caoconno"]','1257797129.54caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797129.54caoconno"]','1257797143.12caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797143.12caoconno"]','1257797208.82caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797208.82caoconno"]','1257797277.72caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]["Objects"]["1257797277.72caoconno"]','1257797277.76caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797277.76caoconno"]','1257797277.77caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797277.77caoconno"]','1257797342.72caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.72caoconno"]','1257797342.74caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.74caoconno"]','1257797342.75caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.75caoconno"]'}} extraInfo = {'camPos': Point3(38.4972, 15.2174, 22.107),'camHpr': VBase3(119.723, -14.2124, 0),'focalLength': 0.657999992371,'skyState': -1,'fog': 0}
from pandac.PandaModules import Point3, VBase3, Vec4, Vec3 objectStruct = {'Objects': {'1156371286.47dzzz0': {'Type': 'Building Interior','Name': '','Instanced': False,'Objects': {'1165344228.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(2.145, 0.0, 0.0),'Pos': Point3(-1.873, -5.288, -0.154),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.76, 0.63, 0.63, 1.0),'Model': 'models/props/table_shanty_2'}},'1165344324.52kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(-45.131, 3.722, -3.619),'Pos': Point3(-1.364, 0.471, -0.116),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8500000238418579, 0.8899999856948853, 1.0),'Model': 'models/props/chair_shanty'}},'1165344556.34kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(88.434, 0.0, 0.0),'Objects': {'1257796843.25caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(0.746, 0.0, 41.101),'Pos': Point3(5.953, 0.347, 7.885),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.72caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(2.188, 2.043, 40.716),'Pos': Point3(5.951, 0.341, 7.887),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}}},'Pos': Point3(-18.325, -5.523, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.800000011920929, 0.6899999976158142, 0.6200000047683716, 1.0),'Model': 'models/props/bench_shanty_1'}},'1165344792.45kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(87.026, 0.0, 0.0),'Pos': Point3(3.702, -5.822, -0.059),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.85, 0.89, 1.0),'Model': 'models/props/bench_shanty_2'}},'1166055838.34kmuller': {'Type': 'Wall_Hangings','DisableCollision': False,'Hpr': VBase3(89.83, 0.0, 0.0),'Pos': Point3(-19.983, -6.616, 8.019),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/Map_01_unframed'}},'1166130817.64kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(87.026, 0.0, 0.0),'Pos': Point3(-4.754, -5.382, -0.154),'Scale': VBase3(1.001, 1.001, 1.001),'Visual': {'Color': (0.85, 0.74, 0.79, 1.0),'Model': 'models/props/bench_shanty_2'}},'1166130858.42kmuller': {'Type': 'Furniture','DisableCollision': False,'Hpr': VBase3(96.22, 0.235, 0.509),'Pos': Point3(-0.609, -10.763, 0.332),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7599999904632568, 0.7599999904632568, 0.699999988079071, 1.0),'Model': 'models/props/chair_shanty'}},'1166130963.4kmuller': {'Type': 'LaundryRope','DisableCollision': False,'Hpr': VBase3(-24.584, 0.0, 0.0),'Pos': Point3(12.688, 24.692, -5.477),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/LaundryRope'}},'1166131071.71kmuller': {'Type': 'Bucket','DisableCollision': False,'Hpr': VBase3(35.24, 3.466, -2.446),'Pos': Point3(18.515, 20.409, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/washtub'}},'1166131830.51kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(-0.376, -4.662, 4.742),'Pos': Point3(-6.011, 11.734, 0.168),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7699999809265137, 0.75, 0.7300000190734863, 1.0),'Model': 'models/props/broom'}},'1166132516.06kmuller': {'Type': 'Baskets','DisableCollision': True,'Hpr': VBase3(-43.987, 0.0, 0.0),'Pos': Point3(19.041, -5.375, 0.0),'Scale': VBase3(1.775, 1.775, 1.775),'Visual': {'Model': 'models/props/crab_pot'}},'1166132600.56kmuller': {'Type': 'Bucket','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(8.542, -25.98, 0.093),'Scale': VBase3(0.676, 0.676, 0.676),'Visual': {'Model': 'models/props/bucket_handles'}},'1166132865.18kmuller': {'Type': 'ChickenCage','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-17.673, -13.339, 0.034),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/ChickenCage'}},'1166132969.78kmuller': {'Type': 'Animal','Hpr': VBase3(0.0, 0.0, 0.0),'Patrol Radius': '1.0000','Pos': Point3(-17.559, -13.569, 0.406),'PoseAnim': '','PoseFrame': '','Respawns': True,'Scale': VBase3(1.0, 1.0, 1.0),'Species': 'Chicken','Start State': 'Idle','StartFrame': '0'},'1166133856.57kmuller': {'Type': 'Prop_Groups','DisableCollision': False,'Hpr': VBase3(89.351, 0.0, 0.0),'Pos': Point3(-15.962, -20.852, 0.106),'Scale': VBase3(0.855, 0.855, 0.855),'Visual': {'Model': 'models/props/prop_group_B'}},'1166135474.96kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(180.0, 6.596, 171.649),'Pos': Point3(19.924, -2.215, 4.423),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/rake'}},'1166135589.98kmuller': {'Type': 'Ship_Props','DisableCollision': False,'Hpr': VBase3(88.476, 0.0, 0.0),'Pos': Point3(20.013, -8.183, 10.185),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/wheel_wallprop'}},'1166135667.84kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-102.146, 0.0, 0.0),'Pos': Point3(18.702, -11.07, 0.051),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.81, 1.0, 1.0, 1.0),'Model': 'models/props/Trunk_square'}},'1166135716.21kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-88.289, 0.0, 0.0),'Pos': Point3(18.576, -7.985, 0.046),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8500000238418579, 0.8199999928474426, 0.7300000190734863, 1.0),'Model': 'models/props/Trunk_square'}},'1166135765.92kmuller': {'Type': 'Trunks','DisableCollision': True,'Hpr': VBase3(-88.289, -0.186, 0.0),'Pos': Point3(18.839, -8.919, 2.025),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 1.0, 0.6000000238418579, 1.0),'Model': 'models/props/Trunk_rounded_2'}},'1166137677.04kmuller': {'Type': 'Prop_Groups','DisableCollision': False,'Hpr': VBase3(-133.683, 0.0, 0.0),'Pos': Point3(12.789, -20.122, 0.003),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/prop_group01'}},'1166137745.73kmuller': {'Type': 'Crate','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(16.748, -24.76, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.83, 0.7, 0.72, 1.0),'Model': 'models/props/crates_group_1'}},'1167157033.71kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(92.24, 0.0, 0.0),'Pos': Point3(-18.473, 8.266, 0.054),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.699999988079071, 0.699999988079071, 0.699999988079071, 1.0),'Model': 'models/props/cabinet_shanty_low'}},'1167157096.42kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-18.763, 7.381, 2.94),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/bottle_green'}},'1167157149.32kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': VBase3(73.306, 0.0, 0.0),'Pos': Point3(-17.99, 9.746, 2.775),'Scale': VBase3(0.501, 0.501, 0.501),'Visual': {'Model': 'models/props/jug_hanging'}},'1167157231.2kmuller': {'Type': 'Paddle','DisableCollision': False,'Hpr': VBase3(89.285, -9.349, -0.054),'Pos': Point3(-18.83, -1.243, -0.228),'Scale': VBase3(1.858, 1.858, 1.858),'Visual': {'Model': 'models/props/paddle_A'}},'1167159781.48kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-91.038, 0.0, 0.0),'Pos': Point3(18.734, 4.197, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.7900000214576721, 0.7799999713897705, 0.699999988079071, 1.0),'Model': 'models/props/cabinet_shanty'}},'1167970188.36kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Holiday': '','Hpr': VBase3(90.015, 0.0, 0.0),'Pos': Point3(-14.562, 11.977, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/interior_wall_shanty'}},'1167970378.72kmuller': {'Type': 'Interior_furnishings','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-9.971, 10.411, 0.0),'Scale': VBase3(1.193, 1.193, 1.193),'Visual': {'Model': 'models/props/stove_potbelly'}},'1167970427.75kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(90.056, 0.0, 0.0),'Pos': Point3(-1.713, 12.461, 8.5),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1167970512.58kmuller': {'Type': 'Log_Stack','DisableCollision': True,'Hpr': VBase3(-92.49, 0.0, 0.0),'Pos': Point3(-18.174, 4.799, 0.0),'Scale': VBase3(0.691, 0.691, 0.691),'Visual': {'Color': (0.44999998807907104, 0.46000000834465027, 0.5099999904632568, 1.0),'Model': 'models/props/Log_stack_a'}},'1167970583.19kmuller': {'Type': 'Sack','DisableCollision': True,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(3.195, 27.599, -0.059),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/sack_6stack'}},'1167970625.67kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(89.713, 0.0, 0.0),'Pos': Point3(-17.681, -0.615, 10.943),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1167970646.1kmuller': {'Type': 'Light_Fixtures','DisableCollision': False,'Hpr': VBase3(-90.851, 0.0, 0.0),'Pos': Point3(17.9, -0.195, 9.695),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/lamp_candle'}},'1174674177.41dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '19.0909','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(91.213, -27.127, -179.178),'Intensity': '1.2121','LightType': 'SPOT','Pos': Point3(25.675, -19.784, 8.777),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8700000047683716, 0.7200000286102295, 1.0),'Model': 'models/props/light_tool_bulb'}},'1174674352.51dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '16.3636','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(85.549, -31.672, -178.789),'Intensity': '1.4545','LightType': 'SPOT','Pos': Point3(29.78, 9.456, 12.447),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1.0, 0.8700000047683716, 0.7200000286102295, 1.0),'Model': 'models/props/light_tool_bulb'}},'1174674462.48dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '0.0000','FlickRate': 0.5,'Flickering': True,'Hpr': VBase3(0.0, 0.0, -2.275),'Intensity': '0.0303','LightType': 'AMBIENT','Pos': Point3(-6.678, 17.878, 7.237),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (1, 1, 1, 1),'Model': 'models/props/light_tool_bulb'}},'1176403754.48dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '118.4091','DropOff': '2.7273','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(141.547, -88.295, -49.746),'Intensity': '0.9091','LightType': 'SPOT','Pos': Point3(3.216, -0.263, 31.117),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.8700000047683716, 1.0, 1.0, 1.0),'Model': 'models/props/light_tool_bulb'}},'1176403947.28dzlu': {'Type': 'Light - Dynamic','Attenuation': '0.005','ConeAngle': '60.0000','DropOff': '0.0000','FlickRate': 0.5,'Flickering': False,'Hpr': VBase3(0.0, 0.0, 0.0),'Intensity': '0.1515','LightType': 'AMBIENT','Pos': Point3(-4.351, -5.826, 8.832),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.6200000047683716, 0.7400000095367432, 0.6299999952316284, 1.0),'Model': 'models/props/light_tool_bulb'}},'1185407971.87kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-19.137, 6.054, -0.358),'Scale': VBase3(1.0, 2.336, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408052.75kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(111.084, 0.0, 0.0),'Pos': Point3(-6.823, -28.771, -0.224),'Scale': VBase3(0.526, 1.0, 1.585),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408099.87kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-18.311, -14.725, -1.321),'Scale': VBase3(1.0, 1.0, 2.18),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408199.58kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-0.132, 0.0, 0.0),'Pos': Point3(-15.564, 25.579, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/bed_shantyB'}},'1185408310.17kmuller': {'Type': 'Furniture','DisableCollision': True,'Hpr': VBase3(-179.994, 0.0, 0.0),'Objects': {'1185408375.03kmuller': {'Type': 'Jugs_and_Jars','DisableCollision': False,'Hpr': VBase3(-158.871, 0.0, 0.0),'Pos': Point3(-1.358, -0.677, 2.799),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/waterpitcher'}}},'Pos': Point3(11.833, -28.694, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Color': (0.3499999940395355, 0.3499999940395355, 0.4099999964237213, 1.0),'Model': 'models/props/cabinet_shanty_low'}},'1185408420.62kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(18.533, -20.381, 0.0),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/butter_churn'}},'1185408515.58kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-176.748, 0.0, 0.0),'Pos': Point3(20.144, -15.07, -0.631),'Scale': VBase3(0.36, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408562.87kmuller': {'Type': 'Tools','DisableCollision': False,'Hpr': VBase3(0.0, 35.595, -10.598),'Pos': Point3(8.462, -27.124, 0.029),'Scale': VBase3(1.0, 1.0, 1.0),'Visual': {'Model': 'models/props/broom'}},'1185408657.03kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': VBase3(-98.007, 0.0, 0.0),'Pos': Point3(7.73, -27.364, -0.101),'Scale': VBase3(0.551, 1.0, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_plane'}},'1185408806.71kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(19.554, 3.666, -0.165),'Scale': VBase3(1.0, 1.295, 1.769),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408860.26kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(20.074, -8.558, 0.0),'Scale': VBase3(1.0, 1.667, 1.0),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185408961.95kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-16.736, 25.815, -0.715),'Scale': VBase3(1.361, 1.803, 2.095),'Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1185409015.65kmuller': {'Type': 'Collision Barrier','DisableCollision': False,'Holiday': '','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(-1.604, 28.25, -0.328),'Scale': VBase3(3.068, 1.263, 1.734),'VisSize': '','Visual': {'Model': 'models/misc/pir_m_prp_lev_cambarrier_cube'}},'1205367433.42kmuller': {'Type': 'Door Locator Node','Name': 'door_locator','Hpr': VBase3(0.0, 0.0, 0.0),'Pos': Point3(0.047, -29.861, 0.067),'Scale': VBase3(1.0, 1.0, 1.0)},'1228170667.7kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-147.374, 1.702, 0.0),'Pos': Point3(-8.78, 12.025, 7.516),'Scale': VBase3(1.386, 1.386, 1.386),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking03_winter09'}},'1228170701.94kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-26.747, -2.266, 0.0),'Pos': Point3(-11.617, 11.993, 7.771),'Scale': VBase3(1.386, 1.386, 1.386),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoStocking02_winter09'}},'1228170770.86kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': Point3(0.0, 0.0, 0.0),'Pos': Point3(18.422, 5.597, 5.548),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Color': (0.6000000238418579, 0.800000011920929, 1.0, 1.0),'Model': 'models/props/pir_m_prp_hol_decoGift04_winter08'}},'1228170797.78kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-14.653, 0.0, 0.0),'Pos': Point3(18.294, 3.195, 2.632),'Scale': VBase3(0.793, 0.793, 0.793),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift01_winter08'}},'1228170869.25kmuller': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(37.436, 0.0, 0.0),'Pos': Point3(18.492, 4.583, 2.593),'Scale': VBase3(1.049, 1.049, 1.049),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoGift02_winter08'}},'1257372614.06caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-91.661, 0.0, 0.0),'Pos': Point3(19.574, -8.163, 7.634),'Scale': VBase3(1.526, 1.526, 1.526),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257796806.06caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-87.122, 2.043, 40.716),'Pos': Point3(18.72, -0.841, 8.143),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797083.57caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.79, 0.0, 0.0),'Pos': Point3(18.638, -0.171, 7.708),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797129.54caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(88.954, 0.0, 0.0),'Pos': Point3(-18.447, -0.237, 7.451),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797143.12caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(93.614, 0.0, 39.463),'Pos': Point3(18.631, 0.367, 8.109),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797208.82caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.642, 0.0, 39.463),'Pos': Point3(-18.461, -0.775, 7.853),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.76caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-88.642, 0.0, 39.463),'Pos': Point3(-18.461, -0.775, 7.853),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797277.77caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(88.954, 0.0, 0.0),'Pos': Point3(-18.447, -0.237, 7.451),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}},'1257797342.72caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-1.881, 2.043, 40.716),'Pos': Point3(-2.685, 11.691, 7.305),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797342.74caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(178.855, 0.0, 39.463),'Pos': Point3(-3.896, 11.702, 7.271),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_candycane_winter09'}},'1257797342.75caoconno': {'Type': 'Holiday','DisableCollision': False,'Holiday': 'WinterFestival','Hpr': VBase3(-3.548, 0.0, 0.0),'Pos': Point3(-3.359, 11.664, 6.869),'Scale': VBase3(1.0, 1.0, 1.0),'VisSize': '','Visual': {'Model': 'models/props/pir_m_prp_hol_decoBow_winter08'}}},'Visual': {'Model': 'models/buildings/interior_shanty_npc_house'}}},'Node Links': [],'Layers': {},'ObjectIds': {'1156371286.47dzzz0': '["Objects"]["1156371286.47dzzz0"]','1165344228.45kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344228.45kmuller"]','1165344324.52kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344324.52kmuller"]','1165344556.34kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]','1165344792.45kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344792.45kmuller"]','1166055838.34kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166055838.34kmuller"]','1166130817.64kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130817.64kmuller"]','1166130858.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130858.42kmuller"]','1166130963.4kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166130963.4kmuller"]','1166131071.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166131071.71kmuller"]','1166131830.51kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166131830.51kmuller"]','1166132516.06kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132516.06kmuller"]','1166132600.56kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132600.56kmuller"]','1166132865.18kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132865.18kmuller"]','1166132969.78kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166132969.78kmuller"]','1166133856.57kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166133856.57kmuller"]','1166135474.96kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135474.96kmuller"]','1166135589.98kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135589.98kmuller"]','1166135667.84kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135667.84kmuller"]','1166135716.21kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135716.21kmuller"]','1166135765.92kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166135765.92kmuller"]','1166137677.04kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166137677.04kmuller"]','1166137745.73kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1166137745.73kmuller"]','1167157033.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157033.71kmuller"]','1167157096.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157096.42kmuller"]','1167157149.32kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157149.32kmuller"]','1167157231.2kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167157231.2kmuller"]','1167159781.48kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167159781.48kmuller"]','1167970188.36kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970188.36kmuller"]','1167970378.72kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970378.72kmuller"]','1167970427.75kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970427.75kmuller"]','1167970512.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970512.58kmuller"]','1167970583.19kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970583.19kmuller"]','1167970625.67kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970625.67kmuller"]','1167970646.1kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1167970646.1kmuller"]','1174674177.41dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674177.41dzlu"]','1174674352.51dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674352.51dzlu"]','1174674462.48dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1174674462.48dzlu"]','1176403754.48dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1176403754.48dzlu"]','1176403947.28dzlu': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1176403947.28dzlu"]','1185407971.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185407971.87kmuller"]','1185408052.75kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408052.75kmuller"]','1185408099.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408099.87kmuller"]','1185408199.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408199.58kmuller"]','1185408310.17kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408310.17kmuller"]','1185408375.03kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408310.17kmuller"]["Objects"]["1185408375.03kmuller"]','1185408420.62kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408420.62kmuller"]','1185408515.58kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408515.58kmuller"]','1185408562.87kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408562.87kmuller"]','1185408657.03kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408657.03kmuller"]','1185408806.71kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408806.71kmuller"]','1185408860.26kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408860.26kmuller"]','1185408961.95kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185408961.95kmuller"]','1185409015.65kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1185409015.65kmuller"]','1205367433.42kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1205367433.42kmuller"]','1228170667.7kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170667.7kmuller"]','1228170701.94kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170701.94kmuller"]','1228170770.86kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170770.86kmuller"]','1228170797.78kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170797.78kmuller"]','1228170869.25kmuller': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1228170869.25kmuller"]','1257372614.06caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257372614.06caoconno"]','1257796806.06caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257796806.06caoconno"]','1257796843.25caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]["Objects"]["1257796843.25caoconno"]','1257797083.57caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797083.57caoconno"]','1257797129.54caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797129.54caoconno"]','1257797143.12caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797143.12caoconno"]','1257797208.82caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797208.82caoconno"]','1257797277.72caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1165344556.34kmuller"]["Objects"]["1257797277.72caoconno"]','1257797277.76caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797277.76caoconno"]','1257797277.77caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797277.77caoconno"]','1257797342.72caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.72caoconno"]','1257797342.74caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.74caoconno"]','1257797342.75caoconno': '["Objects"]["1156371286.47dzzz0"]["Objects"]["1257797342.75caoconno"]'}} extraInfo = {'camPos': Point3(38.4972, 15.2174, 22.107),'camHpr': VBase3(119.723, -14.2124, 0),'focalLength': 0.657999992371,'skyState': -1,'fog': 0}
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : security_sm3 Case Name : 创建用户时的加密算法sm3,认证方式MD5,非初始用户错误的密码通过JDBC连接数据库 Description : 1.修改password_encryption_type=3 2.pg_hba.conf文件中修改认证方式为MD5 3.非初始用户错误的密码通过JDBC登录数据库 Expect : 1-2.参数设置成功 3.数据库连接失败 History : """ import os import unittest from yat.test import Node from yat.test import macro from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger class Security(unittest.TestCase): def setUp(self): self.logger = Logger() self.logger.info('--Opengauss_Function_Security_sm3_Case0045 start--') self.userNode = Node('PrimaryDbUser') self.primary_root = Node('PrimaryRoot') self.DB_ENV_PATH = macro.DB_ENV_PATH self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH self.sh_primy = CommonSH('PrimaryDbUser') self.common = Common() self.user = 'u_security_sm3_0045' self.targetpath = "/home/jdbc_test" self.properties = os.path.join(self.targetpath, "jdbc_connect.conf") self.java_name = "jdbc_drop_schema_case0001" self.script_name = 'bcprov-jdk15on-1.68' self.config = os.path.join(self.DB_INSTANCE_PATH, 'pg_hba.conf') self.confignew = os.path.join(self.DB_INSTANCE_PATH, 'pg_hba_bak.conf') self.logger.info('--------获取参数默认值--------') self.default_msg_list = '' check_default = 'show password_encryption_type;' default_msg = self.sh_primy.execut_db_sql(check_default) self.logger.info(default_msg) self.default_msg_list = default_msg.splitlines()[2].strip() self.logger.info(self.default_msg_list) self.logger.info('--------备份白名单文件---------') cp_cmd = f"cp {self.config} {self.confignew}" self.userNode.sh(cp_cmd).result() def test_encrypted(self): text = '---step1:修改password_encryption_type=3;expect:成功---' self.logger.info(text) exe_cmd1 = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {self.DB_INSTANCE_PATH} -c ' \ '"password_encryption_type=3"' msg1 = self.userNode.sh(exe_cmd1).result() self.logger.info(msg1) check_cmd = 'show password_encryption_type;' check_msg = self.sh_primy.execut_db_sql(check_cmd) self.logger.info(check_msg) self.common.equal_sql_mdg(check_msg, 'password_encryption_type', '3', '(1 row)', flag='1') text = '---step2:pg_hba.conf文件中增加认证方式为md5;expect:成功---' self.logger.info(text) exe_cmd2 = f'grep "IPv4 local connections:" {self.config}' msg2 = self.userNode.sh(exe_cmd2).result() self.logger.info(msg2) insert_messages = f"host {self.userNode.db_name} {self.user} " \ f"{self.userNode.db_host}/32 md5" exe_cmd3 = f'sed -i "/{msg2}/a\{insert_messages}" {self.config}' self.logger.info(exe_cmd3) msg3 = self.userNode.sh(exe_cmd3).result() self.logger.info(msg3) restart_cmd = f'source {macro.DB_ENV_PATH};' \ f'gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M primary' restart_msg = self.userNode.sh(restart_cmd).result() self.logger.info(restart_msg) text = '---step3:创建用户1;expect:成功---' self.logger.info(text) sql_cmd4 = f'create user {self.user} with password \'' \ f'{macro.COMMON_PASSWD}\';' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.assertIn('CREATE ROLE', msg4, '执行失败:' + text) text = '---step4.1:写入配置文件,用户1设置错误的密码;expect:成功---' self.logger.info(text) self.common.scp_file(self.primary_root, f"{self.java_name}.java", self.targetpath) self.common.scp_file(self.primary_root, f"{self.script_name}.jar", self.targetpath) result = self.primary_root.sh( f"touch {self.properties}").result() self.logger.info(result) error_passwd = macro.COMMON_PASSWD + '_error' config = f'echo "password={error_passwd}"> {self.properties}' self.primary_root.sh(config) config = f'echo "port={self.userNode.db_port}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'echo "hostname={self.userNode.db_host}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'echo "user={self.user}">> {self.properties}' self.primary_root.sh(config) config = f'echo "dbname={self.userNode.db_name}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'cat {self.properties}' result = self.primary_root.sh(config).result() assert1 = "password=" in result and "port=" in result and \ "hostname=" in result and "user=" in result and \ "dbname=" in result self.assertTrue(assert1, '执行失败:' + text) text = '---step4.2:编译java脚本;expect:成功---' self.logger.info(text) scp_cmd = self.primary_root.scp_put(macro.JDBC_PATH, f"{self.targetpath}/postgresql.jar") self.logger.info(scp_cmd) cmd = f"javac -encoding utf-8 -cp " \ f"{os.path.join(self.targetpath, "postgresql.jar")} " \ f"{os.path.join(self.targetpath, f"{self.java_name}.java")}" self.logger.info(cmd) result = self.primary_root.sh(cmd).result() self.logger.info(result) text = '---step4.3:运行java脚本,数据库连接成功;expect:成功---' self.logger.info(text) cmd = f"java -cp {os.path.join(self.targetpath, "postgresql.jar")}:" \ f"{os.path.join(self.targetpath, f"{self.script_name}.jar")}:" \ f"{self.targetpath} {self.java_name} -F" \ f" {self.properties}" self.logger.info(cmd) result = self.primary_root.sh(cmd).result() self.logger.info(result) self.assertIn('连接失败', result, '执行失败:' + text) def tearDown(self): self.logger.info('-------1.恢复配置文件中的信息------') check_cmd = f'if [ -f {self.config} ];then mv {self.confignew} ' \ f'{self.config};rm -rf {self.targetpath};fi' self.logger.info(check_cmd) self.primary_root.sh(check_cmd).result() restart_cmd = f'source {macro.DB_ENV_PATH};' \ f'gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M primary' restart_msg = self.userNode.sh(restart_cmd).result() self.logger.info(restart_msg) self.logger.info('-------2.恢复加密方式配置------') exe_cmd2 = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {self.DB_INSTANCE_PATH} -c ' \ f'"password_encryption_type={self.default_msg_list}"' msg2 = self.userNode.sh(exe_cmd2).result() self.logger.info(msg2) sql_cmd3 = 'show password_encryption_type;' msg3 = self.sh_primy.execut_db_sql(sql_cmd3) self.logger.info(msg3) self.logger.info('-------3.删除用户-------') sql_cmd4 = f'drop user {self.user}' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.logger.info( '----Opengauss_Function_Security_sm3_Case0045 finish----')
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : security_sm3 Case Name : 创建用户时的加密算法sm3,认证方式MD5,非初始用户错误的密码通过JDBC连接数据库 Description : 1.修改password_encryption_type=3 2.pg_hba.conf文件中修改认证方式为MD5 3.非初始用户错误的密码通过JDBC登录数据库 Expect : 1-2.参数设置成功 3.数据库连接失败 History : """ import os import unittest from yat.test import Node from yat.test import macro from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Logger import Logger class Security(unittest.TestCase): def setUp(self): self.logger = Logger() self.logger.info('--Opengauss_Function_Security_sm3_Case0045 start--') self.userNode = Node('PrimaryDbUser') self.primary_root = Node('PrimaryRoot') self.DB_ENV_PATH = macro.DB_ENV_PATH self.DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH self.sh_primy = CommonSH('PrimaryDbUser') self.common = Common() self.user = 'u_security_sm3_0045' self.targetpath = "/home/jdbc_test" self.properties = os.path.join(self.targetpath, "jdbc_connect.conf") self.java_name = "jdbc_drop_schema_case0001" self.script_name = 'bcprov-jdk15on-1.68' self.config = os.path.join(self.DB_INSTANCE_PATH, 'pg_hba.conf') self.confignew = os.path.join(self.DB_INSTANCE_PATH, 'pg_hba_bak.conf') self.logger.info('--------获取参数默认值--------') self.default_msg_list = '' check_default = 'show password_encryption_type;' default_msg = self.sh_primy.execut_db_sql(check_default) self.logger.info(default_msg) self.default_msg_list = default_msg.splitlines()[2].strip() self.logger.info(self.default_msg_list) self.logger.info('--------备份白名单文件---------') cp_cmd = f"cp {self.config} {self.confignew}" self.userNode.sh(cp_cmd).result() def test_encrypted(self): text = '---step1:修改password_encryption_type=3;expect:成功---' self.logger.info(text) exe_cmd1 = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {self.DB_INSTANCE_PATH} -c ' \ '"password_encryption_type=3"' msg1 = self.userNode.sh(exe_cmd1).result() self.logger.info(msg1) check_cmd = 'show password_encryption_type;' check_msg = self.sh_primy.execut_db_sql(check_cmd) self.logger.info(check_msg) self.common.equal_sql_mdg(check_msg, 'password_encryption_type', '3', '(1 row)', flag='1') text = '---step2:pg_hba.conf文件中增加认证方式为md5;expect:成功---' self.logger.info(text) exe_cmd2 = f'grep "IPv4 local connections:" {self.config}' msg2 = self.userNode.sh(exe_cmd2).result() self.logger.info(msg2) insert_messages = f"host {self.userNode.db_name} {self.user} " \ f"{self.userNode.db_host}/32 md5" exe_cmd3 = f'sed -i "/{msg2}/a\{insert_messages}" {self.config}' self.logger.info(exe_cmd3) msg3 = self.userNode.sh(exe_cmd3).result() self.logger.info(msg3) restart_cmd = f'source {macro.DB_ENV_PATH};' \ f'gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M primary' restart_msg = self.userNode.sh(restart_cmd).result() self.logger.info(restart_msg) text = '---step3:创建用户1;expect:成功---' self.logger.info(text) sql_cmd4 = f'create user {self.user} with password \'' \ f'{macro.COMMON_PASSWD}\';' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.assertIn('CREATE ROLE', msg4, '执行失败:' + text) text = '---step4.1:写入配置文件,用户1设置错误的密码;expect:成功---' self.logger.info(text) self.common.scp_file(self.primary_root, f"{self.java_name}.java", self.targetpath) self.common.scp_file(self.primary_root, f"{self.script_name}.jar", self.targetpath) result = self.primary_root.sh( f"touch {self.properties}").result() self.logger.info(result) error_passwd = macro.COMMON_PASSWD + '_error' config = f'echo "password={error_passwd}"> {self.properties}' self.primary_root.sh(config) config = f'echo "port={self.userNode.db_port}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'echo "hostname={self.userNode.db_host}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'echo "user={self.user}">> {self.properties}' self.primary_root.sh(config) config = f'echo "dbname={self.userNode.db_name}">> ' \ f'{self.properties}' self.primary_root.sh(config) config = f'cat {self.properties}' result = self.primary_root.sh(config).result() assert1 = "password=" in result and "port=" in result and \ "hostname=" in result and "user=" in result and \ "dbname=" in result self.assertTrue(assert1, '执行失败:' + text) text = '---step4.2:编译java脚本;expect:成功---' self.logger.info(text) scp_cmd = self.primary_root.scp_put(macro.JDBC_PATH, f"{self.targetpath}/postgresql.jar") self.logger.info(scp_cmd) cmd = f"javac -encoding utf-8 -cp " \ f"{os.path.join(self.targetpath, 'postgresql.jar')} " \ f"{os.path.join(self.targetpath, f'{self.java_name}.java')}" self.logger.info(cmd) result = self.primary_root.sh(cmd).result() self.logger.info(result) text = '---step4.3:运行java脚本,数据库连接成功;expect:成功---' self.logger.info(text) cmd = f"java -cp {os.path.join(self.targetpath, 'postgresql.jar')}:" \ f"{os.path.join(self.targetpath, f'{self.script_name}.jar')}:" \ f"{self.targetpath} {self.java_name} -F" \ f" {self.properties}" self.logger.info(cmd) result = self.primary_root.sh(cmd).result() self.logger.info(result) self.assertIn('连接失败', result, '执行失败:' + text) def tearDown(self): self.logger.info('-------1.恢复配置文件中的信息------') check_cmd = f'if [ -f {self.config} ];then mv {self.confignew} ' \ f'{self.config};rm -rf {self.targetpath};fi' self.logger.info(check_cmd) self.primary_root.sh(check_cmd).result() restart_cmd = f'source {macro.DB_ENV_PATH};' \ f'gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M primary' restart_msg = self.userNode.sh(restart_cmd).result() self.logger.info(restart_msg) self.logger.info('-------2.恢复加密方式配置------') exe_cmd2 = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {self.DB_INSTANCE_PATH} -c ' \ f'"password_encryption_type={self.default_msg_list}"' msg2 = self.userNode.sh(exe_cmd2).result() self.logger.info(msg2) sql_cmd3 = 'show password_encryption_type;' msg3 = self.sh_primy.execut_db_sql(sql_cmd3) self.logger.info(msg3) self.logger.info('-------3.删除用户-------') sql_cmd4 = f'drop user {self.user}' msg4 = self.sh_primy.execut_db_sql(sql_cmd4) self.logger.info(msg4) self.logger.info( '----Opengauss_Function_Security_sm3_Case0045 finish----')
import logging import os from pathlib import Path from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.story_reader.story_reader import StoryReader from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) from rasa.shared.core.training_data.structures import StoryStep from rasa.shared.data import YAML_FILE_EXTENSIONS, MARKDOWN_FILE_EXTENSIONS logger = logging.getLogger(__name__) def _get_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if rasa.shared.data.is_likely_markdown_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) elif rasa.shared.data.is_likely_yaml_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) else: # This is a use case for uploading the story over REST API. # The source file has a random name. return _guess_reader(filename, domain, template_variables, use_e2e) def _guess_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if YAMLStoryReader.is_stories_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) elif MarkdownStoryReader.is_stories_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) raise ValueError( f"Failed to find a reader class for the story file `{filename}`. " f"Supported formats are " f"{", ".join(MARKDOWN_FILE_EXTENSIONS + YAML_FILE_EXTENSIONS)}." ) async def load_data_from_resource( resource: Union[Text, Path], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified folder. Args: resource: Folder/File with core training data files. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies if the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ if not os.path.exists(resource): raise ValueError(f"Resource '{resource}' does not exist.") return await load_data_from_files( rasa.shared.utils.io.list_files(resource), domain, template_variables, use_e2e, exclusion_percentage, ) async def load_data_from_files( story_files: List[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified files. Args: story_files: List of files with training data in it. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies whether the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ story_steps = [] for story_file in story_files: reader = _get_reader(story_file, domain, template_variables, use_e2e) steps = reader.read_from_file(story_file) story_steps.extend(steps) if exclusion_percentage and exclusion_percentage != 100: import random idx = int(round(exclusion_percentage / 100.0 * len(story_steps))) random.shuffle(story_steps) story_steps = story_steps[:-idx] return story_steps
import logging import os from pathlib import Path from typing import Text, Optional, Dict, List, Union import rasa.shared.data import rasa.shared.utils.io from rasa.shared.core.domain import Domain from rasa.shared.core.training_data.story_reader.markdown_story_reader import ( MarkdownStoryReader, ) from rasa.shared.core.training_data.story_reader.story_reader import StoryReader from rasa.shared.core.training_data.story_reader.yaml_story_reader import ( YAMLStoryReader, ) from rasa.shared.core.training_data.structures import StoryStep from rasa.shared.data import YAML_FILE_EXTENSIONS, MARKDOWN_FILE_EXTENSIONS logger = logging.getLogger(__name__) def _get_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if rasa.shared.data.is_likely_markdown_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) elif rasa.shared.data.is_likely_yaml_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) else: # This is a use case for uploading the story over REST API. # The source file has a random name. return _guess_reader(filename, domain, template_variables, use_e2e) def _guess_reader( filename: Text, domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, ) -> StoryReader: if YAMLStoryReader.is_stories_file(filename): return YAMLStoryReader(domain, template_variables, use_e2e, filename) elif MarkdownStoryReader.is_stories_file(filename): return MarkdownStoryReader(domain, template_variables, use_e2e, filename) raise ValueError( f"Failed to find a reader class for the story file `{filename}`. " f"Supported formats are " f"{', '.join(MARKDOWN_FILE_EXTENSIONS + YAML_FILE_EXTENSIONS)}." ) async def load_data_from_resource( resource: Union[Text, Path], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified folder. Args: resource: Folder/File with core training data files. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies if the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ if not os.path.exists(resource): raise ValueError(f"Resource '{resource}' does not exist.") return await load_data_from_files( rasa.shared.utils.io.list_files(resource), domain, template_variables, use_e2e, exclusion_percentage, ) async def load_data_from_files( story_files: List[Text], domain: Domain, template_variables: Optional[Dict] = None, use_e2e: bool = False, exclusion_percentage: Optional[int] = None, ) -> List["StoryStep"]: """Loads core training data from the specified files. Args: story_files: List of files with training data in it. domain: Domain object. template_variables: Variables that have to be replaced in the training data. use_e2e: Identifies whether the e2e reader should be used. exclusion_percentage: Identifies the percentage of training data that should be excluded from the training. Returns: Story steps from the training data. """ story_steps = [] for story_file in story_files: reader = _get_reader(story_file, domain, template_variables, use_e2e) steps = reader.read_from_file(story_file) story_steps.extend(steps) if exclusion_percentage and exclusion_percentage != 100: import random idx = int(round(exclusion_percentage / 100.0 * len(story_steps))) random.shuffle(story_steps) story_steps = story_steps[:-idx] return story_steps
import base64 import pathlib import sys import threading def read(path: pathlib.Path, stdout_lock: threading.Lock): with path.open(mode='rb') as file, stdout_lock: sys.stdout.write( f'{{'contents':'{base64.b64encode(file.read()).decode('utf-8')}"}}\n', ) sys.stdout.flush()
import base64 import pathlib import sys import threading def read(path: pathlib.Path, stdout_lock: threading.Lock): with path.open(mode='rb') as file, stdout_lock: sys.stdout.write( f'{{"contents":"{base64.b64encode(file.read()).decode("utf-8")}"}}\n', ) sys.stdout.flush()
# coding: utf-8 """JupyterLab command handler""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import contextlib import errno import hashlib import itertools import json import logging import os import os.path as osp import re import shutil import stat import site import subprocess import sys import tarfile import warnings from copy import deepcopy from glob import glob from pathlib import Path from tempfile import TemporaryDirectory from threading import Event from urllib.error import URLError from urllib.request import Request, quote, urljoin, urlopen from jupyter_core.paths import jupyter_config_path from jupyter_server.extension.serverextension import GREEN_ENABLED, GREEN_OK, RED_DISABLED, RED_X from jupyterlab_server.config import (LabConfig, get_federated_extensions, get_package_url, get_page_config, get_static_page_config, write_page_config) from jupyterlab_server.process import Process, WatchHelper, list2cmdline, which from packaging.version import Version from traitlets import Bool, Dict, HasTraits, Instance, List, Unicode, default from jupyterlab.coreconfig import CoreConfig from jupyterlab.jlpmapp import HERE, YARN_PATH from jupyterlab.semver import Range, gt, gte, lt, lte, make_semver from jupyterlab._version import __version__ # The regex for expecting the webpack output. WEBPACK_EXPECT = re.compile(r'.*theme-light-extension/style/index.css') # The repo root directory REPO_ROOT = osp.abspath(osp.join(HERE, '..')) # The dev mode directory. DEV_DIR = osp.join(REPO_ROOT, 'dev_mode') # If we are pinning the package, rename it `pin@<alias>` PIN_PREFIX = 'pin@' # Default Yarn registry used in default yarn.lock YARN_DEFAULT_REGISTRY = 'https://registry.yarnpkg.com' class ProgressProcess(Process): def __init__(self, cmd, logger=None, cwd=None, kill_event=None, env=None): """Start a subprocess that can be run asynchronously. Parameters ---------- cmd: list The command to run. logger: :class:`~logger.Logger`, optional The logger instance. cwd: string, optional The cwd of the process. kill_event: :class:`~threading.Event`, optional An event used to kill the process operation. env: dict, optional The environment for the process. """ if not isinstance(cmd, (list, tuple)): raise ValueError('Command must be given as a list') if kill_event and kill_event.is_set(): raise ValueError('Process aborted') self.logger = _ensure_logger(logger) self._last_line = '' self.cmd = cmd self.logger.debug('> ' + list2cmdline(cmd)) self.proc = self._create_process( cwd=cwd, env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, universal_newlines=True, encoding='utf-8', ) self._kill_event = kill_event or Event() Process._procs.add(self) def wait(self): cache = [] proc = self.proc kill_event = self._kill_event spinner = itertools.cycle(['-', '\\', '|', '/']) while proc.poll() is None: sys.stdout.write(next(spinner)) # write the next character sys.stdout.flush() # flush stdout buffer (actual character display) sys.stdout.write('\b') if kill_event.is_set(): self.terminate() raise ValueError('Process was aborted') try: out, _ = proc.communicate(timeout=.1) cache.append(out) except subprocess.TimeoutExpired: continue self.logger.debug('\n'.join(cache)) sys.stdout.flush() return self.terminate() def pjoin(*args): """Join paths to create a real path. """ return osp.abspath(osp.join(*args)) def get_user_settings_dir(): """Get the configured JupyterLab user settings directory. """ settings_dir = os.environ.get('JUPYTERLAB_SETTINGS_DIR') settings_dir = settings_dir or pjoin( jupyter_config_path()[0], 'lab', 'user-settings' ) return osp.abspath(settings_dir) def get_workspaces_dir(): """Get the configured JupyterLab workspaces directory. """ workspaces_dir = os.environ.get('JUPYTERLAB_WORKSPACES_DIR') workspaces_dir = workspaces_dir or pjoin( jupyter_config_path()[0], 'lab', 'workspaces' ) return osp.abspath(workspaces_dir) def get_app_dir(): """Get the configured JupyterLab app directory. """ # Default to the override environment variable. if os.environ.get('JUPYTERLAB_DIR'): # We must resolve the path to get the canonical case of the path for # case-sensitive systems return str(Path(os.environ['JUPYTERLAB_DIR']).resolve()) # Use the default locations for data_files. app_dir = pjoin(sys.prefix, 'share', 'jupyter', 'lab') # Check for a user level install. # Ensure that USER_BASE is defined if hasattr(site, 'getuserbase'): site.getuserbase() userbase = getattr(site, 'USER_BASE', None) if HERE.startswith(userbase) and not app_dir.startswith(userbase): app_dir = pjoin(userbase, 'share', 'jupyter', 'lab') # Check for a system install in '/usr/local/share'. elif (sys.prefix.startswith('/usr') and not osp.exists(app_dir) and osp.exists('/usr/local/share/jupyter/lab')): app_dir = '/usr/local/share/jupyter/lab' # We must resolve the path to get the canonical case of the path for # case-sensitive systems return str(Path(app_dir).resolve()) def dedupe_yarn(path, logger=None): """ `yarn-deduplicate` with the `fewer` strategy to minimize total packages installed in a given staging directory This means a extension (or dependency) _could_ cause a downgrade of an version expected at publication time, but core should aggressively set pins above, for example, known-bad versions """ had_dupes = ProgressProcess( ['node', YARN_PATH, 'yarn-deduplicate', '-s', 'fewer', '--fail'], cwd=path, logger=logger ).wait() != 0 if had_dupes: yarn_proc = ProgressProcess(['node', YARN_PATH], cwd=path, logger=logger) yarn_proc.wait() def ensure_node_modules(cwd, logger=None): """Ensure that node_modules is up to date. Returns true if the node_modules was updated. """ logger = _ensure_logger(logger) yarn_proc = ProgressProcess(['node', YARN_PATH, 'check', '--verify-tree'], cwd=cwd, logger=logger) ret = yarn_proc.wait() # Update node_modules if needed. if ret != 0: yarn_proc = ProgressProcess(['node', YARN_PATH], cwd=cwd, logger=logger) yarn_proc.wait() dedupe_yarn(REPO_ROOT, logger) return ret != 0 def ensure_dev(logger=None): """Ensure that the dev assets are available. """ logger = _ensure_logger(logger) target = pjoin(DEV_DIR, 'static') # Determine whether to build. if ensure_node_modules(REPO_ROOT, logger) or not osp.exists(target): yarn_proc = ProgressProcess(['node', YARN_PATH, 'build'], cwd=REPO_ROOT, logger=logger) yarn_proc.wait() def ensure_core(logger=None): """Ensure that the core assets are available. """ staging = pjoin(HERE, 'staging') logger = _ensure_logger(logger) # Determine whether to build. target = pjoin(HERE, 'static', 'index.html') if not osp.exists(target): ensure_node_modules(staging, logger) yarn_proc = ProgressProcess(['node', YARN_PATH, 'build'], cwd=staging, logger=logger) yarn_proc.wait() def ensure_app(app_dir): """Ensure that an application directory is available. If it does not exist, return a list of messages to prompt the user. """ if osp.exists(pjoin(app_dir, 'static', 'index.html')): return msgs = ['JupyterLab application assets not found in "%s"' % app_dir, 'Please run `jupyter lab build` or use a different app directory'] return msgs def watch_packages(logger=None): """Run watch mode for the source packages. Parameters ---------- logger: :class:`~logger.Logger`, optional The logger instance. Returns ------- A list of `WatchHelper` objects. """ logger = _ensure_logger(logger) ensure_node_modules(REPO_ROOT, logger) ts_dir = osp.abspath(osp.join(REPO_ROOT, 'packages', 'metapackage')) # Run typescript watch and wait for the string indicating it is done. ts_regex = r'.* Found 0 errors\. Watching for file changes\.' ts_proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=ts_dir, logger=logger, startup_regex=ts_regex) return [ts_proc] def watch_dev(logger=None): """Run watch mode in a given directory. Parameters ---------- logger: :class:`~logger.Logger`, optional The logger instance. Returns ------- A list of `WatchHelper` objects. """ logger = _ensure_logger(logger) package_procs = watch_packages(logger) # Run webpack watch and wait for compilation. wp_proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=DEV_DIR, logger=logger, startup_regex=WEBPACK_EXPECT) return package_procs + [wp_proc] class AppOptions(HasTraits): """Options object for build system""" def __init__(self, logger=None, core_config=None, **kwargs): if core_config is not None: kwargs['core_config'] = core_config if logger is not None: kwargs['logger'] = logger # use the default if app_dir is empty if 'app_dir' in kwargs and not kwargs['app_dir']: kwargs.pop('app_dir') super(AppOptions, self).__init__(**kwargs) app_dir = Unicode(help='The application directory') use_sys_dir = Bool( True, help=('Whether to shadow the default app_dir if that is set to a ' 'non-default value')) logger = Instance(logging.Logger, help='The logger to use') core_config = Instance(CoreConfig, help='Configuration for core data') kill_event = Instance(Event, args=(), help='Event for aborting call') labextensions_path = List(Unicode(), help='The paths to look in for prebuilt JupyterLab extensions') registry = Unicode(help="NPM packages registry URL") splice_source = Bool(False, help="Splice source packages into app directory.") @default('logger') def _default_logger(self): return logging.getLogger('jupyterlab') # These defaults need to be federated to pick up # any changes to env vars: @default('app_dir') def _default_app_dir(self): return get_app_dir() @default('core_config') def _default_core_config(self): return CoreConfig() @default('registry') def _default_registry(self): config = _yarn_config(self.logger)["yarn config"] return config.get("registry", YARN_DEFAULT_REGISTRY) def _ensure_options(options): """Helper to use deprecated kwargs for AppOption""" if options is None: return AppOptions() elif issubclass(options.__class__, AppOptions): return options else: return AppOptions(**options) def watch(app_options=None): """Watch the application. Parameters ---------- app_options: :class:`AppOptions`, optional The application options. Returns ------- A list of processes to run asynchronously. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if app_options.splice_source: package_procs = watch_packages(app_options.logger) else: package_procs = [] return package_procs + handler.watch() def install_extension(extension, app_options=None, pin=None): """Install an extension package into JupyterLab. The extension is first validated. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.install_extension(extension, pin=pin) def uninstall_extension(name=None, app_options=None, all_=False): """Uninstall an extension by name or path. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if all_ is True: return handler.uninstall_all_extensions() return handler.uninstall_extension(name) def update_extension(name=None, all_=False, app_dir=None, app_options=None): """Update an extension by name, or all extensions. Either `name` must be given as a string, or `all_` must be `True`. If `all_` is `True`, the value of `name` is ignored. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if all_ is True: return handler.update_all_extensions() return handler.update_extension(name) def clean(app_options=None): """Clean the JupyterLab application directory.""" app_options = _ensure_options(app_options) handler = _AppHandler(app_options) logger = app_options.logger app_dir = app_options.app_dir logger.info('Cleaning %s...', app_dir) if app_dir == pjoin(HERE, 'dev'): raise ValueError('Cannot clean the dev app') if app_dir == pjoin(HERE, 'core'): raise ValueError('Cannot clean the core app') if getattr(app_options, 'all', False): logger.info('Removing everything in %s...', app_dir) _rmtree_star(app_dir, logger) else: possibleTargets = ['extensions', 'settings', 'staging', 'static'] targets = [t for t in possibleTargets if getattr(app_options, t)] for name in targets: target = pjoin(app_dir, name) if osp.exists(target): logger.info('Removing %s...', name) _rmtree(target, logger) else: logger.info('%s not present, skipping...', name) logger.info('Success!') if getattr(app_options, 'all', False) or getattr(app_options, 'extensions', False): logger.info('All of your extensions have been removed, and will need to be reinstalled') def build(name=None, version=None, static_url=None, kill_event=None, clean_staging=False, app_options=None, production=True, minimize=True): """Build the JupyterLab application. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.build(name=name, version=version, static_url=static_url, production=production, minimize=minimize, clean_staging=clean_staging) def get_app_info(app_options=None): """Get a dictionary of information about the app. """ handler = _AppHandler(app_options) handler._ensure_disabled_info() return handler.info def enable_extension(extension, app_options=None, level='sys_prefix'): """Enable a JupyterLab extension. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.toggle_extension(extension, False, level=level) def disable_extension(extension, app_options=None, level='sys_prefix'): """Disable a JupyterLab package. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.toggle_extension(extension, True, level=level) def check_extension(extension, installed=False, app_options=None): """Check if a JupyterLab extension is enabled or disabled. """ handler = _AppHandler(app_options) return handler.check_extension(extension, installed) def build_check(app_options=None): """Determine whether JupyterLab should be built. Returns a list of messages. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.build_check() def list_extensions(app_options=None): """List the extensions. """ handler = _AppHandler(app_options) return handler.list_extensions() def link_package(path, app_options=None): """Link a package against the JupyterLab build. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.link_package(path) def unlink_package(package, app_options=None): """Unlink a package from JupyterLab by path or name. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.unlink_package(package) def get_app_version(app_options=None): """Get the application version.""" handler = _AppHandler(app_options) return handler.info['version'] def get_latest_compatible_package_versions(names, app_options=None): """Get the latest compatible version of a list of packages. """ handler = _AppHandler(app_options) return handler.latest_compatible_package_versions(names) def read_package(target): """Read the package data in a given target tarball. """ tar = tarfile.open(target, "r") f = tar.extractfile('package/package.json') data = json.loads(f.read().decode('utf8')) data['jupyterlab_extracted_files'] = [ f.path[len('package/'):] for f in tar.getmembers() ] tar.close() return data # ---------------------------------------------------------------------- # Implementation details # ---------------------------------------------------------------------- class _AppHandler(object): def __init__(self, options): """Create a new _AppHandler object """ options = _ensure_options(options) self._options = options self.app_dir = options.app_dir self.sys_dir = get_app_dir() if options.use_sys_dir else self.app_dir self.logger = options.logger # Make a deep copy of the core data so we don't influence the original copy self.core_data = deepcopy(options.core_config._data) self.labextensions_path = options.labextensions_path self.kill_event = options.kill_event self.registry = options.registry # Do this last since it relies on other attributes self.info = self._get_app_info() def install_extension(self, extension, existing=None, pin=None): """Install an extension package into JupyterLab. The extension is first validated. Returns `True` if a rebuild is recommended, `False` otherwise. """ extension = _normalize_path(extension) extensions = self.info['extensions'] # Check for a core extensions. if extension in self.info['core_extensions']: config = self._read_build_config() uninstalled = config.get('uninstalled_core_extensions', []) if extension in uninstalled: self.logger.info('Installing core extension %s' % extension) uninstalled.remove(extension) config['uninstalled_core_extensions'] = uninstalled self._write_build_config(config) return True return False # Create the app dirs if needed. self._ensure_app_dirs() # Install the package using a temporary directory. with TemporaryDirectory() as tempdir: info = self._install_extension(extension, tempdir, pin=pin) name = info['name'] # Local directories get name mangled and stored in metadata. if info['is_dir']: config = self._read_build_config() local = config.setdefault('local_extensions', dict()) local[name] = info['source'] self._write_build_config(config) # Remove an existing extension with the same name and different path if name in extensions: other = extensions[name] if other['path'] != info['path'] and other['location'] == 'app': os.remove(other['path']) return True def build(self, name=None, version=None, static_url=None, clean_staging=False, production=True, minimize=True): """Build the application. """ if production is None: production = not (self.info['linked_packages'] or self.info['local_extensions']) if not production: minimize = False # If splicing, make sure the source packages are built if self._options.splice_source: ensure_node_modules(REPO_ROOT, logger=self.logger) self._run(['node', YARN_PATH, 'build:packages'], cwd=REPO_ROOT) info = ['production' if production else 'development'] if production: info.append('minimized' if minimize else 'not minimized') self.logger.info(f'Building jupyterlab assets ({', '.join(info)})') # Set up the build directory. app_dir = self.app_dir self._populate_staging( name=name, version=version, static_url=static_url, clean=clean_staging ) staging = pjoin(app_dir, 'staging') # Make sure packages are installed. ret = self._run(['node', YARN_PATH, 'install', '--non-interactive'], cwd=staging) if ret != 0: msg = 'npm dependencies failed to install' self.logger.debug(msg) raise RuntimeError(msg) # Build the app. dedupe_yarn(staging, self.logger) command = f'build:{'prod' if production else 'dev'}{':minimize' if minimize else ''}' ret = self._run(['node', YARN_PATH, 'run', command], cwd=staging) if ret != 0: msg = 'JupyterLab failed to build' self.logger.debug(msg) raise RuntimeError(msg) def watch(self): """Start the application watcher and then run the watch in the background. """ staging = pjoin(self.app_dir, 'staging') self._populate_staging() # Make sure packages are installed. self._run(['node', YARN_PATH, 'install'], cwd=staging) dedupe_yarn(staging, self.logger) proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=pjoin(self.app_dir, 'staging'), startup_regex=WEBPACK_EXPECT, logger=self.logger) return [proc] def list_extensions(self): """Print an output of the extensions. """ self._ensure_disabled_info() logger = self.logger info = self.info logger.info('JupyterLab v%s' % info['version']) if info['federated_extensions'] or info['extensions']: info['compat_errors'] = self._get_extension_compat() if info['federated_extensions']: self._list_federated_extensions() if info['extensions']: logger.info('Other labextensions (built into JupyterLab)') self._list_extensions(info, 'app') self._list_extensions(info, 'sys') local = info['local_extensions'] if local: logger.info('\n local extensions:') for name in sorted(local): logger.info(' %s: %s' % (name, local[name])) linked_packages = info['linked_packages'] if linked_packages: logger.info('\n linked packages:') for key in sorted(linked_packages): source = linked_packages[key]['source'] logger.info(' %s: %s' % (key, source)) uninstalled_core = info['uninstalled_core'] if uninstalled_core: logger.info('\nUninstalled core extensions:') [logger.info(' %s' % item) for item in sorted(uninstalled_core)] all_exts = list(info['federated_extensions']) + list(info['extensions']) + list(info['core_extensions']) # Ignore disabled extensions that are not installed disabled = [i for i in info['disabled'] if i.partition(':')[0] in all_exts] if disabled: logger.info('\nDisabled extensions:') for item in sorted(disabled): # Show that all plugins will be disabled if the whole extension matches if item in all_exts: item += ' (all plugins)' logger.info(' %s' % item) # Here check if modules are improperly shadowed improper_shadowed = [] for ext_name in self.info['shadowed_exts']: source_version = self.info['extensions'][ext_name]['version'] prebuilt_version = self.info['federated_extensions'][ext_name]['version'] if not gte(prebuilt_version, source_version, True): improper_shadowed.append(ext_name) if improper_shadowed: logger.info('\nThe following source extensions are overshadowed by older prebuilt extensions:') [logger.info(' %s' % name) for name in sorted(improper_shadowed)] messages = self.build_check(fast=True) if messages: logger.info('\nBuild recommended, please run `jupyter lab build`:') [logger.info(' %s' % item) for item in messages] def build_check(self, fast=False): """Determine whether JupyterLab should be built. Returns a list of messages. """ app_dir = self.app_dir local = self.info['local_extensions'] linked = self.info['linked_packages'] messages = [] # Check for no application. pkg_path = pjoin(app_dir, 'static', 'package.json') if not osp.exists(pkg_path): return ['No built application'] static_data = self.info['static_data'] old_jlab = static_data['jupyterlab'] old_deps = static_data.get('dependencies', dict()) # Look for mismatched version. static_version = old_jlab.get('version', '') if not static_version.endswith('-spliced'): core_version = old_jlab['version'] if Version(static_version) != Version(core_version): msg = 'Version mismatch: %s (built), %s (current)' return [msg % (static_version, core_version)] shadowed_exts = self.info['shadowed_exts'] # Look for mismatched extensions. new_package = self._get_package_template(silent=fast) new_jlab = new_package['jupyterlab'] new_deps = new_package.get('dependencies', dict()) for ext_type in ['extensions', 'mimeExtensions']: # Extensions that were added. for ext in new_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in old_jlab[ext_type]: messages.append('%s needs to be included in build' % ext) # Extensions that were removed. for ext in old_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in new_jlab[ext_type]: messages.append('%s needs to be removed from build' % ext) # Look for mismatched dependencies src_pkg_dir = pjoin(REPO_ROOT, 'packages') for (pkg, dep) in new_deps.items(): if old_deps.get(pkg, '').startswith(src_pkg_dir): continue if pkg not in old_deps: continue # Skip local and linked since we pick them up separately. if pkg in local or pkg in linked: continue if old_deps[pkg] != dep: msg = '%s changed from %s to %s' messages.append(msg % (pkg, old_deps[pkg], new_deps[pkg])) # Look for updated local extensions. for (name, source) in local.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, 'extensions') if self._check_local(name, source, dname): messages.append('%s content changed' % name) # Look for updated linked packages. for (name, item) in linked.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, 'staging', 'linked_packages') if self._check_local(name, item['source'], dname): messages.append('%s content changed' % name) return messages def uninstall_extension(self, name): """Uninstall an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ info = self.info logger = self.logger if name in info['federated_extensions']: if info['federated_extensions'][name].get('install', dict()).get('uninstallInstructions', None): logger.error('JupyterLab cannot uninstall this extension. %s' % info['federated_extensions'][name]['install']['uninstallInstructions']) else: logger.error('JupyterLab cannot uninstall %s since it was installed outside of JupyterLab. Use the same method used to install this extension to uninstall this extension.' % name) return False # Allow for uninstalled core extensions. if name in info['core_extensions']: config = self._read_build_config() uninstalled = config.get('uninstalled_core_extensions', []) if name not in uninstalled: logger.info('Uninstalling core extension %s' % name) uninstalled.append(name) config['uninstalled_core_extensions'] = uninstalled self._write_build_config(config) return True return False local = info['local_extensions'] for (extname, data) in info['extensions'].items(): path = data['path'] if extname == name: msg = 'Uninstalling %s from %s' % (name, osp.dirname(path)) logger.info(msg) os.remove(path) # Handle local extensions. if extname in local: config = self._read_build_config() data = config.setdefault('local_extensions', dict()) del data[extname] self._write_build_config(config) return True logger.warn('No labextension named "%s" installed' % name) return False def uninstall_all_extensions(self): """Uninstalls all extensions Returns `True` if a rebuild is recommended, `False` otherwise """ should_rebuild = False for (extname, _) in self.info['extensions'].items(): uninstalled = self.uninstall_extension(extname) should_rebuild = should_rebuild or uninstalled return should_rebuild def update_all_extensions(self): """Update all non-local extensions. Returns `True` if a rebuild is recommended, `False` otherwise. """ should_rebuild = False for (extname, _) in self.info['extensions'].items(): if extname in self.info['local_extensions']: continue updated = self._update_extension(extname) # Rebuild if at least one update happens: should_rebuild = should_rebuild or updated return should_rebuild def update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ if name not in self.info['extensions']: self.logger.warning('No labextension named "%s" installed' % name) return False return self._update_extension(name) def _update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ data = self.info['extensions'][name] if data["alias_package_source"]: self.logger.warn("Skipping updating pinned extension '%s'." % name) return False try: latest = self._latest_compatible_package_version(name) except URLError: return False if latest is None: self.logger.warn('No compatible version found for %s!' % (name,)) return False if latest == data['version']: self.logger.info('Extension %r already up to date' % name) return False self.logger.info('Updating %s to version %s' % (name, latest)) return self.install_extension('%s@%s' % (name, latest)) def link_package(self, path): """Link a package at the given path. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) if not osp.exists(path) or not osp.isdir(path): msg = 'Cannot install "%s" only link local directories' raise ValueError(msg % path) with TemporaryDirectory() as tempdir: info = self._extract_package(path, tempdir) messages = _validate_extension(info['data']) if not messages: return self.install_extension(path) # Warn that it is a linked package. self.logger.warning('Installing %s as a linked package because it does not have extension metadata:', path) [self.logger.warning(' %s' % m) for m in messages] # Add to metadata. config = self._read_build_config() linked = config.setdefault('linked_packages', dict()) linked[info['name']] = info['source'] self._write_build_config(config) return True def unlink_package(self, path): """Unlink a package by name or at the given path. A ValueError is raised if the path is not an unlinkable package. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) config = self._read_build_config() linked = config.setdefault('linked_packages', dict()) found = None for (name, source) in linked.items(): if name == path or source == path: found = name if found: del linked[found] else: local = config.setdefault('local_extensions', dict()) for (name, source) in local.items(): if name == path or source == path: found = name if found: del local[found] path = self.info['extensions'][found]['path'] os.remove(path) if not found: raise ValueError('No linked package for %s' % path) self._write_build_config(config) return True def toggle_extension(self, extension, value, level='sys_prefix'): """Enable or disable a lab extension. Returns `True` if a rebuild is recommended, `False` otherwise. """ lab_config = LabConfig() app_settings_dir = osp.join(self.app_dir, 'settings') page_config = get_static_page_config(app_settings_dir=app_settings_dir, logger=self.logger, level=level) disabled = page_config.get('disabledExtensions', {}) did_something = False is_disabled = disabled.get(extension, False) if value and not is_disabled: disabled[extension] = True did_something = True elif not value and is_disabled: disabled[extension] = False did_something = True if did_something: page_config['disabledExtensions'] = disabled write_page_config(page_config, level=level) return did_something def check_extension(self, extension, check_installed_only=False): """Check if a lab extension is enabled or disabled """ self._ensure_disabled_info() info = self.info if extension in info["core_extensions"]: return self._check_core_extension( extension, info, check_installed_only) if extension in info["linked_packages"]: self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True return self._check_common_extension( extension, info, check_installed_only) def _check_core_extension(self, extension, info, check_installed_only): """Check if a core extension is enabled or disabled """ if extension in info['uninstalled_core']: self.logger.info('%s:%s' % (extension, RED_X)) return False if check_installed_only: self.logger.info('%s: %s' % (extension, GREEN_OK)) return True if extension in info['disabled_core']: self.logger.info('%s: %s' % (extension, RED_DISABLED)) return False self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True def _check_common_extension(self, extension, info, check_installed_only): """Check if a common (non-core) extension is enabled or disabled """ if extension not in info['extensions']: self.logger.info('%s:%s' % (extension, RED_X)) return False errors = self._get_extension_compat()[extension] if errors: self.logger.info('%s:%s (compatibility errors)' % (extension, RED_X)) return False if check_installed_only: self.logger.info('%s: %s' % (extension, GREEN_OK)) return True if _is_disabled(extension, info['disabled']): self.logger.info('%s: %s' % (extension, RED_DISABLED)) return False self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True def _get_app_info(self): """Get information about the app. """ info = dict() info['core_data'] = core_data = self.core_data info['extensions'] = extensions = self._get_extensions(core_data) info['local_extensions'] = self._get_local_extensions() info['linked_packages'] = self._get_linked_packages() info['app_extensions'] = app = [] info['sys_extensions'] = sys = [] for (name, data) in extensions.items(): data['is_local'] = name in info['local_extensions'] if data['location'] == 'app': app.append(name) else: sys.append(name) info['uninstalled_core'] = self._get_uninstalled_core_extensions() info['static_data'] = _get_static_data(self.app_dir) app_data = info['static_data'] or core_data info['version'] = app_data['jupyterlab']['version'] info['staticUrl'] = app_data['jupyterlab'].get('staticUrl', '') info['sys_dir'] = self.sys_dir info['app_dir'] = self.app_dir info['core_extensions'] = _get_core_extensions(self.core_data) info['federated_extensions'] = get_federated_extensions(self.labextensions_path) info['shadowed_exts'] = [ext for ext in info['extensions'] if ext in info['federated_extensions']] return info def _ensure_disabled_info(self): info = self.info if 'disabled' in info: return labextensions_path = self.labextensions_path app_settings_dir = osp.join(self.app_dir, 'settings') page_config = get_page_config(labextensions_path, app_settings_dir=app_settings_dir, logger=self.logger) info['disabled'] = page_config.get('disabledExtensions', []) disabled_core = [] for key in info['core_extensions']: if key in info['disabled']: disabled_core.append(key) info['disabled_core'] = disabled_core def _populate_staging(self, name=None, version=None, static_url=None, clean=False): """Set up the assets in the staging directory. """ app_dir = self.app_dir staging = pjoin(app_dir, 'staging') if clean and osp.exists(staging): self.logger.info("Cleaning %s", staging) _rmtree(staging, self.logger) self._ensure_app_dirs() if not version: version = self.info['core_data']['jupyterlab']['version'] splice_source = self._options.splice_source if splice_source: self.logger.debug('Splicing dev packages into app directory.') source_dir = DEV_DIR version = __version__ + '-spliced' else: source_dir = pjoin(HERE, 'staging') # Look for mismatched version. pkg_path = pjoin(staging, 'package.json') if osp.exists(pkg_path): with open(pkg_path) as fid: data = json.load(fid) if data['jupyterlab'].get('version', '') != version: _rmtree(staging, self.logger) os.makedirs(staging) for fname in ['index.js', 'bootstrap.js', 'publicpath.js', 'webpack.config.js', 'webpack.prod.config.js', 'webpack.prod.minimize.config.js']: target = pjoin(staging, fname) shutil.copy(pjoin(source_dir, fname), target) for fname in ['.yarnrc', 'yarn.js']: target = pjoin(staging, fname) shutil.copy(pjoin(HERE, 'staging', fname), target) # Ensure a clean templates directory templates = pjoin(staging, 'templates') if osp.exists(templates): _rmtree(templates, self.logger) try: shutil.copytree(pjoin(source_dir, 'templates'), templates) except shutil.Error as error: # `copytree` throws an error if copying to + from NFS even though # the copy is successful (see https://bugs.python.org/issue24564 # and https://github.com/jupyterlab/jupyterlab/issues/5233) real_error = '[Errno 22]' not in str(error) and '[Errno 5]' not in str(error) if real_error or not osp.exists(templates): raise # Ensure a clean linked packages directory. linked_dir = pjoin(staging, 'linked_packages') if osp.exists(linked_dir): _rmtree(linked_dir, self.logger) os.makedirs(linked_dir) # Template the package.json file. # Update the local extensions. extensions = self.info['extensions'] removed = False for (key, source) in self.info['local_extensions'].items(): # Handle a local extension that was removed. if key not in extensions: config = self._read_build_config() data = config.setdefault('local_extensions', dict()) del data[key] self._write_build_config(config) removed = True continue dname = pjoin(app_dir, 'extensions') self._update_local(key, source, dname, extensions[key], 'local_extensions') # Update the list of local extensions if any were removed. if removed: self.info['local_extensions'] = self._get_local_extensions() # Update the linked packages. linked = self.info['linked_packages'] for (key, item) in linked.items(): dname = pjoin(staging, 'linked_packages') self._update_local(key, item['source'], dname, item, 'linked_packages') # Then get the package template. data = self._get_package_template() jlab = data['jupyterlab'] if version: jlab['version'] = version if name: jlab['name'] = name if static_url: jlab['staticUrl'] = static_url # Handle splicing of packages if splice_source: # Splice workspace tree as linked dependencies for path in glob(pjoin(REPO_ROOT, 'packages', '*', 'package.json')): local_path = osp.dirname(osp.abspath(path)) pkg_data = json.loads(Path(path).read_text(encoding='utf-8')) name = pkg_data['name'] if name in data['dependencies']: data['dependencies'][name] = local_path jlab['linkedPackages'][name] = local_path if name in data['resolutions']: data['resolutions'][name] = local_path # splice the builder as well local_path = osp.abspath(pjoin(REPO_ROOT, 'builder')) data['devDependencies']['@jupyterlab/builder'] = local_path target = osp.join(staging, 'node_modules', '@jupyterlab', 'builder') # Remove node_modules so it gets re-populated node_modules = pjoin(staging, 'node_modules') if osp.exists(node_modules): shutil.rmtree(node_modules, ignore_errors=True) # Write the package file pkg_path = pjoin(staging, 'package.json') with open(pkg_path, 'w') as fid: json.dump(data, fid, indent=4) # copy known-good yarn.lock if missing lock_path = pjoin(staging, 'yarn.lock') lock_template = pjoin(HERE, 'staging', 'yarn.lock') if self.registry != YARN_DEFAULT_REGISTRY: # Replace on the fly the yarn repository see #3658 with open(lock_template, encoding='utf-8') as f: template = f.read() template = template.replace(YARN_DEFAULT_REGISTRY, self.registry.strip("/")) with open(lock_path, 'w', encoding='utf-8') as f: f.write(template) elif not osp.exists(lock_path): shutil.copy(lock_template, lock_path) os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD) def _get_package_template(self, silent=False): """Get the template the for staging package.json file. """ logger = self.logger # make a deep copy of the data so we don't influence the core data data = deepcopy(self.info['core_data']) local = self.info['local_extensions'] linked = self.info['linked_packages'] extensions = self.info['extensions'] shadowed_exts = self.info['shadowed_exts'] jlab = data['jupyterlab'] def format_path(path): path = osp.relpath(path, pjoin(self.app_dir, 'staging')) path = 'file:' + path.replace(os.sep, '/') if os.name == 'nt': path = path.lower() return path jlab['linkedPackages'] = dict() # Handle local extensions. for (key, source) in local.items(): if key in shadowed_exts: continue jlab['linkedPackages'][key] = source data['resolutions'][key] = 'file:' + self.info['extensions'][key]['path'] # Handle linked packages. for (key, item) in linked.items(): if key in shadowed_exts: continue path = pjoin(self.app_dir, 'staging', 'linked_packages') path = pjoin(path, item['filename']) data['dependencies'][key] = format_path(path) jlab['linkedPackages'][key] = item['source'] data['resolutions'][key] = format_path(path) data['jupyterlab']['extensionMetadata'] = dict() # Handle extensions compat_errors = self._get_extension_compat() for (key, value) in extensions.items(): # Reject incompatible extensions with a message. errors = compat_errors[key] if errors: if not silent: _log_single_compat_errors( logger, key, value['version'], errors ) continue data['dependencies'][key] = format_path(value['path']) jlab_data = value['jupyterlab'] for item in ['extension', 'mimeExtension']: ext = jlab_data.get(item, False) if not ext: continue if ext is True: ext = '' jlab[item + 's'][key] = ext # Add metadata for the extension data['jupyterlab']['extensionMetadata'][key] = jlab_data # Handle uninstalled core extensions. for item in self.info['uninstalled_core']: if item in jlab['extensions']: data['jupyterlab']['extensions'].pop(item) elif item in jlab['mimeExtensions']: data['jupyterlab']['mimeExtensions'].pop(item) # Remove from dependencies as well. if item in data['dependencies']: data['dependencies'].pop(item) return data def _check_local(self, name, source, dname): """Check if a local package has changed. `dname` is the directory name of existing package tar archives. """ # Extract the package in a temporary directory. with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Test if the file content has changed. # This relies on `_extract_package` adding the hashsum # to the filename, allowing a simple exist check to # compare the hash to the "cache" in dname. target = pjoin(dname, info['filename']) return not osp.exists(target) def _update_local(self, name, source, dname, data, dtype): """Update a local dependency. Return `True` if changed. """ # Extract the package in a temporary directory. existing = data['filename'] if not osp.exists(pjoin(dname, existing)): existing = '' with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Bail if the file content has not changed. if info['filename'] == existing: return existing shutil.move(info['path'], pjoin(dname, info['filename'])) # Remove the previous tarball and return the new file name. if existing: os.remove(pjoin(dname, existing)) data['filename'] = info['filename'] data['path'] = pjoin(data['tar_dir'], data['filename']) return info['filename'] def _get_extensions(self, core_data): """Get the extensions for the application. """ app_dir = self.app_dir extensions = dict() # Get system level packages. sys_path = pjoin(self.sys_dir, 'extensions') app_path = pjoin(self.app_dir, 'extensions') extensions = self._get_extensions_in_dir(self.sys_dir, core_data) # Look in app_dir if different. app_path = pjoin(app_dir, 'extensions') if app_path == sys_path or not osp.exists(app_path): return extensions extensions.update(self._get_extensions_in_dir(app_dir, core_data)) return extensions def _get_extensions_in_dir(self, dname, core_data): """Get the extensions in a given directory. """ extensions = dict() location = 'app' if dname == self.app_dir else 'sys' for target in glob(pjoin(dname, 'extensions', '*.tgz')): data = read_package(target) deps = data.get('dependencies', dict()) name = data['name'] jlab = data.get('jupyterlab', dict()) path = osp.abspath(target) filename = osp.basename(target) if filename.startswith(PIN_PREFIX): alias = filename[len(PIN_PREFIX):-len(".tgz")] else: alias = None url = get_package_url(data) extensions[alias or name] = dict(path=path, filename=osp.basename(path), url=url, version=data['version'], # Only save the package name if the extension name is an alias alias_package_source=name if alias else None, jupyterlab=jlab, dependencies=deps, tar_dir=osp.dirname(path), location=location) return extensions def _get_extension_compat(self): """Get the extension compatibility info. """ compat = dict() core_data = self.info['core_data'] seen = set() for (name, data) in self.info['federated_extensions'].items(): deps = data['dependencies'] compat[name] = _validate_compatibility(name, deps, core_data) seen.add(name) for (name, data) in self.info['extensions'].items(): if name in seen: continue deps = data['dependencies'] compat[name] = _validate_compatibility(name, deps, core_data) return compat def _get_local_extensions(self): """Get the locally installed extensions. """ return self._get_local_data('local_extensions') def _get_linked_packages(self): """Get the linked packages. """ info = self._get_local_data('linked_packages') dname = pjoin(self.app_dir, 'staging', 'linked_packages') for (name, source) in info.items(): info[name] = dict(source=source, filename='', tar_dir=dname) if not osp.exists(dname): return info for path in glob(pjoin(dname, '*.tgz')): path = osp.abspath(path) data = read_package(path) name = data['name'] if name not in info: self.logger.warn('Removing orphaned linked package %s' % name) os.remove(path) continue item = info[name] item['filename'] = osp.basename(path) item['path'] = path item['version'] = data['version'] item['data'] = data return info def _get_uninstalled_core_extensions(self): """Get the uninstalled core extensions. """ config = self._read_build_config() return config.get('uninstalled_core_extensions', []) def _ensure_app_dirs(self): """Ensure that the application directories exist""" dirs = ['extensions', 'settings', 'staging', 'schemas', 'themes'] for dname in dirs: path = pjoin(self.app_dir, dname) if not osp.exists(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def _list_extensions(self, info, ext_type): """List the extensions of a given type. """ self._ensure_disabled_info() logger = self.logger names = info['%s_extensions' % ext_type] if not names: return dname = info['%s_dir' % ext_type] error_accumulator = {} logger.info(' %s dir: %s' % (ext_type, dname)) for name in sorted(names): if name in info['federated_extensions']: continue data = info['extensions'][name] version = data['version'] errors = info['compat_errors'][name] extra = '' if _is_disabled(name, info['disabled']): extra += ' %s' % RED_DISABLED else: extra += ' %s' % GREEN_ENABLED if errors: extra += ' %s' % RED_X else: extra += ' %s' % GREEN_OK if data['is_local']: extra += '*' # If we have the package name in the data, this means this extension's name is the alias name alias_package_source = data['alias_package_source'] if alias_package_source: logger.info(' %s %s v%s%s' % (name, alias_package_source, version, extra)) else: logger.info(' %s v%s%s' % (name, version, extra)) if errors: error_accumulator[name] = (version, errors) # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator) # Write a blank line separator logger.info('') def _list_federated_extensions(self): self._ensure_disabled_info() info = self.info logger = self.logger error_accumulator = {} ext_dirs = dict((p, False) for p in self.labextensions_path) for value in info['federated_extensions'].values(): ext_dirs[value['ext_dir']] = True for ext_dir, has_exts in ext_dirs.items(): if not has_exts: continue logger.info(ext_dir) for name in info['federated_extensions']: data = info['federated_extensions'][name] if data['ext_dir'] != ext_dir: continue version = data['version'] errors = info['compat_errors'][name] extra = '' if _is_disabled(name, info['disabled']): extra += ' %s' % RED_DISABLED else: extra += ' %s' % GREEN_ENABLED if errors: extra += ' %s' % RED_X else: extra += ' %s' % GREEN_OK if data['is_local']: extra += '*' install = data.get('install') if install: extra += ' (%s, %s)' % ( install['packageManager'], install['packageName'] ) logger.info(' %s v%s%s' % (name, version, extra)) if errors: error_accumulator[name] = (version, errors) # Add a spacer line after logger.info('') # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator) def _read_build_config(self): """Get the build config data for the app dir. """ target = pjoin(self.app_dir, 'settings', 'build_config.json') if not osp.exists(target): return {} else: with open(target) as fid: return json.load(fid) def _write_build_config(self, config): """Write the build config to the app dir. """ self._ensure_app_dirs() target = pjoin(self.app_dir, 'settings', 'build_config.json') with open(target, 'w') as fid: json.dump(config, fid, indent=4) def _get_local_data(self, source): """Get the local data for extensions or linked packages. """ config = self._read_build_config() data = config.setdefault(source, dict()) dead = [] for (name, source) in data.items(): if not osp.exists(source): dead.append(name) for name in dead: link_type = source.replace('_', ' ') msg = '**Note: Removing dead %s "%s"' % (link_type, name) self.logger.warn(msg) del data[name] if dead: self._write_build_config(config) return data def _install_extension(self, extension, tempdir, pin=None): """Install an extension with validation and return the name and path. """ info = self._extract_package(extension, tempdir, pin=pin) data = info['data'] # Check for compatible version unless: # - A specific version was requested (@ in name, # but after first char to allow for scope marker). # - Package is locally installed. allow_fallback = '@' not in extension[1:] and not info['is_dir'] name = info['name'] # Verify that the package is an extension. messages = _validate_extension(data) if messages: msg = '"%s" is not a valid extension:\n%s' msg = msg % (extension, '\n'.join(messages)) if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: raise ValueError(msg) else: raise ValueError(msg) # Verify package compatibility. deps = data.get('dependencies', dict()) errors = _validate_compatibility(extension, deps, self.core_data) if errors: msg = _format_compatibility_errors( data['name'], data['version'], errors ) if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: # We cannot add any additional information to error message raise ValueError(msg) if version and name: self.logger.debug('Incompatible extension:\n%s', name) self.logger.debug('Found compatible version: %s', version) with TemporaryDirectory() as tempdir2: return self._install_extension( '%s@%s' % (name, version), tempdir2) # Extend message to better guide the user what to do: conflicts = '\n'.join(msg.splitlines()[2:]) msg = ''.join(( self._format_no_compatible_package_version(name), "\n\n", conflicts)) raise ValueError(msg) # Move the file to the app directory. target = pjoin(self.app_dir, 'extensions', info['filename']) if osp.exists(target): os.remove(target) shutil.move(info['path'], target) info['path'] = target return info def _extract_package(self, source, tempdir, pin=None): """Call `npm pack` for an extension. The pack command will download the package tar if `source` is a package name, or run `npm pack` locally if `source` is a directory. """ is_dir = osp.exists(source) and osp.isdir(source) if is_dir and not osp.exists(pjoin(source, 'node_modules')): self._run(['node', YARN_PATH, 'install'], cwd=source) info = dict(source=source, is_dir=is_dir) ret = self._run([which('npm'), 'pack', source], cwd=tempdir) if ret != 0: msg = '"%s" is not a valid npm package' raise ValueError(msg % source) path = glob(pjoin(tempdir, '*.tgz'))[0] info['data'] = read_package(path) if is_dir: info['sha'] = sha = _tarsum(path) target = path.replace('.tgz', '-%s.tgz' % sha) shutil.move(path, target) info['path'] = target else: info['path'] = path if pin: old_path = info['path'] new_path = pjoin(osp.dirname(old_path), '{}{}.tgz'.format(PIN_PREFIX, pin)) shutil.move(old_path, new_path) info['path'] = new_path info['filename'] = osp.basename(info['path']) info['name'] = info['data']['name'] info['version'] = info['data']['version'] return info def _latest_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info['core_data'] try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: return versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): deps = data.get('dependencies', {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version # skip deprecated versions if 'deprecated' in data: self.logger.debug( 'Disregarding compatible version of package as it is deprecated: %s@%s' % (name, version) ) continue # Verify that the version is a valid extension. with TemporaryDirectory() as tempdir: info = self._extract_package( '%s@%s' % (name, version), tempdir) if _validate_extension(info['data']): # Invalid, do not consider other versions return # Valid return version def latest_compatible_package_versions(self, names): """Get the latest compatible versions of several packages Like _latest_compatible_package_version, but optimized for retrieving the latest version for several packages in one go. """ core_data = self.info['core_data'] keys = [] for name in names: try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: continue versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): # skip deprecated versions if 'deprecated' in data: continue deps = data.get('dependencies', {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version keys.append('%s@%s' % (name, version)) break # break inner for versions = {} if not keys: return versions with TemporaryDirectory() as tempdir: ret = self._run([which('npm'), 'pack'] + keys, cwd=tempdir) if ret != 0: msg = '"%s" is not a valid npm package' raise ValueError(msg % keys) for key in keys: fname = key[0].replace('@', '') + key[1:].replace('@', '-').replace('/', '-') + '.tgz' data = read_package(osp.join(tempdir, fname)) # Verify that the version is a valid extension. if not _validate_extension(data): # Valid versions[data['name']] = data['version'] return versions def _format_no_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info['core_data'] # Whether lab version is too new: lab_newer_than_latest = False # Whether the latest version of the extension depend on a "future" version # of a singleton package (from the perspective of current lab version): latest_newer_than_lab = False try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: pass else: versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) store = tuple(sorted(versions.items(), key=sort_key, reverse=True)) latest_deps = store[0][1].get('dependencies', {}) core_deps = core_data['resolutions'] singletons = core_data['jupyterlab']['singletonPackages'] for (key, value) in latest_deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. c = _compare_ranges(core_deps[key], value, drop_prerelease1=True) lab_newer_than_latest = lab_newer_than_latest or c < 0 latest_newer_than_lab = latest_newer_than_lab or c > 0 if lab_newer_than_latest: # All singleton deps in current version of lab are newer than those # in the latest version of the extension return ("The extension \"%s\" does not yet support the current version of " "JupyterLab.\n" % name) parts = ["No version of {extension} could be found that is compatible with " "the current version of JupyterLab."] if latest_newer_than_lab: parts.extend(("However, it seems to support a new version of JupyterLab.", "Consider upgrading JupyterLab.")) return " ".join(parts).format(extension=name) def _run(self, cmd, **kwargs): """Run the command using our logger and abort callback. Returns the exit code. """ if self.kill_event.is_set(): raise ValueError('Command was killed') kwargs['logger'] = self.logger kwargs['kill_event'] = self.kill_event proc = ProgressProcess(cmd, **kwargs) return proc.wait() def _node_check(logger): """Check for the existence of nodejs with the correct version. """ node = which('node') try: output = subprocess.check_output([node, 'node-version-check.js'], cwd=HERE) logger.debug(output.decode('utf-8')) except Exception: data = CoreConfig()._data ver = data['engines']['node'] msg = 'Please install nodejs %s before continuing. nodejs may be installed using conda or directly from the nodejs website.' % ver raise ValueError(msg) def _yarn_config(logger): """Get the yarn configuration. Returns ------- {"yarn config": dict, "npm config": dict} if unsuccessfull the subdictionary are empty """ configuration = {"yarn config": {}, "npm config": {}} try: node = which('node') except ValueError: # Node not found == user with no need for building jupyterlab logger.debug("NodeJS was not found. Yarn user configuration is ignored.") return configuration try: output_binary = subprocess.check_output([node, YARN_PATH, 'config', 'list', '--json'], stderr=subprocess.PIPE, cwd=HERE) output = output_binary.decode('utf-8') lines = iter(output.splitlines()) try: for line in lines: info = json.loads(line) if info["type"] == "info": key = info["data"] inspect = json.loads(next(lines)) if inspect["type"] == "inspect": configuration[key] = inspect["data"] except StopIteration: pass logger.debug("Yarn configuration loaded.") except subprocess.CalledProcessError as e: logger.error("Fail to get yarn configuration. {!s}{!s}".format(e.stderr.decode('utf-8'), e.output.decode('utf-8'))) except Exception as e: logger.error("Fail to get yarn configuration. {!s}".format(e)) finally: return configuration def _ensure_logger(logger=None): """Ensure that we have a logger""" return logger or logging.getLogger('jupyterlab') def _normalize_path(extension): """Normalize a given extension if it is a path. """ extension = osp.expanduser(extension) if osp.exists(extension): extension = osp.abspath(extension) return extension def _rmtree(path, logger): """Remove a tree, logging errors""" def onerror(*exc_info): logger.debug('Error in shutil.rmtree', exc_info=exc_info) shutil.rmtree(path, onerror=onerror) def _unlink(path, logger): """Remove a file, logging errors""" try: os.unlink(path) except Exception: logger.debug('Error in os.unlink', exc_info=sys.exc_info()) def _rmtree_star(path, logger): """Remove all files/trees within a dir, logging errors""" for filename in os.listdir(path): file_path = osp.join(path, filename) if osp.isfile(file_path) or osp.islink(file_path): _unlink(file_path, logger) elif osp.isdir(file_path): _rmtree(file_path, logger) def _validate_extension(data): """Detect if a package is an extension using its metadata. Returns any problems it finds. """ jlab = data.get('jupyterlab', None) if jlab is None: return ['No `jupyterlab` key'] if not isinstance(jlab, dict): return ['The `jupyterlab` key must be a JSON object'] extension = jlab.get('extension', False) mime_extension = jlab.get('mimeExtension', False) themePath = jlab.get('themePath', '') schemaDir = jlab.get('schemaDir', '') messages = [] if not extension and not mime_extension: messages.append('No `extension` or `mimeExtension` key present') if extension == mime_extension: msg = '`mimeExtension` and `extension` must point to different modules' messages.append(msg) files = data['jupyterlab_extracted_files'] main = data.get('main', 'index.js') if not main.endswith('.js'): main += '.js' if extension is True: extension = main elif extension and not extension.endswith('.js'): extension += '.js' if mime_extension is True: mime_extension = main elif mime_extension and not mime_extension.endswith('.js'): mime_extension += '.js' if extension and extension not in files: messages.append('Missing extension module "%s"' % extension) if mime_extension and mime_extension not in files: messages.append('Missing mimeExtension module "%s"' % mime_extension) if themePath and not any(f.startswith(themePath) for f in files): messages.append('themePath is empty: "%s"' % themePath) if schemaDir and not any(f.startswith(schemaDir) for f in files): messages.append('schemaDir is empty: "%s"' % schemaDir) return messages def _tarsum(input_file): """ Compute the recursive sha sum of a tar file. """ tar = tarfile.open(input_file, "r") chunk_size = 100 * 1024 h = hashlib.new("sha1") for member in tar: if not member.isfile(): continue f = tar.extractfile(member) data = f.read(chunk_size) while data: h.update(data) data = f.read(chunk_size) return h.hexdigest() def _get_static_data(app_dir): """Get the data for the app static dir. """ target = pjoin(app_dir, 'static', 'package.json') if osp.exists(target): with open(target) as fid: return json.load(fid) else: return None def _validate_compatibility(extension, deps, core_data): """Validate the compatibility of an extension. """ core_deps = core_data['resolutions'] singletons = core_data['jupyterlab']['singletonPackages'] errors = [] for (key, value) in deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. overlap = _test_overlap(core_deps[key], value, drop_prerelease1=True) if overlap is False: errors.append((key, core_deps[key], value)) return errors def _test_overlap(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise whether there is an overlap """ cmp = _compare_ranges(spec1, spec2, drop_prerelease1=drop_prerelease1, drop_prerelease2=drop_prerelease2) if cmp is None: return return cmp == 0 def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise return 0 if there is an overlap, 1 if spec1 is lower/older than spec2, and -1 if spec1 is higher/newer than spec2. """ # Test for overlapping semver ranges. r1 = Range(spec1, True) r2 = Range(spec2, True) # If either range is empty, we cannot verify. if not r1.range or not r2.range: return # Set return_value to a sentinel value return_value = False # r1.set may be a list of ranges if the range involved an ||, so we need to test for overlaps between each pair. for r1set, r2set in itertools.product(r1.set, r2.set): x1 = r1set[0].semver x2 = r1set[-1].semver y1 = r2set[0].semver y2 = r2set[-1].semver if x1.prerelease and drop_prerelease1: x1 = x1.inc('patch') if y1.prerelease and drop_prerelease2: y1 = y1.inc('patch') o1 = r1set[0].operator o2 = r2set[0].operator # We do not handle (<) specifiers. if (o1.startswith('<') or o2.startswith('<')): continue # Handle single value specifiers. lx = lte if x1 == x2 else lt ly = lte if y1 == y2 else lt gx = gte if x1 == x2 else gt gy = gte if x1 == x2 else gt # Handle unbounded (>) specifiers. def noop(x, y, z): return True if x1 == x2 and o1.startswith('>'): lx = noop if y1 == y2 and o2.startswith('>'): ly = noop # Check for overlap. if (gte(x1, y1, True) and ly(x1, y2, True) or gy(x2, y1, True) and ly(x2, y2, True) or gte(y1, x1, True) and lx(y1, x2, True) or gx(y2, x1, True) and lx(y2, x2, True) ): # if we ever find an overlap, we can return immediately return 0 if gte(y1, x2, True): if return_value is False: # We can possibly return 1 return_value = 1 elif return_value == -1: # conflicting information, so we must return None return_value = None continue if gte(x1, y2, True): if return_value is False: return_value = -1 elif return_value == 1: # conflicting information, so we must return None return_value = None continue raise AssertionError('Unexpected case comparing version ranges') if return_value is False: return_value = None return return_value def _is_disabled(name, disabled=[]): """Test whether the package is disabled. """ for pattern in disabled: if name == pattern: return True if re.compile(pattern).match(name) is not None: return True return False def _format_compatibility_errors(name, version, errors): """Format a message for compatibility errors. """ msgs = [] l0 = 10 l1 = 10 for error in errors: pkg, jlab, ext = error jlab = str(Range(jlab, True)) ext = str(Range(ext, True)) msgs.append((pkg, jlab, ext)) l0 = max(l0, len(pkg) + 1) l1 = max(l1, len(jlab) + 1) msg = '\n"%s@%s" is not compatible with the current JupyterLab' msg = msg % (name, version) msg += '\nConflicting Dependencies:\n' msg += 'JupyterLab'.ljust(l0) msg += 'Extension'.ljust(l1) msg += 'Package\n' for (pkg, jlab, ext) in msgs: msg += jlab.ljust(l0) + ext.ljust(l1) + pkg + '\n' return msg def _log_multiple_compat_errors(logger, errors_map): """Log compatibility errors for multiple extensions at once""" outdated = [] others = [] for name, (version, errors) in errors_map.items(): age = _compat_error_age(errors) if age > 0: outdated.append(name) else: others.append(name) if outdated: logger.warn('\n '.join( ['\n The following extension are outdated:'] + outdated + ['\n Consider running "jupyter labextension update --all" ' 'to check for updates.\n'] )) for name in others: version, errors = errors_map[name] msg = _format_compatibility_errors(name, version, errors) logger.warn(msg + '\n') def _log_single_compat_errors(logger, name, version, errors): """Log compatability errors for a single extension""" age = _compat_error_age(errors) if age > 0: logger.warn('The extension "%s" is outdated.\n', name) else: msg = _format_compatibility_errors(name, version, errors) logger.warn(msg + '\n') def _compat_error_age(errors): """Compare all incompatabilites for an extension. Returns a number > 0 if all extensions are older than that supported by lab. Returns a number < 0 if all extensions are newer than that supported by lab. Returns 0 otherwise (i.e. a mix). """ # Do any extensions depend on too old lab packages? any_older = False # Do any extensions depend on too new lab packages? any_newer = False for _, jlab, ext in errors: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. c = _compare_ranges(ext, jlab, drop_prerelease1=True) any_newer = any_newer or c < 0 any_older = any_older or c > 0 if any_older and not any_newer: return 1 elif any_newer and not any_older: return -1 return 0 def _get_core_extensions(core_data): """Get the core extensions. """ data = core_data['jupyterlab'] return list(data['extensions']) + list(data['mimeExtensions']) def _semver_prerelease_key(prerelease): """Sort key for prereleases. Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing each dot separated identifier from left to right until a difference is found as follows: identifiers consisting of only digits are compare numerically and identifiers with letters or hyphens are compared lexically in ASCII sort order. Numeric identifiers always have lower precedence than non- numeric identifiers. A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal. """ for entry in prerelease: if isinstance(entry, int): # Assure numerics always sort before string yield ('', entry) else: # Use ASCII compare: yield (entry,) def _semver_key(version, prerelease_first=False): """A sort key-function for sorting semver version string. The default sorting order is ascending (0.x -> 1.x -> 2.x). If `prerelease_first`, pre-releases will come before ALL other semver keys (not just those with same version). I.e (1.0-pre, 2.0-pre -> 0.x -> 1.x -> 2.x). Otherwise it will sort in the standard way that it simply comes before any release with shared version string (0.x -> 1.0-pre -> 1.x -> 2.0-pre -> 2.x). """ v = make_semver(version, True) if prerelease_first: key = (0,) if v.prerelease else (1,) else: key = () key = key + (v.major, v.minor, v.patch) if not prerelease_first: # NOT having a prerelease is > having one key = key + (0,) if v.prerelease else (1,) if v.prerelease: key = key + tuple(_semver_prerelease_key( v.prerelease)) return key def _fetch_package_metadata(registry, name, logger): """Fetch the metadata for a package from the npm registry""" req = Request( urljoin(registry, quote(name, safe='@')), headers={ 'Accept': ('application/vnd.npm.install-v1+json;' ' q=1.0, application/json; q=0.8, */*') } ) try: logger.debug('Fetching URL: %s' % (req.full_url)) except AttributeError: logger.debug('Fetching URL: %s' % (req.get_full_url())) try: with contextlib.closing(urlopen(req)) as response: return json.loads(response.read().decode('utf-8')) except URLError as exc: logger.warning( 'Failed to fetch package metadata for %r: %r', name, exc) raise if __name__ == '__main__': watch_dev(HERE)
# coding: utf-8 """JupyterLab command handler""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import contextlib import errno import hashlib import itertools import json import logging import os import os.path as osp import re import shutil import stat import site import subprocess import sys import tarfile import warnings from copy import deepcopy from glob import glob from pathlib import Path from tempfile import TemporaryDirectory from threading import Event from urllib.error import URLError from urllib.request import Request, quote, urljoin, urlopen from jupyter_core.paths import jupyter_config_path from jupyter_server.extension.serverextension import GREEN_ENABLED, GREEN_OK, RED_DISABLED, RED_X from jupyterlab_server.config import (LabConfig, get_federated_extensions, get_package_url, get_page_config, get_static_page_config, write_page_config) from jupyterlab_server.process import Process, WatchHelper, list2cmdline, which from packaging.version import Version from traitlets import Bool, Dict, HasTraits, Instance, List, Unicode, default from jupyterlab.coreconfig import CoreConfig from jupyterlab.jlpmapp import HERE, YARN_PATH from jupyterlab.semver import Range, gt, gte, lt, lte, make_semver from jupyterlab._version import __version__ # The regex for expecting the webpack output. WEBPACK_EXPECT = re.compile(r'.*theme-light-extension/style/index.css') # The repo root directory REPO_ROOT = osp.abspath(osp.join(HERE, '..')) # The dev mode directory. DEV_DIR = osp.join(REPO_ROOT, 'dev_mode') # If we are pinning the package, rename it `pin@<alias>` PIN_PREFIX = 'pin@' # Default Yarn registry used in default yarn.lock YARN_DEFAULT_REGISTRY = 'https://registry.yarnpkg.com' class ProgressProcess(Process): def __init__(self, cmd, logger=None, cwd=None, kill_event=None, env=None): """Start a subprocess that can be run asynchronously. Parameters ---------- cmd: list The command to run. logger: :class:`~logger.Logger`, optional The logger instance. cwd: string, optional The cwd of the process. kill_event: :class:`~threading.Event`, optional An event used to kill the process operation. env: dict, optional The environment for the process. """ if not isinstance(cmd, (list, tuple)): raise ValueError('Command must be given as a list') if kill_event and kill_event.is_set(): raise ValueError('Process aborted') self.logger = _ensure_logger(logger) self._last_line = '' self.cmd = cmd self.logger.debug('> ' + list2cmdline(cmd)) self.proc = self._create_process( cwd=cwd, env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, universal_newlines=True, encoding='utf-8', ) self._kill_event = kill_event or Event() Process._procs.add(self) def wait(self): cache = [] proc = self.proc kill_event = self._kill_event spinner = itertools.cycle(['-', '\\', '|', '/']) while proc.poll() is None: sys.stdout.write(next(spinner)) # write the next character sys.stdout.flush() # flush stdout buffer (actual character display) sys.stdout.write('\b') if kill_event.is_set(): self.terminate() raise ValueError('Process was aborted') try: out, _ = proc.communicate(timeout=.1) cache.append(out) except subprocess.TimeoutExpired: continue self.logger.debug('\n'.join(cache)) sys.stdout.flush() return self.terminate() def pjoin(*args): """Join paths to create a real path. """ return osp.abspath(osp.join(*args)) def get_user_settings_dir(): """Get the configured JupyterLab user settings directory. """ settings_dir = os.environ.get('JUPYTERLAB_SETTINGS_DIR') settings_dir = settings_dir or pjoin( jupyter_config_path()[0], 'lab', 'user-settings' ) return osp.abspath(settings_dir) def get_workspaces_dir(): """Get the configured JupyterLab workspaces directory. """ workspaces_dir = os.environ.get('JUPYTERLAB_WORKSPACES_DIR') workspaces_dir = workspaces_dir or pjoin( jupyter_config_path()[0], 'lab', 'workspaces' ) return osp.abspath(workspaces_dir) def get_app_dir(): """Get the configured JupyterLab app directory. """ # Default to the override environment variable. if os.environ.get('JUPYTERLAB_DIR'): # We must resolve the path to get the canonical case of the path for # case-sensitive systems return str(Path(os.environ['JUPYTERLAB_DIR']).resolve()) # Use the default locations for data_files. app_dir = pjoin(sys.prefix, 'share', 'jupyter', 'lab') # Check for a user level install. # Ensure that USER_BASE is defined if hasattr(site, 'getuserbase'): site.getuserbase() userbase = getattr(site, 'USER_BASE', None) if HERE.startswith(userbase) and not app_dir.startswith(userbase): app_dir = pjoin(userbase, 'share', 'jupyter', 'lab') # Check for a system install in '/usr/local/share'. elif (sys.prefix.startswith('/usr') and not osp.exists(app_dir) and osp.exists('/usr/local/share/jupyter/lab')): app_dir = '/usr/local/share/jupyter/lab' # We must resolve the path to get the canonical case of the path for # case-sensitive systems return str(Path(app_dir).resolve()) def dedupe_yarn(path, logger=None): """ `yarn-deduplicate` with the `fewer` strategy to minimize total packages installed in a given staging directory This means a extension (or dependency) _could_ cause a downgrade of an version expected at publication time, but core should aggressively set pins above, for example, known-bad versions """ had_dupes = ProgressProcess( ['node', YARN_PATH, 'yarn-deduplicate', '-s', 'fewer', '--fail'], cwd=path, logger=logger ).wait() != 0 if had_dupes: yarn_proc = ProgressProcess(['node', YARN_PATH], cwd=path, logger=logger) yarn_proc.wait() def ensure_node_modules(cwd, logger=None): """Ensure that node_modules is up to date. Returns true if the node_modules was updated. """ logger = _ensure_logger(logger) yarn_proc = ProgressProcess(['node', YARN_PATH, 'check', '--verify-tree'], cwd=cwd, logger=logger) ret = yarn_proc.wait() # Update node_modules if needed. if ret != 0: yarn_proc = ProgressProcess(['node', YARN_PATH], cwd=cwd, logger=logger) yarn_proc.wait() dedupe_yarn(REPO_ROOT, logger) return ret != 0 def ensure_dev(logger=None): """Ensure that the dev assets are available. """ logger = _ensure_logger(logger) target = pjoin(DEV_DIR, 'static') # Determine whether to build. if ensure_node_modules(REPO_ROOT, logger) or not osp.exists(target): yarn_proc = ProgressProcess(['node', YARN_PATH, 'build'], cwd=REPO_ROOT, logger=logger) yarn_proc.wait() def ensure_core(logger=None): """Ensure that the core assets are available. """ staging = pjoin(HERE, 'staging') logger = _ensure_logger(logger) # Determine whether to build. target = pjoin(HERE, 'static', 'index.html') if not osp.exists(target): ensure_node_modules(staging, logger) yarn_proc = ProgressProcess(['node', YARN_PATH, 'build'], cwd=staging, logger=logger) yarn_proc.wait() def ensure_app(app_dir): """Ensure that an application directory is available. If it does not exist, return a list of messages to prompt the user. """ if osp.exists(pjoin(app_dir, 'static', 'index.html')): return msgs = ['JupyterLab application assets not found in "%s"' % app_dir, 'Please run `jupyter lab build` or use a different app directory'] return msgs def watch_packages(logger=None): """Run watch mode for the source packages. Parameters ---------- logger: :class:`~logger.Logger`, optional The logger instance. Returns ------- A list of `WatchHelper` objects. """ logger = _ensure_logger(logger) ensure_node_modules(REPO_ROOT, logger) ts_dir = osp.abspath(osp.join(REPO_ROOT, 'packages', 'metapackage')) # Run typescript watch and wait for the string indicating it is done. ts_regex = r'.* Found 0 errors\. Watching for file changes\.' ts_proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=ts_dir, logger=logger, startup_regex=ts_regex) return [ts_proc] def watch_dev(logger=None): """Run watch mode in a given directory. Parameters ---------- logger: :class:`~logger.Logger`, optional The logger instance. Returns ------- A list of `WatchHelper` objects. """ logger = _ensure_logger(logger) package_procs = watch_packages(logger) # Run webpack watch and wait for compilation. wp_proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=DEV_DIR, logger=logger, startup_regex=WEBPACK_EXPECT) return package_procs + [wp_proc] class AppOptions(HasTraits): """Options object for build system""" def __init__(self, logger=None, core_config=None, **kwargs): if core_config is not None: kwargs['core_config'] = core_config if logger is not None: kwargs['logger'] = logger # use the default if app_dir is empty if 'app_dir' in kwargs and not kwargs['app_dir']: kwargs.pop('app_dir') super(AppOptions, self).__init__(**kwargs) app_dir = Unicode(help='The application directory') use_sys_dir = Bool( True, help=('Whether to shadow the default app_dir if that is set to a ' 'non-default value')) logger = Instance(logging.Logger, help='The logger to use') core_config = Instance(CoreConfig, help='Configuration for core data') kill_event = Instance(Event, args=(), help='Event for aborting call') labextensions_path = List(Unicode(), help='The paths to look in for prebuilt JupyterLab extensions') registry = Unicode(help="NPM packages registry URL") splice_source = Bool(False, help="Splice source packages into app directory.") @default('logger') def _default_logger(self): return logging.getLogger('jupyterlab') # These defaults need to be federated to pick up # any changes to env vars: @default('app_dir') def _default_app_dir(self): return get_app_dir() @default('core_config') def _default_core_config(self): return CoreConfig() @default('registry') def _default_registry(self): config = _yarn_config(self.logger)["yarn config"] return config.get("registry", YARN_DEFAULT_REGISTRY) def _ensure_options(options): """Helper to use deprecated kwargs for AppOption""" if options is None: return AppOptions() elif issubclass(options.__class__, AppOptions): return options else: return AppOptions(**options) def watch(app_options=None): """Watch the application. Parameters ---------- app_options: :class:`AppOptions`, optional The application options. Returns ------- A list of processes to run asynchronously. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if app_options.splice_source: package_procs = watch_packages(app_options.logger) else: package_procs = [] return package_procs + handler.watch() def install_extension(extension, app_options=None, pin=None): """Install an extension package into JupyterLab. The extension is first validated. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.install_extension(extension, pin=pin) def uninstall_extension(name=None, app_options=None, all_=False): """Uninstall an extension by name or path. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if all_ is True: return handler.uninstall_all_extensions() return handler.uninstall_extension(name) def update_extension(name=None, all_=False, app_dir=None, app_options=None): """Update an extension by name, or all extensions. Either `name` must be given as a string, or `all_` must be `True`. If `all_` is `True`, the value of `name` is ignored. Returns `True` if a rebuild is recommended, `False` otherwise. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) if all_ is True: return handler.update_all_extensions() return handler.update_extension(name) def clean(app_options=None): """Clean the JupyterLab application directory.""" app_options = _ensure_options(app_options) handler = _AppHandler(app_options) logger = app_options.logger app_dir = app_options.app_dir logger.info('Cleaning %s...', app_dir) if app_dir == pjoin(HERE, 'dev'): raise ValueError('Cannot clean the dev app') if app_dir == pjoin(HERE, 'core'): raise ValueError('Cannot clean the core app') if getattr(app_options, 'all', False): logger.info('Removing everything in %s...', app_dir) _rmtree_star(app_dir, logger) else: possibleTargets = ['extensions', 'settings', 'staging', 'static'] targets = [t for t in possibleTargets if getattr(app_options, t)] for name in targets: target = pjoin(app_dir, name) if osp.exists(target): logger.info('Removing %s...', name) _rmtree(target, logger) else: logger.info('%s not present, skipping...', name) logger.info('Success!') if getattr(app_options, 'all', False) or getattr(app_options, 'extensions', False): logger.info('All of your extensions have been removed, and will need to be reinstalled') def build(name=None, version=None, static_url=None, kill_event=None, clean_staging=False, app_options=None, production=True, minimize=True): """Build the JupyterLab application. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.build(name=name, version=version, static_url=static_url, production=production, minimize=minimize, clean_staging=clean_staging) def get_app_info(app_options=None): """Get a dictionary of information about the app. """ handler = _AppHandler(app_options) handler._ensure_disabled_info() return handler.info def enable_extension(extension, app_options=None, level='sys_prefix'): """Enable a JupyterLab extension. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.toggle_extension(extension, False, level=level) def disable_extension(extension, app_options=None, level='sys_prefix'): """Disable a JupyterLab package. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.toggle_extension(extension, True, level=level) def check_extension(extension, installed=False, app_options=None): """Check if a JupyterLab extension is enabled or disabled. """ handler = _AppHandler(app_options) return handler.check_extension(extension, installed) def build_check(app_options=None): """Determine whether JupyterLab should be built. Returns a list of messages. """ app_options = _ensure_options(app_options) _node_check(app_options.logger) handler = _AppHandler(app_options) return handler.build_check() def list_extensions(app_options=None): """List the extensions. """ handler = _AppHandler(app_options) return handler.list_extensions() def link_package(path, app_options=None): """Link a package against the JupyterLab build. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.link_package(path) def unlink_package(package, app_options=None): """Unlink a package from JupyterLab by path or name. Returns `True` if a rebuild is recommended, `False` otherwise. """ handler = _AppHandler(app_options) return handler.unlink_package(package) def get_app_version(app_options=None): """Get the application version.""" handler = _AppHandler(app_options) return handler.info['version'] def get_latest_compatible_package_versions(names, app_options=None): """Get the latest compatible version of a list of packages. """ handler = _AppHandler(app_options) return handler.latest_compatible_package_versions(names) def read_package(target): """Read the package data in a given target tarball. """ tar = tarfile.open(target, "r") f = tar.extractfile('package/package.json') data = json.loads(f.read().decode('utf8')) data['jupyterlab_extracted_files'] = [ f.path[len('package/'):] for f in tar.getmembers() ] tar.close() return data # ---------------------------------------------------------------------- # Implementation details # ---------------------------------------------------------------------- class _AppHandler(object): def __init__(self, options): """Create a new _AppHandler object """ options = _ensure_options(options) self._options = options self.app_dir = options.app_dir self.sys_dir = get_app_dir() if options.use_sys_dir else self.app_dir self.logger = options.logger # Make a deep copy of the core data so we don't influence the original copy self.core_data = deepcopy(options.core_config._data) self.labextensions_path = options.labextensions_path self.kill_event = options.kill_event self.registry = options.registry # Do this last since it relies on other attributes self.info = self._get_app_info() def install_extension(self, extension, existing=None, pin=None): """Install an extension package into JupyterLab. The extension is first validated. Returns `True` if a rebuild is recommended, `False` otherwise. """ extension = _normalize_path(extension) extensions = self.info['extensions'] # Check for a core extensions. if extension in self.info['core_extensions']: config = self._read_build_config() uninstalled = config.get('uninstalled_core_extensions', []) if extension in uninstalled: self.logger.info('Installing core extension %s' % extension) uninstalled.remove(extension) config['uninstalled_core_extensions'] = uninstalled self._write_build_config(config) return True return False # Create the app dirs if needed. self._ensure_app_dirs() # Install the package using a temporary directory. with TemporaryDirectory() as tempdir: info = self._install_extension(extension, tempdir, pin=pin) name = info['name'] # Local directories get name mangled and stored in metadata. if info['is_dir']: config = self._read_build_config() local = config.setdefault('local_extensions', dict()) local[name] = info['source'] self._write_build_config(config) # Remove an existing extension with the same name and different path if name in extensions: other = extensions[name] if other['path'] != info['path'] and other['location'] == 'app': os.remove(other['path']) return True def build(self, name=None, version=None, static_url=None, clean_staging=False, production=True, minimize=True): """Build the application. """ if production is None: production = not (self.info['linked_packages'] or self.info['local_extensions']) if not production: minimize = False # If splicing, make sure the source packages are built if self._options.splice_source: ensure_node_modules(REPO_ROOT, logger=self.logger) self._run(['node', YARN_PATH, 'build:packages'], cwd=REPO_ROOT) info = ['production' if production else 'development'] if production: info.append('minimized' if minimize else 'not minimized') self.logger.info(f'Building jupyterlab assets ({", ".join(info)})') # Set up the build directory. app_dir = self.app_dir self._populate_staging( name=name, version=version, static_url=static_url, clean=clean_staging ) staging = pjoin(app_dir, 'staging') # Make sure packages are installed. ret = self._run(['node', YARN_PATH, 'install', '--non-interactive'], cwd=staging) if ret != 0: msg = 'npm dependencies failed to install' self.logger.debug(msg) raise RuntimeError(msg) # Build the app. dedupe_yarn(staging, self.logger) command = f'build:{"prod" if production else "dev"}{":minimize" if minimize else ""}' ret = self._run(['node', YARN_PATH, 'run', command], cwd=staging) if ret != 0: msg = 'JupyterLab failed to build' self.logger.debug(msg) raise RuntimeError(msg) def watch(self): """Start the application watcher and then run the watch in the background. """ staging = pjoin(self.app_dir, 'staging') self._populate_staging() # Make sure packages are installed. self._run(['node', YARN_PATH, 'install'], cwd=staging) dedupe_yarn(staging, self.logger) proc = WatchHelper(['node', YARN_PATH, 'run', 'watch'], cwd=pjoin(self.app_dir, 'staging'), startup_regex=WEBPACK_EXPECT, logger=self.logger) return [proc] def list_extensions(self): """Print an output of the extensions. """ self._ensure_disabled_info() logger = self.logger info = self.info logger.info('JupyterLab v%s' % info['version']) if info['federated_extensions'] or info['extensions']: info['compat_errors'] = self._get_extension_compat() if info['federated_extensions']: self._list_federated_extensions() if info['extensions']: logger.info('Other labextensions (built into JupyterLab)') self._list_extensions(info, 'app') self._list_extensions(info, 'sys') local = info['local_extensions'] if local: logger.info('\n local extensions:') for name in sorted(local): logger.info(' %s: %s' % (name, local[name])) linked_packages = info['linked_packages'] if linked_packages: logger.info('\n linked packages:') for key in sorted(linked_packages): source = linked_packages[key]['source'] logger.info(' %s: %s' % (key, source)) uninstalled_core = info['uninstalled_core'] if uninstalled_core: logger.info('\nUninstalled core extensions:') [logger.info(' %s' % item) for item in sorted(uninstalled_core)] all_exts = list(info['federated_extensions']) + list(info['extensions']) + list(info['core_extensions']) # Ignore disabled extensions that are not installed disabled = [i for i in info['disabled'] if i.partition(':')[0] in all_exts] if disabled: logger.info('\nDisabled extensions:') for item in sorted(disabled): # Show that all plugins will be disabled if the whole extension matches if item in all_exts: item += ' (all plugins)' logger.info(' %s' % item) # Here check if modules are improperly shadowed improper_shadowed = [] for ext_name in self.info['shadowed_exts']: source_version = self.info['extensions'][ext_name]['version'] prebuilt_version = self.info['federated_extensions'][ext_name]['version'] if not gte(prebuilt_version, source_version, True): improper_shadowed.append(ext_name) if improper_shadowed: logger.info('\nThe following source extensions are overshadowed by older prebuilt extensions:') [logger.info(' %s' % name) for name in sorted(improper_shadowed)] messages = self.build_check(fast=True) if messages: logger.info('\nBuild recommended, please run `jupyter lab build`:') [logger.info(' %s' % item) for item in messages] def build_check(self, fast=False): """Determine whether JupyterLab should be built. Returns a list of messages. """ app_dir = self.app_dir local = self.info['local_extensions'] linked = self.info['linked_packages'] messages = [] # Check for no application. pkg_path = pjoin(app_dir, 'static', 'package.json') if not osp.exists(pkg_path): return ['No built application'] static_data = self.info['static_data'] old_jlab = static_data['jupyterlab'] old_deps = static_data.get('dependencies', dict()) # Look for mismatched version. static_version = old_jlab.get('version', '') if not static_version.endswith('-spliced'): core_version = old_jlab['version'] if Version(static_version) != Version(core_version): msg = 'Version mismatch: %s (built), %s (current)' return [msg % (static_version, core_version)] shadowed_exts = self.info['shadowed_exts'] # Look for mismatched extensions. new_package = self._get_package_template(silent=fast) new_jlab = new_package['jupyterlab'] new_deps = new_package.get('dependencies', dict()) for ext_type in ['extensions', 'mimeExtensions']: # Extensions that were added. for ext in new_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in old_jlab[ext_type]: messages.append('%s needs to be included in build' % ext) # Extensions that were removed. for ext in old_jlab[ext_type]: if ext in shadowed_exts: continue if ext not in new_jlab[ext_type]: messages.append('%s needs to be removed from build' % ext) # Look for mismatched dependencies src_pkg_dir = pjoin(REPO_ROOT, 'packages') for (pkg, dep) in new_deps.items(): if old_deps.get(pkg, '').startswith(src_pkg_dir): continue if pkg not in old_deps: continue # Skip local and linked since we pick them up separately. if pkg in local or pkg in linked: continue if old_deps[pkg] != dep: msg = '%s changed from %s to %s' messages.append(msg % (pkg, old_deps[pkg], new_deps[pkg])) # Look for updated local extensions. for (name, source) in local.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, 'extensions') if self._check_local(name, source, dname): messages.append('%s content changed' % name) # Look for updated linked packages. for (name, item) in linked.items(): if fast or name in shadowed_exts: continue dname = pjoin(app_dir, 'staging', 'linked_packages') if self._check_local(name, item['source'], dname): messages.append('%s content changed' % name) return messages def uninstall_extension(self, name): """Uninstall an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ info = self.info logger = self.logger if name in info['federated_extensions']: if info['federated_extensions'][name].get('install', dict()).get('uninstallInstructions', None): logger.error('JupyterLab cannot uninstall this extension. %s' % info['federated_extensions'][name]['install']['uninstallInstructions']) else: logger.error('JupyterLab cannot uninstall %s since it was installed outside of JupyterLab. Use the same method used to install this extension to uninstall this extension.' % name) return False # Allow for uninstalled core extensions. if name in info['core_extensions']: config = self._read_build_config() uninstalled = config.get('uninstalled_core_extensions', []) if name not in uninstalled: logger.info('Uninstalling core extension %s' % name) uninstalled.append(name) config['uninstalled_core_extensions'] = uninstalled self._write_build_config(config) return True return False local = info['local_extensions'] for (extname, data) in info['extensions'].items(): path = data['path'] if extname == name: msg = 'Uninstalling %s from %s' % (name, osp.dirname(path)) logger.info(msg) os.remove(path) # Handle local extensions. if extname in local: config = self._read_build_config() data = config.setdefault('local_extensions', dict()) del data[extname] self._write_build_config(config) return True logger.warn('No labextension named "%s" installed' % name) return False def uninstall_all_extensions(self): """Uninstalls all extensions Returns `True` if a rebuild is recommended, `False` otherwise """ should_rebuild = False for (extname, _) in self.info['extensions'].items(): uninstalled = self.uninstall_extension(extname) should_rebuild = should_rebuild or uninstalled return should_rebuild def update_all_extensions(self): """Update all non-local extensions. Returns `True` if a rebuild is recommended, `False` otherwise. """ should_rebuild = False for (extname, _) in self.info['extensions'].items(): if extname in self.info['local_extensions']: continue updated = self._update_extension(extname) # Rebuild if at least one update happens: should_rebuild = should_rebuild or updated return should_rebuild def update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ if name not in self.info['extensions']: self.logger.warning('No labextension named "%s" installed' % name) return False return self._update_extension(name) def _update_extension(self, name): """Update an extension by name. Returns `True` if a rebuild is recommended, `False` otherwise. """ data = self.info['extensions'][name] if data["alias_package_source"]: self.logger.warn("Skipping updating pinned extension '%s'." % name) return False try: latest = self._latest_compatible_package_version(name) except URLError: return False if latest is None: self.logger.warn('No compatible version found for %s!' % (name,)) return False if latest == data['version']: self.logger.info('Extension %r already up to date' % name) return False self.logger.info('Updating %s to version %s' % (name, latest)) return self.install_extension('%s@%s' % (name, latest)) def link_package(self, path): """Link a package at the given path. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) if not osp.exists(path) or not osp.isdir(path): msg = 'Cannot install "%s" only link local directories' raise ValueError(msg % path) with TemporaryDirectory() as tempdir: info = self._extract_package(path, tempdir) messages = _validate_extension(info['data']) if not messages: return self.install_extension(path) # Warn that it is a linked package. self.logger.warning('Installing %s as a linked package because it does not have extension metadata:', path) [self.logger.warning(' %s' % m) for m in messages] # Add to metadata. config = self._read_build_config() linked = config.setdefault('linked_packages', dict()) linked[info['name']] = info['source'] self._write_build_config(config) return True def unlink_package(self, path): """Unlink a package by name or at the given path. A ValueError is raised if the path is not an unlinkable package. Returns `True` if a rebuild is recommended, `False` otherwise. """ path = _normalize_path(path) config = self._read_build_config() linked = config.setdefault('linked_packages', dict()) found = None for (name, source) in linked.items(): if name == path or source == path: found = name if found: del linked[found] else: local = config.setdefault('local_extensions', dict()) for (name, source) in local.items(): if name == path or source == path: found = name if found: del local[found] path = self.info['extensions'][found]['path'] os.remove(path) if not found: raise ValueError('No linked package for %s' % path) self._write_build_config(config) return True def toggle_extension(self, extension, value, level='sys_prefix'): """Enable or disable a lab extension. Returns `True` if a rebuild is recommended, `False` otherwise. """ lab_config = LabConfig() app_settings_dir = osp.join(self.app_dir, 'settings') page_config = get_static_page_config(app_settings_dir=app_settings_dir, logger=self.logger, level=level) disabled = page_config.get('disabledExtensions', {}) did_something = False is_disabled = disabled.get(extension, False) if value and not is_disabled: disabled[extension] = True did_something = True elif not value and is_disabled: disabled[extension] = False did_something = True if did_something: page_config['disabledExtensions'] = disabled write_page_config(page_config, level=level) return did_something def check_extension(self, extension, check_installed_only=False): """Check if a lab extension is enabled or disabled """ self._ensure_disabled_info() info = self.info if extension in info["core_extensions"]: return self._check_core_extension( extension, info, check_installed_only) if extension in info["linked_packages"]: self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True return self._check_common_extension( extension, info, check_installed_only) def _check_core_extension(self, extension, info, check_installed_only): """Check if a core extension is enabled or disabled """ if extension in info['uninstalled_core']: self.logger.info('%s:%s' % (extension, RED_X)) return False if check_installed_only: self.logger.info('%s: %s' % (extension, GREEN_OK)) return True if extension in info['disabled_core']: self.logger.info('%s: %s' % (extension, RED_DISABLED)) return False self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True def _check_common_extension(self, extension, info, check_installed_only): """Check if a common (non-core) extension is enabled or disabled """ if extension not in info['extensions']: self.logger.info('%s:%s' % (extension, RED_X)) return False errors = self._get_extension_compat()[extension] if errors: self.logger.info('%s:%s (compatibility errors)' % (extension, RED_X)) return False if check_installed_only: self.logger.info('%s: %s' % (extension, GREEN_OK)) return True if _is_disabled(extension, info['disabled']): self.logger.info('%s: %s' % (extension, RED_DISABLED)) return False self.logger.info('%s:%s' % (extension, GREEN_ENABLED)) return True def _get_app_info(self): """Get information about the app. """ info = dict() info['core_data'] = core_data = self.core_data info['extensions'] = extensions = self._get_extensions(core_data) info['local_extensions'] = self._get_local_extensions() info['linked_packages'] = self._get_linked_packages() info['app_extensions'] = app = [] info['sys_extensions'] = sys = [] for (name, data) in extensions.items(): data['is_local'] = name in info['local_extensions'] if data['location'] == 'app': app.append(name) else: sys.append(name) info['uninstalled_core'] = self._get_uninstalled_core_extensions() info['static_data'] = _get_static_data(self.app_dir) app_data = info['static_data'] or core_data info['version'] = app_data['jupyterlab']['version'] info['staticUrl'] = app_data['jupyterlab'].get('staticUrl', '') info['sys_dir'] = self.sys_dir info['app_dir'] = self.app_dir info['core_extensions'] = _get_core_extensions(self.core_data) info['federated_extensions'] = get_federated_extensions(self.labextensions_path) info['shadowed_exts'] = [ext for ext in info['extensions'] if ext in info['federated_extensions']] return info def _ensure_disabled_info(self): info = self.info if 'disabled' in info: return labextensions_path = self.labextensions_path app_settings_dir = osp.join(self.app_dir, 'settings') page_config = get_page_config(labextensions_path, app_settings_dir=app_settings_dir, logger=self.logger) info['disabled'] = page_config.get('disabledExtensions', []) disabled_core = [] for key in info['core_extensions']: if key in info['disabled']: disabled_core.append(key) info['disabled_core'] = disabled_core def _populate_staging(self, name=None, version=None, static_url=None, clean=False): """Set up the assets in the staging directory. """ app_dir = self.app_dir staging = pjoin(app_dir, 'staging') if clean and osp.exists(staging): self.logger.info("Cleaning %s", staging) _rmtree(staging, self.logger) self._ensure_app_dirs() if not version: version = self.info['core_data']['jupyterlab']['version'] splice_source = self._options.splice_source if splice_source: self.logger.debug('Splicing dev packages into app directory.') source_dir = DEV_DIR version = __version__ + '-spliced' else: source_dir = pjoin(HERE, 'staging') # Look for mismatched version. pkg_path = pjoin(staging, 'package.json') if osp.exists(pkg_path): with open(pkg_path) as fid: data = json.load(fid) if data['jupyterlab'].get('version', '') != version: _rmtree(staging, self.logger) os.makedirs(staging) for fname in ['index.js', 'bootstrap.js', 'publicpath.js', 'webpack.config.js', 'webpack.prod.config.js', 'webpack.prod.minimize.config.js']: target = pjoin(staging, fname) shutil.copy(pjoin(source_dir, fname), target) for fname in ['.yarnrc', 'yarn.js']: target = pjoin(staging, fname) shutil.copy(pjoin(HERE, 'staging', fname), target) # Ensure a clean templates directory templates = pjoin(staging, 'templates') if osp.exists(templates): _rmtree(templates, self.logger) try: shutil.copytree(pjoin(source_dir, 'templates'), templates) except shutil.Error as error: # `copytree` throws an error if copying to + from NFS even though # the copy is successful (see https://bugs.python.org/issue24564 # and https://github.com/jupyterlab/jupyterlab/issues/5233) real_error = '[Errno 22]' not in str(error) and '[Errno 5]' not in str(error) if real_error or not osp.exists(templates): raise # Ensure a clean linked packages directory. linked_dir = pjoin(staging, 'linked_packages') if osp.exists(linked_dir): _rmtree(linked_dir, self.logger) os.makedirs(linked_dir) # Template the package.json file. # Update the local extensions. extensions = self.info['extensions'] removed = False for (key, source) in self.info['local_extensions'].items(): # Handle a local extension that was removed. if key not in extensions: config = self._read_build_config() data = config.setdefault('local_extensions', dict()) del data[key] self._write_build_config(config) removed = True continue dname = pjoin(app_dir, 'extensions') self._update_local(key, source, dname, extensions[key], 'local_extensions') # Update the list of local extensions if any were removed. if removed: self.info['local_extensions'] = self._get_local_extensions() # Update the linked packages. linked = self.info['linked_packages'] for (key, item) in linked.items(): dname = pjoin(staging, 'linked_packages') self._update_local(key, item['source'], dname, item, 'linked_packages') # Then get the package template. data = self._get_package_template() jlab = data['jupyterlab'] if version: jlab['version'] = version if name: jlab['name'] = name if static_url: jlab['staticUrl'] = static_url # Handle splicing of packages if splice_source: # Splice workspace tree as linked dependencies for path in glob(pjoin(REPO_ROOT, 'packages', '*', 'package.json')): local_path = osp.dirname(osp.abspath(path)) pkg_data = json.loads(Path(path).read_text(encoding='utf-8')) name = pkg_data['name'] if name in data['dependencies']: data['dependencies'][name] = local_path jlab['linkedPackages'][name] = local_path if name in data['resolutions']: data['resolutions'][name] = local_path # splice the builder as well local_path = osp.abspath(pjoin(REPO_ROOT, 'builder')) data['devDependencies']['@jupyterlab/builder'] = local_path target = osp.join(staging, 'node_modules', '@jupyterlab', 'builder') # Remove node_modules so it gets re-populated node_modules = pjoin(staging, 'node_modules') if osp.exists(node_modules): shutil.rmtree(node_modules, ignore_errors=True) # Write the package file pkg_path = pjoin(staging, 'package.json') with open(pkg_path, 'w') as fid: json.dump(data, fid, indent=4) # copy known-good yarn.lock if missing lock_path = pjoin(staging, 'yarn.lock') lock_template = pjoin(HERE, 'staging', 'yarn.lock') if self.registry != YARN_DEFAULT_REGISTRY: # Replace on the fly the yarn repository see #3658 with open(lock_template, encoding='utf-8') as f: template = f.read() template = template.replace(YARN_DEFAULT_REGISTRY, self.registry.strip("/")) with open(lock_path, 'w', encoding='utf-8') as f: f.write(template) elif not osp.exists(lock_path): shutil.copy(lock_template, lock_path) os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD) def _get_package_template(self, silent=False): """Get the template the for staging package.json file. """ logger = self.logger # make a deep copy of the data so we don't influence the core data data = deepcopy(self.info['core_data']) local = self.info['local_extensions'] linked = self.info['linked_packages'] extensions = self.info['extensions'] shadowed_exts = self.info['shadowed_exts'] jlab = data['jupyterlab'] def format_path(path): path = osp.relpath(path, pjoin(self.app_dir, 'staging')) path = 'file:' + path.replace(os.sep, '/') if os.name == 'nt': path = path.lower() return path jlab['linkedPackages'] = dict() # Handle local extensions. for (key, source) in local.items(): if key in shadowed_exts: continue jlab['linkedPackages'][key] = source data['resolutions'][key] = 'file:' + self.info['extensions'][key]['path'] # Handle linked packages. for (key, item) in linked.items(): if key in shadowed_exts: continue path = pjoin(self.app_dir, 'staging', 'linked_packages') path = pjoin(path, item['filename']) data['dependencies'][key] = format_path(path) jlab['linkedPackages'][key] = item['source'] data['resolutions'][key] = format_path(path) data['jupyterlab']['extensionMetadata'] = dict() # Handle extensions compat_errors = self._get_extension_compat() for (key, value) in extensions.items(): # Reject incompatible extensions with a message. errors = compat_errors[key] if errors: if not silent: _log_single_compat_errors( logger, key, value['version'], errors ) continue data['dependencies'][key] = format_path(value['path']) jlab_data = value['jupyterlab'] for item in ['extension', 'mimeExtension']: ext = jlab_data.get(item, False) if not ext: continue if ext is True: ext = '' jlab[item + 's'][key] = ext # Add metadata for the extension data['jupyterlab']['extensionMetadata'][key] = jlab_data # Handle uninstalled core extensions. for item in self.info['uninstalled_core']: if item in jlab['extensions']: data['jupyterlab']['extensions'].pop(item) elif item in jlab['mimeExtensions']: data['jupyterlab']['mimeExtensions'].pop(item) # Remove from dependencies as well. if item in data['dependencies']: data['dependencies'].pop(item) return data def _check_local(self, name, source, dname): """Check if a local package has changed. `dname` is the directory name of existing package tar archives. """ # Extract the package in a temporary directory. with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Test if the file content has changed. # This relies on `_extract_package` adding the hashsum # to the filename, allowing a simple exist check to # compare the hash to the "cache" in dname. target = pjoin(dname, info['filename']) return not osp.exists(target) def _update_local(self, name, source, dname, data, dtype): """Update a local dependency. Return `True` if changed. """ # Extract the package in a temporary directory. existing = data['filename'] if not osp.exists(pjoin(dname, existing)): existing = '' with TemporaryDirectory() as tempdir: info = self._extract_package(source, tempdir) # Bail if the file content has not changed. if info['filename'] == existing: return existing shutil.move(info['path'], pjoin(dname, info['filename'])) # Remove the previous tarball and return the new file name. if existing: os.remove(pjoin(dname, existing)) data['filename'] = info['filename'] data['path'] = pjoin(data['tar_dir'], data['filename']) return info['filename'] def _get_extensions(self, core_data): """Get the extensions for the application. """ app_dir = self.app_dir extensions = dict() # Get system level packages. sys_path = pjoin(self.sys_dir, 'extensions') app_path = pjoin(self.app_dir, 'extensions') extensions = self._get_extensions_in_dir(self.sys_dir, core_data) # Look in app_dir if different. app_path = pjoin(app_dir, 'extensions') if app_path == sys_path or not osp.exists(app_path): return extensions extensions.update(self._get_extensions_in_dir(app_dir, core_data)) return extensions def _get_extensions_in_dir(self, dname, core_data): """Get the extensions in a given directory. """ extensions = dict() location = 'app' if dname == self.app_dir else 'sys' for target in glob(pjoin(dname, 'extensions', '*.tgz')): data = read_package(target) deps = data.get('dependencies', dict()) name = data['name'] jlab = data.get('jupyterlab', dict()) path = osp.abspath(target) filename = osp.basename(target) if filename.startswith(PIN_PREFIX): alias = filename[len(PIN_PREFIX):-len(".tgz")] else: alias = None url = get_package_url(data) extensions[alias or name] = dict(path=path, filename=osp.basename(path), url=url, version=data['version'], # Only save the package name if the extension name is an alias alias_package_source=name if alias else None, jupyterlab=jlab, dependencies=deps, tar_dir=osp.dirname(path), location=location) return extensions def _get_extension_compat(self): """Get the extension compatibility info. """ compat = dict() core_data = self.info['core_data'] seen = set() for (name, data) in self.info['federated_extensions'].items(): deps = data['dependencies'] compat[name] = _validate_compatibility(name, deps, core_data) seen.add(name) for (name, data) in self.info['extensions'].items(): if name in seen: continue deps = data['dependencies'] compat[name] = _validate_compatibility(name, deps, core_data) return compat def _get_local_extensions(self): """Get the locally installed extensions. """ return self._get_local_data('local_extensions') def _get_linked_packages(self): """Get the linked packages. """ info = self._get_local_data('linked_packages') dname = pjoin(self.app_dir, 'staging', 'linked_packages') for (name, source) in info.items(): info[name] = dict(source=source, filename='', tar_dir=dname) if not osp.exists(dname): return info for path in glob(pjoin(dname, '*.tgz')): path = osp.abspath(path) data = read_package(path) name = data['name'] if name not in info: self.logger.warn('Removing orphaned linked package %s' % name) os.remove(path) continue item = info[name] item['filename'] = osp.basename(path) item['path'] = path item['version'] = data['version'] item['data'] = data return info def _get_uninstalled_core_extensions(self): """Get the uninstalled core extensions. """ config = self._read_build_config() return config.get('uninstalled_core_extensions', []) def _ensure_app_dirs(self): """Ensure that the application directories exist""" dirs = ['extensions', 'settings', 'staging', 'schemas', 'themes'] for dname in dirs: path = pjoin(self.app_dir, dname) if not osp.exists(path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def _list_extensions(self, info, ext_type): """List the extensions of a given type. """ self._ensure_disabled_info() logger = self.logger names = info['%s_extensions' % ext_type] if not names: return dname = info['%s_dir' % ext_type] error_accumulator = {} logger.info(' %s dir: %s' % (ext_type, dname)) for name in sorted(names): if name in info['federated_extensions']: continue data = info['extensions'][name] version = data['version'] errors = info['compat_errors'][name] extra = '' if _is_disabled(name, info['disabled']): extra += ' %s' % RED_DISABLED else: extra += ' %s' % GREEN_ENABLED if errors: extra += ' %s' % RED_X else: extra += ' %s' % GREEN_OK if data['is_local']: extra += '*' # If we have the package name in the data, this means this extension's name is the alias name alias_package_source = data['alias_package_source'] if alias_package_source: logger.info(' %s %s v%s%s' % (name, alias_package_source, version, extra)) else: logger.info(' %s v%s%s' % (name, version, extra)) if errors: error_accumulator[name] = (version, errors) # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator) # Write a blank line separator logger.info('') def _list_federated_extensions(self): self._ensure_disabled_info() info = self.info logger = self.logger error_accumulator = {} ext_dirs = dict((p, False) for p in self.labextensions_path) for value in info['federated_extensions'].values(): ext_dirs[value['ext_dir']] = True for ext_dir, has_exts in ext_dirs.items(): if not has_exts: continue logger.info(ext_dir) for name in info['federated_extensions']: data = info['federated_extensions'][name] if data['ext_dir'] != ext_dir: continue version = data['version'] errors = info['compat_errors'][name] extra = '' if _is_disabled(name, info['disabled']): extra += ' %s' % RED_DISABLED else: extra += ' %s' % GREEN_ENABLED if errors: extra += ' %s' % RED_X else: extra += ' %s' % GREEN_OK if data['is_local']: extra += '*' install = data.get('install') if install: extra += ' (%s, %s)' % ( install['packageManager'], install['packageName'] ) logger.info(' %s v%s%s' % (name, version, extra)) if errors: error_accumulator[name] = (version, errors) # Add a spacer line after logger.info('') # Write all errors at end: _log_multiple_compat_errors(logger, error_accumulator) def _read_build_config(self): """Get the build config data for the app dir. """ target = pjoin(self.app_dir, 'settings', 'build_config.json') if not osp.exists(target): return {} else: with open(target) as fid: return json.load(fid) def _write_build_config(self, config): """Write the build config to the app dir. """ self._ensure_app_dirs() target = pjoin(self.app_dir, 'settings', 'build_config.json') with open(target, 'w') as fid: json.dump(config, fid, indent=4) def _get_local_data(self, source): """Get the local data for extensions or linked packages. """ config = self._read_build_config() data = config.setdefault(source, dict()) dead = [] for (name, source) in data.items(): if not osp.exists(source): dead.append(name) for name in dead: link_type = source.replace('_', ' ') msg = '**Note: Removing dead %s "%s"' % (link_type, name) self.logger.warn(msg) del data[name] if dead: self._write_build_config(config) return data def _install_extension(self, extension, tempdir, pin=None): """Install an extension with validation and return the name and path. """ info = self._extract_package(extension, tempdir, pin=pin) data = info['data'] # Check for compatible version unless: # - A specific version was requested (@ in name, # but after first char to allow for scope marker). # - Package is locally installed. allow_fallback = '@' not in extension[1:] and not info['is_dir'] name = info['name'] # Verify that the package is an extension. messages = _validate_extension(data) if messages: msg = '"%s" is not a valid extension:\n%s' msg = msg % (extension, '\n'.join(messages)) if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: raise ValueError(msg) else: raise ValueError(msg) # Verify package compatibility. deps = data.get('dependencies', dict()) errors = _validate_compatibility(extension, deps, self.core_data) if errors: msg = _format_compatibility_errors( data['name'], data['version'], errors ) if allow_fallback: try: version = self._latest_compatible_package_version(name) except URLError: # We cannot add any additional information to error message raise ValueError(msg) if version and name: self.logger.debug('Incompatible extension:\n%s', name) self.logger.debug('Found compatible version: %s', version) with TemporaryDirectory() as tempdir2: return self._install_extension( '%s@%s' % (name, version), tempdir2) # Extend message to better guide the user what to do: conflicts = '\n'.join(msg.splitlines()[2:]) msg = ''.join(( self._format_no_compatible_package_version(name), "\n\n", conflicts)) raise ValueError(msg) # Move the file to the app directory. target = pjoin(self.app_dir, 'extensions', info['filename']) if osp.exists(target): os.remove(target) shutil.move(info['path'], target) info['path'] = target return info def _extract_package(self, source, tempdir, pin=None): """Call `npm pack` for an extension. The pack command will download the package tar if `source` is a package name, or run `npm pack` locally if `source` is a directory. """ is_dir = osp.exists(source) and osp.isdir(source) if is_dir and not osp.exists(pjoin(source, 'node_modules')): self._run(['node', YARN_PATH, 'install'], cwd=source) info = dict(source=source, is_dir=is_dir) ret = self._run([which('npm'), 'pack', source], cwd=tempdir) if ret != 0: msg = '"%s" is not a valid npm package' raise ValueError(msg % source) path = glob(pjoin(tempdir, '*.tgz'))[0] info['data'] = read_package(path) if is_dir: info['sha'] = sha = _tarsum(path) target = path.replace('.tgz', '-%s.tgz' % sha) shutil.move(path, target) info['path'] = target else: info['path'] = path if pin: old_path = info['path'] new_path = pjoin(osp.dirname(old_path), '{}{}.tgz'.format(PIN_PREFIX, pin)) shutil.move(old_path, new_path) info['path'] = new_path info['filename'] = osp.basename(info['path']) info['name'] = info['data']['name'] info['version'] = info['data']['version'] return info def _latest_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info['core_data'] try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: return versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): deps = data.get('dependencies', {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version # skip deprecated versions if 'deprecated' in data: self.logger.debug( 'Disregarding compatible version of package as it is deprecated: %s@%s' % (name, version) ) continue # Verify that the version is a valid extension. with TemporaryDirectory() as tempdir: info = self._extract_package( '%s@%s' % (name, version), tempdir) if _validate_extension(info['data']): # Invalid, do not consider other versions return # Valid return version def latest_compatible_package_versions(self, names): """Get the latest compatible versions of several packages Like _latest_compatible_package_version, but optimized for retrieving the latest version for several packages in one go. """ core_data = self.info['core_data'] keys = [] for name in names: try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: continue versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) for version, data in sorted(versions.items(), key=sort_key, reverse=True): # skip deprecated versions if 'deprecated' in data: continue deps = data.get('dependencies', {}) errors = _validate_compatibility(name, deps, core_data) if not errors: # Found a compatible version keys.append('%s@%s' % (name, version)) break # break inner for versions = {} if not keys: return versions with TemporaryDirectory() as tempdir: ret = self._run([which('npm'), 'pack'] + keys, cwd=tempdir) if ret != 0: msg = '"%s" is not a valid npm package' raise ValueError(msg % keys) for key in keys: fname = key[0].replace('@', '') + key[1:].replace('@', '-').replace('/', '-') + '.tgz' data = read_package(osp.join(tempdir, fname)) # Verify that the version is a valid extension. if not _validate_extension(data): # Valid versions[data['name']] = data['version'] return versions def _format_no_compatible_package_version(self, name): """Get the latest compatible version of a package""" core_data = self.info['core_data'] # Whether lab version is too new: lab_newer_than_latest = False # Whether the latest version of the extension depend on a "future" version # of a singleton package (from the perspective of current lab version): latest_newer_than_lab = False try: metadata = _fetch_package_metadata(self.registry, name, self.logger) except URLError: pass else: versions = metadata.get('versions', {}) # Sort pre-release first, as we will reverse the sort: def sort_key(key_value): return _semver_key(key_value[0], prerelease_first=True) store = tuple(sorted(versions.items(), key=sort_key, reverse=True)) latest_deps = store[0][1].get('dependencies', {}) core_deps = core_data['resolutions'] singletons = core_data['jupyterlab']['singletonPackages'] for (key, value) in latest_deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. c = _compare_ranges(core_deps[key], value, drop_prerelease1=True) lab_newer_than_latest = lab_newer_than_latest or c < 0 latest_newer_than_lab = latest_newer_than_lab or c > 0 if lab_newer_than_latest: # All singleton deps in current version of lab are newer than those # in the latest version of the extension return ("The extension \"%s\" does not yet support the current version of " "JupyterLab.\n" % name) parts = ["No version of {extension} could be found that is compatible with " "the current version of JupyterLab."] if latest_newer_than_lab: parts.extend(("However, it seems to support a new version of JupyterLab.", "Consider upgrading JupyterLab.")) return " ".join(parts).format(extension=name) def _run(self, cmd, **kwargs): """Run the command using our logger and abort callback. Returns the exit code. """ if self.kill_event.is_set(): raise ValueError('Command was killed') kwargs['logger'] = self.logger kwargs['kill_event'] = self.kill_event proc = ProgressProcess(cmd, **kwargs) return proc.wait() def _node_check(logger): """Check for the existence of nodejs with the correct version. """ node = which('node') try: output = subprocess.check_output([node, 'node-version-check.js'], cwd=HERE) logger.debug(output.decode('utf-8')) except Exception: data = CoreConfig()._data ver = data['engines']['node'] msg = 'Please install nodejs %s before continuing. nodejs may be installed using conda or directly from the nodejs website.' % ver raise ValueError(msg) def _yarn_config(logger): """Get the yarn configuration. Returns ------- {"yarn config": dict, "npm config": dict} if unsuccessfull the subdictionary are empty """ configuration = {"yarn config": {}, "npm config": {}} try: node = which('node') except ValueError: # Node not found == user with no need for building jupyterlab logger.debug("NodeJS was not found. Yarn user configuration is ignored.") return configuration try: output_binary = subprocess.check_output([node, YARN_PATH, 'config', 'list', '--json'], stderr=subprocess.PIPE, cwd=HERE) output = output_binary.decode('utf-8') lines = iter(output.splitlines()) try: for line in lines: info = json.loads(line) if info["type"] == "info": key = info["data"] inspect = json.loads(next(lines)) if inspect["type"] == "inspect": configuration[key] = inspect["data"] except StopIteration: pass logger.debug("Yarn configuration loaded.") except subprocess.CalledProcessError as e: logger.error("Fail to get yarn configuration. {!s}{!s}".format(e.stderr.decode('utf-8'), e.output.decode('utf-8'))) except Exception as e: logger.error("Fail to get yarn configuration. {!s}".format(e)) finally: return configuration def _ensure_logger(logger=None): """Ensure that we have a logger""" return logger or logging.getLogger('jupyterlab') def _normalize_path(extension): """Normalize a given extension if it is a path. """ extension = osp.expanduser(extension) if osp.exists(extension): extension = osp.abspath(extension) return extension def _rmtree(path, logger): """Remove a tree, logging errors""" def onerror(*exc_info): logger.debug('Error in shutil.rmtree', exc_info=exc_info) shutil.rmtree(path, onerror=onerror) def _unlink(path, logger): """Remove a file, logging errors""" try: os.unlink(path) except Exception: logger.debug('Error in os.unlink', exc_info=sys.exc_info()) def _rmtree_star(path, logger): """Remove all files/trees within a dir, logging errors""" for filename in os.listdir(path): file_path = osp.join(path, filename) if osp.isfile(file_path) or osp.islink(file_path): _unlink(file_path, logger) elif osp.isdir(file_path): _rmtree(file_path, logger) def _validate_extension(data): """Detect if a package is an extension using its metadata. Returns any problems it finds. """ jlab = data.get('jupyterlab', None) if jlab is None: return ['No `jupyterlab` key'] if not isinstance(jlab, dict): return ['The `jupyterlab` key must be a JSON object'] extension = jlab.get('extension', False) mime_extension = jlab.get('mimeExtension', False) themePath = jlab.get('themePath', '') schemaDir = jlab.get('schemaDir', '') messages = [] if not extension and not mime_extension: messages.append('No `extension` or `mimeExtension` key present') if extension == mime_extension: msg = '`mimeExtension` and `extension` must point to different modules' messages.append(msg) files = data['jupyterlab_extracted_files'] main = data.get('main', 'index.js') if not main.endswith('.js'): main += '.js' if extension is True: extension = main elif extension and not extension.endswith('.js'): extension += '.js' if mime_extension is True: mime_extension = main elif mime_extension and not mime_extension.endswith('.js'): mime_extension += '.js' if extension and extension not in files: messages.append('Missing extension module "%s"' % extension) if mime_extension and mime_extension not in files: messages.append('Missing mimeExtension module "%s"' % mime_extension) if themePath and not any(f.startswith(themePath) for f in files): messages.append('themePath is empty: "%s"' % themePath) if schemaDir and not any(f.startswith(schemaDir) for f in files): messages.append('schemaDir is empty: "%s"' % schemaDir) return messages def _tarsum(input_file): """ Compute the recursive sha sum of a tar file. """ tar = tarfile.open(input_file, "r") chunk_size = 100 * 1024 h = hashlib.new("sha1") for member in tar: if not member.isfile(): continue f = tar.extractfile(member) data = f.read(chunk_size) while data: h.update(data) data = f.read(chunk_size) return h.hexdigest() def _get_static_data(app_dir): """Get the data for the app static dir. """ target = pjoin(app_dir, 'static', 'package.json') if osp.exists(target): with open(target) as fid: return json.load(fid) else: return None def _validate_compatibility(extension, deps, core_data): """Validate the compatibility of an extension. """ core_deps = core_data['resolutions'] singletons = core_data['jupyterlab']['singletonPackages'] errors = [] for (key, value) in deps.items(): if key in singletons: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. overlap = _test_overlap(core_deps[key], value, drop_prerelease1=True) if overlap is False: errors.append((key, core_deps[key], value)) return errors def _test_overlap(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise whether there is an overlap """ cmp = _compare_ranges(spec1, spec2, drop_prerelease1=drop_prerelease1, drop_prerelease2=drop_prerelease2) if cmp is None: return return cmp == 0 def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): """Test whether two version specs overlap. Returns `None` if we cannot determine compatibility, otherwise return 0 if there is an overlap, 1 if spec1 is lower/older than spec2, and -1 if spec1 is higher/newer than spec2. """ # Test for overlapping semver ranges. r1 = Range(spec1, True) r2 = Range(spec2, True) # If either range is empty, we cannot verify. if not r1.range or not r2.range: return # Set return_value to a sentinel value return_value = False # r1.set may be a list of ranges if the range involved an ||, so we need to test for overlaps between each pair. for r1set, r2set in itertools.product(r1.set, r2.set): x1 = r1set[0].semver x2 = r1set[-1].semver y1 = r2set[0].semver y2 = r2set[-1].semver if x1.prerelease and drop_prerelease1: x1 = x1.inc('patch') if y1.prerelease and drop_prerelease2: y1 = y1.inc('patch') o1 = r1set[0].operator o2 = r2set[0].operator # We do not handle (<) specifiers. if (o1.startswith('<') or o2.startswith('<')): continue # Handle single value specifiers. lx = lte if x1 == x2 else lt ly = lte if y1 == y2 else lt gx = gte if x1 == x2 else gt gy = gte if x1 == x2 else gt # Handle unbounded (>) specifiers. def noop(x, y, z): return True if x1 == x2 and o1.startswith('>'): lx = noop if y1 == y2 and o2.startswith('>'): ly = noop # Check for overlap. if (gte(x1, y1, True) and ly(x1, y2, True) or gy(x2, y1, True) and ly(x2, y2, True) or gte(y1, x1, True) and lx(y1, x2, True) or gx(y2, x1, True) and lx(y2, x2, True) ): # if we ever find an overlap, we can return immediately return 0 if gte(y1, x2, True): if return_value is False: # We can possibly return 1 return_value = 1 elif return_value == -1: # conflicting information, so we must return None return_value = None continue if gte(x1, y2, True): if return_value is False: return_value = -1 elif return_value == 1: # conflicting information, so we must return None return_value = None continue raise AssertionError('Unexpected case comparing version ranges') if return_value is False: return_value = None return return_value def _is_disabled(name, disabled=[]): """Test whether the package is disabled. """ for pattern in disabled: if name == pattern: return True if re.compile(pattern).match(name) is not None: return True return False def _format_compatibility_errors(name, version, errors): """Format a message for compatibility errors. """ msgs = [] l0 = 10 l1 = 10 for error in errors: pkg, jlab, ext = error jlab = str(Range(jlab, True)) ext = str(Range(ext, True)) msgs.append((pkg, jlab, ext)) l0 = max(l0, len(pkg) + 1) l1 = max(l1, len(jlab) + 1) msg = '\n"%s@%s" is not compatible with the current JupyterLab' msg = msg % (name, version) msg += '\nConflicting Dependencies:\n' msg += 'JupyterLab'.ljust(l0) msg += 'Extension'.ljust(l1) msg += 'Package\n' for (pkg, jlab, ext) in msgs: msg += jlab.ljust(l0) + ext.ljust(l1) + pkg + '\n' return msg def _log_multiple_compat_errors(logger, errors_map): """Log compatibility errors for multiple extensions at once""" outdated = [] others = [] for name, (version, errors) in errors_map.items(): age = _compat_error_age(errors) if age > 0: outdated.append(name) else: others.append(name) if outdated: logger.warn('\n '.join( ['\n The following extension are outdated:'] + outdated + ['\n Consider running "jupyter labextension update --all" ' 'to check for updates.\n'] )) for name in others: version, errors = errors_map[name] msg = _format_compatibility_errors(name, version, errors) logger.warn(msg + '\n') def _log_single_compat_errors(logger, name, version, errors): """Log compatability errors for a single extension""" age = _compat_error_age(errors) if age > 0: logger.warn('The extension "%s" is outdated.\n', name) else: msg = _format_compatibility_errors(name, version, errors) logger.warn(msg + '\n') def _compat_error_age(errors): """Compare all incompatabilites for an extension. Returns a number > 0 if all extensions are older than that supported by lab. Returns a number < 0 if all extensions are newer than that supported by lab. Returns 0 otherwise (i.e. a mix). """ # Do any extensions depend on too old lab packages? any_older = False # Do any extensions depend on too new lab packages? any_newer = False for _, jlab, ext in errors: # Drop prereleases in comparisons to allow extension authors # to not have to update their versions for each # Jupyterlab prerelease version. c = _compare_ranges(ext, jlab, drop_prerelease1=True) any_newer = any_newer or c < 0 any_older = any_older or c > 0 if any_older and not any_newer: return 1 elif any_newer and not any_older: return -1 return 0 def _get_core_extensions(core_data): """Get the core extensions. """ data = core_data['jupyterlab'] return list(data['extensions']) + list(data['mimeExtensions']) def _semver_prerelease_key(prerelease): """Sort key for prereleases. Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing each dot separated identifier from left to right until a difference is found as follows: identifiers consisting of only digits are compare numerically and identifiers with letters or hyphens are compared lexically in ASCII sort order. Numeric identifiers always have lower precedence than non- numeric identifiers. A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal. """ for entry in prerelease: if isinstance(entry, int): # Assure numerics always sort before string yield ('', entry) else: # Use ASCII compare: yield (entry,) def _semver_key(version, prerelease_first=False): """A sort key-function for sorting semver version string. The default sorting order is ascending (0.x -> 1.x -> 2.x). If `prerelease_first`, pre-releases will come before ALL other semver keys (not just those with same version). I.e (1.0-pre, 2.0-pre -> 0.x -> 1.x -> 2.x). Otherwise it will sort in the standard way that it simply comes before any release with shared version string (0.x -> 1.0-pre -> 1.x -> 2.0-pre -> 2.x). """ v = make_semver(version, True) if prerelease_first: key = (0,) if v.prerelease else (1,) else: key = () key = key + (v.major, v.minor, v.patch) if not prerelease_first: # NOT having a prerelease is > having one key = key + (0,) if v.prerelease else (1,) if v.prerelease: key = key + tuple(_semver_prerelease_key( v.prerelease)) return key def _fetch_package_metadata(registry, name, logger): """Fetch the metadata for a package from the npm registry""" req = Request( urljoin(registry, quote(name, safe='@')), headers={ 'Accept': ('application/vnd.npm.install-v1+json;' ' q=1.0, application/json; q=0.8, */*') } ) try: logger.debug('Fetching URL: %s' % (req.full_url)) except AttributeError: logger.debug('Fetching URL: %s' % (req.get_full_url())) try: with contextlib.closing(urlopen(req)) as response: return json.loads(response.read().decode('utf-8')) except URLError as exc: logger.warning( 'Failed to fetch package metadata for %r: %r', name, exc) raise if __name__ == '__main__': watch_dev(HERE)
"""This script is used to measure output dispersion score of synthetic datasets """ import os import sys import numpy as np import torch import random import tqdm import time from pathlib import Path from os.path import join from model.model import EncoderDecoder sys.path.append(join(os.path.dirname(os.path.abspath(__file__)), "../")) from dataset.toy_dataset.toydataset import ToyDataset from auxiliary.my_utils import plant_seeds from auxiliary.metric_parser import parser from model.pseudo_network import Generator from eval.metric import ChamferDistanceL2, compute_ptcloud_dismatrix_batch, cluster_eval from eval.eval_utils import get_logger, CountFrequency, dic_to_array, mean_std import auxiliary.ChamferDistancePytorch.chamfer3D.dist_chamfer_3D as dist_chamfer_3D opt = parser() ###Mkdir and logger opt.device = torch.device("cuda") res_path = join(opt.dir_name, opt.res_folder) Path(res_path).mkdir(parents=True, exist_ok=True) proc_logger = get_logger("process", res_path, "process.log") res_logger = get_logger("results", res_path, "score.log") opt.logger = proc_logger print(opt.trained_exp_dir) nviews_dic = {"train":opt.nviews_train, "test":opt.nviews_test} num_seed = max(len(opt.seed_list), 1) score_collect = {} eval_label_list = set() for seed_idx in range(num_seed): if opt.seed_list: opt.seed = opt.seed_list[seed_idx] score_collect.update({str(opt.seed):{}}) plant_seeds(opt.seed) ##Loading Data and Network if opt.split == 'pred': eval_loss = ChamferDistanceL2().to(opt.device) distChamfer = dist_chamfer_3D.chamfer_3DDist() if opt.network=='atlasnet': network = EncoderDecoder(opt) opt.logger.info(f"Reloading Network Weights from {opt.reload_model_path}...") network.load_state_dict(torch.load(opt.reload_model_path)['model_state_dict']) network.to(opt.device) if opt.split == "train": dataset = ToyDataset(data_base_dir=opt.data_base_dir, json_file=opt.train_json_file, num_points=opt.number_points, train=True, normalization=opt.normalization, logger=opt.logger) elif opt.split == "test" or opt.split == "pred": dataset = ToyDataset(data_base_dir=opt.data_base_dir, json_file=opt.test_json_file, num_points=opt.number_points, train=False, normalization=opt.normalization, logger=opt.logger) else: raise NotImplementedError() loader = torch.utils.data.DataLoader(dataset, batch_size=opt.pred_batch_size, shuffle=False, num_workers=8) if opt.rsample == 1: sample_num = len(dataset) opt.nsample = len(dataset) else: if opt.rsample != -1: opt.nsample = int(opt.rsample * len(dataset)) subset_index = random.sample(range(len(dataset)), opt.nsample) dataset = torch.utils.data.Subset(dataset, subset_index) sample_num = len(subset_index) data = None pred_loss = 0.0 with torch.set_grad_enabled(False): for batch in tqdm.tqdm(loader, desc=f"loading {opt.split} {opt.type} data"): if opt.split == 'pred': input_img = batch['image'].to(opt.device) pred_points = network(input_img, train=False) pred_points = pred_points.transpose(2, 3).contiguous() B = pred_points.shape[0] pred_points = pred_points.view(B, -1, 3) gt_points = batch['points'].to(opt.device) assert gt_points.shape[0] == B, f'gt {gt_points.shape[0]}, while pred {B}' if data is None: data = pred_points else: data = torch.cat((data, pred_points), dim=0) pred_loss += eval_loss(gt_points, pred_points).item() dist1, dist2, idx1, idx2 = distChamfer(gt_points, pred_points) opt.type = 'points' pred_loss /= len(loader) proc_logger.info(f"Pred Chamfer Loss: {pred_loss:4f}") start_time = time.time() if opt.type == 'points': data = data.to(opt.device) metric = ChamferDistanceL2().to(opt.device) distance_matrix = compute_ptcloud_dismatrix_batch(data, data, metric, opt.pred_batch_size, opt.device, proc_logger) else: raise NotImplementedError() elasp_time = (time.time() - start_time) / 60 distance_matrix = distance_matrix.cpu().numpy() score_collect[str(opt.seed)].update({"dm": distance_matrix}) score_collect[str(opt.seed)].update({"pred_chamfer": pred_loss}) n_evals = len(opt.perf_pc_list) for index in range(n_evals): c_method, e_method, n_cluster, perf_pc = opt.c_method[index], opt.e_method[index], opt.cluster_k[index], opt.perf_pc_list[index] score, part_label = cluster_eval(c_method=c_method, e_method=e_method, distance_matrix=distance_matrix, seed=opt.seed, n_cluster=n_cluster, pc=perf_pc) label_stat_verbose = "" freq = CountFrequency(part_label) for key, value in freq.items(): label_stat_verbose += "% d :% d | "%(key, value) proc_logger.info(f"{opt.type} mode: {opt.mode}, split: {opt.split} " + f"nviews: train {opt.nviews_train}, test {opt.nviews_test}, sample num:{sample_num} " + f"seed{opt.seed}, metric{opt.metric} perf{perf_pc}% " + f"samp{distance_matrix.shape[0]}, Pred Chamfer: {pred_loss:.4f}, score: {score:.4f} DM" + f"{distance_matrix.shape[0]}, compute time {elasp_time:2f} min") eval_label = f"{c_method}_{e_method}_k{n_cluster}p{perf_pc}" score_collect[str(opt.seed)].update({eval_label: {}}) eval_label_list.add(eval_label) score_collect[str(opt.seed)][eval_label].update({"score": score}) score_collect[str(opt.seed)][eval_label].update({"label": np.array(part_label)}) # cluster label score_collect[str(opt.seed)][eval_label].update({"perf_percent": perf_pc}) score_collect[str(opt.seed)][eval_label].update({"label_stats": dic_to_array(freq)}) eval_label_list = list(eval_label_list) eval_label_list.sort() ss_list = {} for eval_label in eval_label_list: ss_list.update({eval_label:[]}) pred_list = [] for seed in score_collect: pred_list.append(score_collect[seed]['pred_chamfer']) for eval_label in eval_label_list: ss_list[eval_label].append(score_collect[seed][eval_label]["score"]) for eval_label in eval_label_list: avg_score_lst = [score/sample_num for score in ss_list[eval_label]] ss_mean, ss_std = mean_std(ss_list[eval_label]) avg_ss_mean, avg_ss_std = mean_std(avg_score_lst) score_collect.update({f'{eval_label}': np.array([ss_mean, ss_std])}) score_collect.update({f'avg_{eval_label}': np.array([avg_ss_mean, avg_ss_std])}) pred_loss_mean, pred_loss_std = mean_std(pred_list) score_collect.update({'split': opt.split}) score_collect.update({'type': opt.type}) score_collect.update({'mode': opt.mode}) score_collect.update({'sample_num': sample_num}) score_collect.update({'chamfer_stats': np.array([pred_loss_mean, pred_loss_std])}) score_collect.update({'trainnv': np.array([opt.nviews_train])}) score_collect.update({'testnv': np.array([opt.nviews_test])}) for eval_label in eval_label_list: ss_mean, ss_std = score_collect[f'{eval_label}'][0], score_collect[f'{eval_label}'][1] avg_ss_mean, avg_ss_std = score_collect[f'avg_{eval_label}'][0], score_collect[f'avg_{eval_label}'][1] res_logger.info(f"{opt.network} {opt.type} mode: {opt.mode}, split: {opt.split}, " + f"nviews: train {opt.nviews_train}, test {opt.nviews_test}, sample num: {sample_num} " + f"seed_list {opt.seed_list}, metric {opt.metric} perf: {perf_pc} % {opt.metric} {opt.trained_exp_dir} {eval_label} " + f"Sum of Score: (mean: {ss_mean:.4f}|std: {ss_std:.4f}) "+ f"Average Score: (mean: {avg_ss_mean:.4f}|std: {avg_ss_std:.4f}) "+ f"Pred Chamfer: (mean:{pred_loss_mean:.4f}|std: {pred_loss_std:.4f}) " + f"DM compute time {elasp_time:.2f} min") np.savez_compressed(os.path.join(res_path, f"{opt.network}_{opt.mode}_{opt.split}_{opt.type}_{sample_num}_{opt.trained_exp_dir.split("/")[-1]}.npz"), **score_collect) res_logger.info(f"###############END OF {opt.type} {opt.network} {opt.trained_exp_dir} PIPELINE#################")
"""This script is used to measure output dispersion score of synthetic datasets """ import os import sys import numpy as np import torch import random import tqdm import time from pathlib import Path from os.path import join from model.model import EncoderDecoder sys.path.append(join(os.path.dirname(os.path.abspath(__file__)), "../")) from dataset.toy_dataset.toydataset import ToyDataset from auxiliary.my_utils import plant_seeds from auxiliary.metric_parser import parser from model.pseudo_network import Generator from eval.metric import ChamferDistanceL2, compute_ptcloud_dismatrix_batch, cluster_eval from eval.eval_utils import get_logger, CountFrequency, dic_to_array, mean_std import auxiliary.ChamferDistancePytorch.chamfer3D.dist_chamfer_3D as dist_chamfer_3D opt = parser() ###Mkdir and logger opt.device = torch.device("cuda") res_path = join(opt.dir_name, opt.res_folder) Path(res_path).mkdir(parents=True, exist_ok=True) proc_logger = get_logger("process", res_path, "process.log") res_logger = get_logger("results", res_path, "score.log") opt.logger = proc_logger print(opt.trained_exp_dir) nviews_dic = {"train":opt.nviews_train, "test":opt.nviews_test} num_seed = max(len(opt.seed_list), 1) score_collect = {} eval_label_list = set() for seed_idx in range(num_seed): if opt.seed_list: opt.seed = opt.seed_list[seed_idx] score_collect.update({str(opt.seed):{}}) plant_seeds(opt.seed) ##Loading Data and Network if opt.split == 'pred': eval_loss = ChamferDistanceL2().to(opt.device) distChamfer = dist_chamfer_3D.chamfer_3DDist() if opt.network=='atlasnet': network = EncoderDecoder(opt) opt.logger.info(f"Reloading Network Weights from {opt.reload_model_path}...") network.load_state_dict(torch.load(opt.reload_model_path)['model_state_dict']) network.to(opt.device) if opt.split == "train": dataset = ToyDataset(data_base_dir=opt.data_base_dir, json_file=opt.train_json_file, num_points=opt.number_points, train=True, normalization=opt.normalization, logger=opt.logger) elif opt.split == "test" or opt.split == "pred": dataset = ToyDataset(data_base_dir=opt.data_base_dir, json_file=opt.test_json_file, num_points=opt.number_points, train=False, normalization=opt.normalization, logger=opt.logger) else: raise NotImplementedError() loader = torch.utils.data.DataLoader(dataset, batch_size=opt.pred_batch_size, shuffle=False, num_workers=8) if opt.rsample == 1: sample_num = len(dataset) opt.nsample = len(dataset) else: if opt.rsample != -1: opt.nsample = int(opt.rsample * len(dataset)) subset_index = random.sample(range(len(dataset)), opt.nsample) dataset = torch.utils.data.Subset(dataset, subset_index) sample_num = len(subset_index) data = None pred_loss = 0.0 with torch.set_grad_enabled(False): for batch in tqdm.tqdm(loader, desc=f"loading {opt.split} {opt.type} data"): if opt.split == 'pred': input_img = batch['image'].to(opt.device) pred_points = network(input_img, train=False) pred_points = pred_points.transpose(2, 3).contiguous() B = pred_points.shape[0] pred_points = pred_points.view(B, -1, 3) gt_points = batch['points'].to(opt.device) assert gt_points.shape[0] == B, f'gt {gt_points.shape[0]}, while pred {B}' if data is None: data = pred_points else: data = torch.cat((data, pred_points), dim=0) pred_loss += eval_loss(gt_points, pred_points).item() dist1, dist2, idx1, idx2 = distChamfer(gt_points, pred_points) opt.type = 'points' pred_loss /= len(loader) proc_logger.info(f"Pred Chamfer Loss: {pred_loss:4f}") start_time = time.time() if opt.type == 'points': data = data.to(opt.device) metric = ChamferDistanceL2().to(opt.device) distance_matrix = compute_ptcloud_dismatrix_batch(data, data, metric, opt.pred_batch_size, opt.device, proc_logger) else: raise NotImplementedError() elasp_time = (time.time() - start_time) / 60 distance_matrix = distance_matrix.cpu().numpy() score_collect[str(opt.seed)].update({"dm": distance_matrix}) score_collect[str(opt.seed)].update({"pred_chamfer": pred_loss}) n_evals = len(opt.perf_pc_list) for index in range(n_evals): c_method, e_method, n_cluster, perf_pc = opt.c_method[index], opt.e_method[index], opt.cluster_k[index], opt.perf_pc_list[index] score, part_label = cluster_eval(c_method=c_method, e_method=e_method, distance_matrix=distance_matrix, seed=opt.seed, n_cluster=n_cluster, pc=perf_pc) label_stat_verbose = "" freq = CountFrequency(part_label) for key, value in freq.items(): label_stat_verbose += "% d :% d | "%(key, value) proc_logger.info(f"{opt.type} mode: {opt.mode}, split: {opt.split} " + f"nviews: train {opt.nviews_train}, test {opt.nviews_test}, sample num:{sample_num} " + f"seed{opt.seed}, metric{opt.metric} perf{perf_pc}% " + f"samp{distance_matrix.shape[0]}, Pred Chamfer: {pred_loss:.4f}, score: {score:.4f} DM" + f"{distance_matrix.shape[0]}, compute time {elasp_time:2f} min") eval_label = f"{c_method}_{e_method}_k{n_cluster}p{perf_pc}" score_collect[str(opt.seed)].update({eval_label: {}}) eval_label_list.add(eval_label) score_collect[str(opt.seed)][eval_label].update({"score": score}) score_collect[str(opt.seed)][eval_label].update({"label": np.array(part_label)}) # cluster label score_collect[str(opt.seed)][eval_label].update({"perf_percent": perf_pc}) score_collect[str(opt.seed)][eval_label].update({"label_stats": dic_to_array(freq)}) eval_label_list = list(eval_label_list) eval_label_list.sort() ss_list = {} for eval_label in eval_label_list: ss_list.update({eval_label:[]}) pred_list = [] for seed in score_collect: pred_list.append(score_collect[seed]['pred_chamfer']) for eval_label in eval_label_list: ss_list[eval_label].append(score_collect[seed][eval_label]["score"]) for eval_label in eval_label_list: avg_score_lst = [score/sample_num for score in ss_list[eval_label]] ss_mean, ss_std = mean_std(ss_list[eval_label]) avg_ss_mean, avg_ss_std = mean_std(avg_score_lst) score_collect.update({f'{eval_label}': np.array([ss_mean, ss_std])}) score_collect.update({f'avg_{eval_label}': np.array([avg_ss_mean, avg_ss_std])}) pred_loss_mean, pred_loss_std = mean_std(pred_list) score_collect.update({'split': opt.split}) score_collect.update({'type': opt.type}) score_collect.update({'mode': opt.mode}) score_collect.update({'sample_num': sample_num}) score_collect.update({'chamfer_stats': np.array([pred_loss_mean, pred_loss_std])}) score_collect.update({'trainnv': np.array([opt.nviews_train])}) score_collect.update({'testnv': np.array([opt.nviews_test])}) for eval_label in eval_label_list: ss_mean, ss_std = score_collect[f'{eval_label}'][0], score_collect[f'{eval_label}'][1] avg_ss_mean, avg_ss_std = score_collect[f'avg_{eval_label}'][0], score_collect[f'avg_{eval_label}'][1] res_logger.info(f"{opt.network} {opt.type} mode: {opt.mode}, split: {opt.split}, " + f"nviews: train {opt.nviews_train}, test {opt.nviews_test}, sample num: {sample_num} " + f"seed_list {opt.seed_list}, metric {opt.metric} perf: {perf_pc} % {opt.metric} {opt.trained_exp_dir} {eval_label} " + f"Sum of Score: (mean: {ss_mean:.4f}|std: {ss_std:.4f}) "+ f"Average Score: (mean: {avg_ss_mean:.4f}|std: {avg_ss_std:.4f}) "+ f"Pred Chamfer: (mean:{pred_loss_mean:.4f}|std: {pred_loss_std:.4f}) " + f"DM compute time {elasp_time:.2f} min") np.savez_compressed(os.path.join(res_path, f"{opt.network}_{opt.mode}_{opt.split}_{opt.type}_{sample_num}_{opt.trained_exp_dir.split('/')[-1]}.npz"), **score_collect) res_logger.info(f"###############END OF {opt.type} {opt.network} {opt.trained_exp_dir} PIPELINE#################")
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a network across multiple GPUs. """ import contextlib import logging import sys import time from argparse import Namespace from itertools import chain from typing import Any, Dict, List import torch from fairseq import checkpoint_utils, models, optim, utils from fairseq.dataclass.configs import FairseqConfig from fairseq.dataclass.utils import convert_namespace_to_omegaconf from fairseq.distributed import utils as distributed_utils from fairseq.file_io import PathManager from fairseq.logging import meters, metrics from fairseq.nan_detector import NanDetector from fairseq.optim import lr_scheduler from omegaconf import OmegaConf logger = logging.getLogger(__name__) class Trainer(object): """Main class for data parallel training. This class supports synchronous distributed data parallel training, where multiple workers each have a full model replica and gradients are accumulated across workers before each update. We use :class:`~torch.nn.parallel.DistributedDataParallel` to handle communication of the gradients across workers. """ def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None): if isinstance(cfg, Namespace): logger.warning( "argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf" ) cfg = convert_namespace_to_omegaconf(cfg) self.cfg = cfg self.task = task # catalog shared parameters shared_params = _catalog_shared_params(model) self.tpu = cfg.common.tpu self.cuda = torch.cuda.is_available() and not cfg.common.cpu and not self.tpu if self.cuda: self.device = torch.device("cuda") elif self.tpu: self.device = utils.get_tpu_device() else: self.device = torch.device("cpu") if self.cfg.distributed_training.ddp_backend == "fully_sharded": if self.cfg.common.bf16: raise ValueError( "FullyShardedDataParallel is not compatible with --bf16 or " "--memory-efficient-bf16" ) if self.cfg.distributed_training.zero_sharding != "none": raise ValueError( "FullyShardedDataParallel is not compatible with --zero-sharding " "option (it's already built in)" ) else: if self.cfg.distributed_training.cpu_offload: raise ValueError("--cpu-offload requires --ddp-backend=fully_sharded") # copy model and criterion to current device/dtype self._criterion = criterion self._model = model if cfg.distributed_training.ddp_backend != "fully_sharded": if cfg.common.fp16: self._criterion = self._criterion.half() self._model = self._model.half() elif cfg.common.bf16: self._criterion = self._criterion.to(dtype=torch.bfloat16) self._model = self._model.to(dtype=torch.bfloat16) if ( not cfg.distributed_training.pipeline_model_parallel # the DistributedFairseqModel wrapper will handle moving to device, # so only handle cases which don't use the wrapper and not self.use_distributed_wrapper ): self._criterion = self._criterion.to(device=self.device) self._model = self._model.to(device=self.device) self.pipeline_model_parallel = cfg.distributed_training.pipeline_model_parallel self.last_device = None if self.cuda and self.pipeline_model_parallel: self.last_device = torch.device( cfg.distributed_training.pipeline_devices[-1] ) # check that shared parameters are preserved after device transfer for shared_param in shared_params: ref = _get_module_by_path(self._model, shared_param[0]) for path in shared_param[1:]: logger.info( "detected shared parameter: {} <- {}".format(shared_param[0], path) ) _set_module_by_path(self._model, path, ref) self._dummy_batch = None # indicates we don't have a dummy batch at first self._lr_scheduler = None self._num_updates = 0 self._num_xla_compiles = 0 # for TPUs self._optim_history = None self._optimizer = None self._warn_once = set() self._wrapped_criterion = None self._wrapped_model = None # TODO(myleott): support tpu if self.cuda and self.data_parallel_world_size > 1: self._grad_norm_buf = torch.cuda.DoubleTensor(self.data_parallel_world_size) else: self._grad_norm_buf = None self.quantizer = quantizer if self.quantizer is not None: self.quantizer.set_trainer(self) # get detailed cuda environment if self.cuda: self.cuda_env = utils.CudaEnvironment() if self.data_parallel_world_size > 1: self.cuda_env_arr = distributed_utils.all_gather_list( self.cuda_env, group=distributed_utils.get_global_group() ) else: self.cuda_env_arr = [self.cuda_env] if self.data_parallel_rank == 0: utils.CudaEnvironment.pretty_print_cuda_env_list(self.cuda_env_arr) else: self.cuda_env = None self.cuda_env_arr = None metrics.log_start_time("wall", priority=790, round=0) self._start_time = time.time() self._previous_training_time = 0 self._cumulative_training_time = None def reinitialize(self): """Reinitialize the Trainer, typically after model params change.""" self._lr_scheduler = None self._optimizer = None self._wrapped_criterion = None self._wrapped_model = None @property def data_parallel_world_size(self): if self.cfg.distributed_training.distributed_world_size == 1: return 1 return distributed_utils.get_data_parallel_world_size() @property def data_parallel_process_group(self): return distributed_utils.get_data_parallel_group() @property def data_parallel_rank(self): if self.cfg.distributed_training.distributed_world_size == 1: return 0 return distributed_utils.get_data_parallel_rank() @property def is_data_parallel_master(self): # NOTE: this returns true for all model parallel replicas with data # parallel rank 0 return self.data_parallel_rank == 0 @property def use_distributed_wrapper(self) -> bool: return ( self.data_parallel_world_size > 1 and not self.cfg.optimization.use_bmuf ) or ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and self.cfg.distributed_training.cpu_offload ) @property def should_save_checkpoint_on_current_rank(self) -> bool: """Indicates whether to save checkpoints on the current DDP rank.""" if self.cfg.distributed_training.ddp_backend == "fully_sharded": return True else: return self.is_data_parallel_master @property def checkpoint_suffix(self) -> str: """Suffix to add to the checkpoint file name.""" if self.cfg.distributed_training.ddp_backend == "fully_sharded": return self.cfg.checkpoint.checkpoint_suffix + "-shard{0}".format(self.data_parallel_rank) else: return self.cfg.checkpoint.checkpoint_suffix or "" @property def criterion(self): if self._wrapped_criterion is None: if ( utils.has_parameters(self._criterion) and self.use_distributed_wrapper ): self._wrapped_criterion = models.DistributedFairseqModel( self.cfg.distributed_training, self._criterion, process_group=self.data_parallel_process_group, device=self.device, ) else: self._wrapped_criterion = self._criterion return self._wrapped_criterion @property def model(self): if self._wrapped_model is None: if self.use_distributed_wrapper: self._wrapped_model = models.DistributedFairseqModel( self.cfg.distributed_training, self._model, process_group=self.data_parallel_process_group, device=self.device, ) else: self._wrapped_model = self._model return self._wrapped_model @property def optimizer(self): if self._optimizer is None: self._build_optimizer() return self._optimizer @property def lr_scheduler(self): if self._lr_scheduler is None: self._build_optimizer() # this will initialize self._lr_scheduler return self._lr_scheduler def _build_optimizer(self): params = list( filter( lambda p: p.requires_grad, chain(self.model.parameters(), self.criterion.parameters()), ) ) if ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and self.cfg.common.fp16 ): # FullyShardedDataParallel always uses MemoryEfficientFP16 wrapper, # mostly for the grad scaling. But if we don't have the # --memory-efficient-fp16 flag set, then we're effectively doing # regular --fp16 and can allow the use of optimizers that would # otherwise be unsupported by MemoryEfficientFP16Optimizer. allow_unsupported = not self.cfg.common.memory_efficient_fp16 self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer( self.cfg, params, allow_unsupported=allow_unsupported ) elif self.cfg.common.fp16 or self.cfg.common.bf16: if self.cuda and torch.cuda.get_device_capability(0)[0] < 7: logger.info( "NOTE: your device does NOT support faster training with --fp16, " "please switch to FP32 which is likely to be faster" ) if ( self.cfg.common.memory_efficient_fp16 or self.cfg.common.memory_efficient_bf16 ): self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer( self.cfg, params ) else: self._optimizer = optim.FP16Optimizer.build_optimizer(self.cfg, params) else: if self.cuda and torch.cuda.get_device_capability(0)[0] >= 7: logger.info("NOTE: your device may support faster training with --fp16") self._optimizer = optim.build_optimizer(self.cfg.optimizer, params) if self.cfg.distributed_training.ddp_backend == "fully_sharded": assert not self.cfg.optimization.use_bmuf, \ "--ddp-backend=fully_sharded is not compatible with BMUF" assert self._optimizer.supports_flat_params, ( "--ddp-backend=fully_sharded is only compatible with pointwise " "optimizers (e.g., Adam, AdamW, Adadelta, Adamax, SGD, etc.). " "However, the sharding will result in slightly different results when " "using non-pointwise optimizers (e.g., Adagrad, Adafactor, LAMB)" ) if self.cfg.optimization.use_bmuf: self._optimizer = optim.FairseqBMUF( self.cfg.bmuf, self._optimizer, ) if self.cfg.distributed_training.zero_sharding == "os": if ( self.cfg.common.fp16 and not self.cfg.common.memory_efficient_fp16 and not self.cfg.common.memory_efficient_bf16 ) and not self.cfg.common.fp16_no_flatten_grads: raise ValueError( "ZeRO is incomptabile with fp16 and flattened grads. " "Please use --fp16-no-flatten-grads" ) else: optim.shard_(self._optimizer, self.data_parallel_process_group) # We should initialize the learning rate scheduler immediately after # building the optimizer, so that the initial learning rate is set. self._lr_scheduler = lr_scheduler.build_lr_scheduler( self.cfg.lr_scheduler, self.optimizer, ) self._lr_scheduler.step_update(0) def consolidate_optimizer(self): """For OSS, we need to consolidate the state dict.""" if hasattr(self.optimizer.optimizer, "consolidate_state_dict"): self.optimizer.optimizer.consolidate_state_dict() def state_dict(self): state_dict = { "args": None, # legacy "cfg": ( OmegaConf.to_container(self.cfg) if OmegaConf.is_config(self.cfg) else self.cfg ), "model": self.model.state_dict(), "criterion": ( self.criterion.state_dict() if utils.has_parameters(self.criterion) else None ), "optimizer_history": (self._optim_history or []) + [ { "criterion_name": self.get_criterion().__class__.__name__, "optimizer_name": self.optimizer.__class__.__name__, "lr_scheduler_state": self.lr_scheduler.state_dict(), "num_updates": self.get_num_updates(), } ], "task_state": self.task.state_dict() if self.task is not None else {}, "extra_state": { "metrics": metrics.state_dict(), "previous_training_time": self.cumulative_training_time(), } } if not self.cfg.checkpoint.no_save_optimizer_state: state_dict["last_optimizer_state"] = self.optimizer.state_dict() return state_dict def save_checkpoint(self, filename, extra_state): """Save all training state in a checkpoint file.""" logger.info(f"Saving checkpoint to {filename}") # call state_dict on all ranks in case it needs internal communication state_dict = utils.move_to_cpu(self.state_dict()) state_dict["extra_state"].update(extra_state) if self.should_save_checkpoint_on_current_rank: checkpoint_utils.torch_persistent_save( state_dict, filename, async_write=self.cfg.checkpoint.write_checkpoints_asynchronously, ) logger.info(f"Finished saving checkpoint to {filename}") def load_checkpoint( self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None, reset_meters=False, ): """ Load all training state from a checkpoint file. rank = 0 will load the checkpoint, and then broadcast it to all other ranks. """ extra_state, self._optim_history, last_optim_state = None, [], None logger.info(f"Preparing to load checkpoint {filename}") is_distributed = self.data_parallel_world_size > 1 bexists = PathManager.isfile(filename) if bexists: load_on_all_ranks = ( self.cfg.checkpoint.load_checkpoint_on_all_dp_ranks # TPUs don't support broadcast yet, so load checkpoints # on every worker for now or self.tpu # FSDP requires loading checkpoint shards on all ranks or self.cfg.distributed_training.ddp_backend == "fully_sharded" ) if load_on_all_ranks or self.data_parallel_rank == 0: state = checkpoint_utils.load_checkpoint_to_cpu( filename, load_on_all_ranks=load_on_all_ranks ) last_optim_state = state.get("last_optimizer_state", None) # If doing zero_sharding, do not broadcast global optimizer # state. Later we will broadcast sharded states to each rank # to avoid memory from exploding. if ( not load_on_all_ranks and self.cfg.distributed_training.zero_sharding == "os" and "last_optimizer_state" in state and is_distributed ): state["last_optimizer_state"] = "SHARDED" else: last_optim_state = None state = None if is_distributed and not load_on_all_ranks: state = distributed_utils.broadcast_object( state, src_rank=0, group=self.data_parallel_process_group, dist_device=self.device, ) if self.data_parallel_rank > 0: last_optim_state = state.get("last_optimizer_state", None) # load model parameters try: self.model.load_state_dict( state["model"], strict=True, model_cfg=self.cfg.model ) # save memory for later steps del state["model"] if utils.has_parameters(self.get_criterion()): self.get_criterion().load_state_dict( state["criterion"], strict=True ) del state["criterion"] except Exception: raise Exception( "Cannot load model parameters from checkpoint {}; " "please ensure that the architectures match.".format(filename) ) extra_state = state["extra_state"] self._optim_history = state["optimizer_history"] if last_optim_state is not None and not reset_optimizer: # rebuild optimizer after loading model, since params may have changed self._build_optimizer() # only reload optimizer and lr_scheduler if they match last_optim = self._optim_history[-1] assert ( last_optim["criterion_name"] == self.get_criterion().__class__.__name__ ), f"Criterion does not match; please reset the optimizer (--reset-optimizer). {last_optim["criterion_name"]} vs {self.get_criterion().__class__.__name__}" assert ( last_optim["optimizer_name"] == self.optimizer.__class__.__name__ ), f"Optimizer does not match; please reset the optimizer (--reset-optimizer). {last_optim["optimizer_name"]} vs {self.optimizer.__class__.__name__}" if not reset_lr_scheduler: self.lr_scheduler.load_state_dict(last_optim["lr_scheduler_state"]) if not load_on_all_ranks and is_distributed: last_optim_state = self.optimizer.broadcast_global_state_dict( last_optim_state ) self.optimizer.load_state_dict(last_optim_state, optimizer_overrides) self.set_num_updates(last_optim["num_updates"]) if extra_state is not None: itr_state = extra_state["train_iterator"] epoch = itr_state["epoch"] if "previous_training_time" in extra_state: self._previous_training_time = extra_state["previous_training_time"] self._start_time = time.time() self.lr_step(epoch) if itr_state.get("version", 1) >= 2 and itr_state["iterations_in_epoch"] == 0: # reset meters at start of epoch reset_meters = True if "metrics" in extra_state and not reset_meters: metrics.load_state_dict(extra_state["metrics"]) # reset TimeMeters, since their start times don't make sense anymore for meter in metrics.get_meters("default"): if isinstance(meter, meters.TimeMeter): meter.reset() logger.info( "Loaded checkpoint {} (epoch {} @ {} updates)".format( filename, epoch, self.get_num_updates() ) ) else: logger.info("No existing checkpoint found {}".format(filename)) return extra_state def get_train_iterator( self, epoch, combine=True, load_dataset=True, data_selector=None, shard_batch_itr=True, disable_iterator_cache=False, ): """Return an EpochBatchIterator over the training set for a given epoch.""" if load_dataset: logger.info("loading train data for epoch {}".format(epoch)) self.task.load_dataset( self.cfg.dataset.train_subset, epoch=epoch, combine=combine, data_selector=data_selector, tpu=self.tpu, ) batch_iterator = self.task.get_batch_iterator( dataset=self.task.dataset(self.cfg.dataset.train_subset), max_tokens=self.cfg.dataset.max_tokens, max_sentences=self.cfg.dataset.batch_size, max_positions=utils.resolve_max_positions( self.task.max_positions(), self.model.max_positions(), self.cfg.dataset.max_tokens, ), ignore_invalid_inputs=True, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=self.data_parallel_world_size if shard_batch_itr else 1, shard_id=self.data_parallel_rank if shard_batch_itr else 0, num_workers=self.cfg.dataset.num_workers, epoch=epoch, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache, ) self.reset_dummy_batch(batch_iterator.first_batch) return batch_iterator def get_valid_iterator( self, subset, disable_iterator_cache=False, ): """Return an EpochBatchIterator over given validation subset for a given epoch.""" batch_iterator = self.task.get_batch_iterator( dataset=self.task.dataset(subset), max_tokens=self.cfg.dataset.max_tokens_valid, max_sentences=self.cfg.dataset.batch_size_valid, max_positions=utils.resolve_max_positions( self.task.max_positions(), self.model.max_positions(), ), ignore_invalid_inputs=self.cfg.dataset.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=self.data_parallel_world_size, shard_id=self.data_parallel_rank, num_workers=self.cfg.dataset.num_workers, # always pass a fixed "epoch" to keep validation data consistent # across training epochs epoch=1, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache, ) self.reset_dummy_batch(batch_iterator.first_batch) return batch_iterator def begin_epoch(self, epoch): """Called at the beginning of each epoch.""" logger.info("begin training epoch {}".format(epoch)) self.lr_step_begin_epoch(epoch) if self.quantizer is not None: self.quantizer.begin_epoch(epoch) # task specific setup per epoch self.task.begin_epoch(epoch, self.get_model()) if self.tpu: import torch_xla.core.xla_model as xm xm.rendezvous("begin_epoch") # wait for all workers xm.mark_step() def begin_valid_epoch(self, epoch): """Called at the beginning of each validation epoch.""" # task specific setup per validation epoch self.task.begin_valid_epoch(epoch, self.get_model()) def reset_dummy_batch(self, batch): self._dummy_batch = batch @metrics.aggregate("train") def train_step(self, samples, raise_oom=False): """Do forward, backward and parameter update.""" self._set_seed() self.model.train() self.criterion.train() self.zero_grad() metrics.log_start_time("train_wall", priority=800, round=0) # forward and backward pass logging_outputs, sample_size, ooms = [], 0, 0 for i, sample in enumerate(samples): # delayed update loop sample, is_dummy_batch = self._prepare_sample(sample) def maybe_no_sync(): """ Whenever *samples* contains more than one mini-batch, we want to accumulate gradients locally and only call all-reduce in the last backwards pass. """ if ( self.data_parallel_world_size > 1 and hasattr(self.model, "no_sync") and i < len(samples) - 1 ): return self.model.no_sync() else: return contextlib.ExitStack() # dummy contextmanager try: with maybe_no_sync(): # forward and backward loss, sample_size_i, logging_output = self.task.train_step( sample=sample, model=self.model, criterion=self.criterion, optimizer=self.optimizer, update_num=self.get_num_updates(), ignore_grad=is_dummy_batch, ) del loss logging_outputs.append(logging_output) sample_size += sample_size_i # emptying the CUDA cache after the first step can # reduce the chance of OOM if self.cuda and self.get_num_updates() == 0: torch.cuda.empty_cache() except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) if raise_oom: raise e logger.warning( "attempting to recover from OOM in forward/backward pass" ) ooms += 1 self.zero_grad() if self.cuda: torch.cuda.empty_cache() if self.cfg.distributed_training.distributed_world_size == 1: return None else: raise e if self.tpu and i < len(samples) - 1: # tpu-comment: every XLA operation before marking step is # appended to the IR graph, and processing too many batches # before marking step can lead to OOM errors. # To handle gradient accumulation use case, we explicitly # mark step here for every forward pass without a backward pass self._xla_markstep_and_send_to_cpu() if is_dummy_batch: if torch.is_tensor(sample_size): sample_size.zero_() else: sample_size *= 0.0 if torch.is_tensor(sample_size): sample_size = sample_size.float() else: sample_size = float(sample_size) # gather logging outputs from all replicas if self._sync_stats(): train_time = self._local_cumulative_training_time() logging_outputs, ( sample_size, ooms, total_train_time, ) = self._aggregate_logging_outputs( logging_outputs, sample_size, ooms, train_time, ignore=is_dummy_batch ) self._cumulative_training_time = ( total_train_time / self.data_parallel_world_size ) overflow = False try: with torch.autograd.profiler.record_function("reduce-grads"): # reduce gradients across workers self.optimizer.all_reduce_grads(self.model) if utils.has_parameters(self.criterion): self.optimizer.all_reduce_grads(self.criterion) with torch.autograd.profiler.record_function("multiply-grads"): # multiply gradients by (data_parallel_size / sample_size) since # DDP normalizes by the number of data parallel workers for # improved fp16 precision. # Thus we get (sum_of_gradients / sample_size) at the end. # In case of fp16, this step also undoes loss scaling. # (Debugging note: Some optimizers perform this scaling on the # fly, so inspecting model.parameters() or optimizer.params may # still show the original, unscaled gradients.) numer = ( self.data_parallel_world_size if not self.cfg.optimization.use_bmuf or self._sync_stats() else 1 ) self.optimizer.multiply_grads(numer / (sample_size or 1.0)) # Note: (sample_size or 1.0) handles the case of a zero gradient, in a # way that avoids CPU/device transfers in case sample_size is a GPU or # TPU object. The assumption is that the gradient itself is also 0. with torch.autograd.profiler.record_function("clip-grads"): # clip grads grad_norm = self.clip_grad_norm(self.cfg.optimization.clip_norm) # check that grad norms are consistent across workers # on tpu check tensor is slow if not self.tpu: if ( not self.cfg.optimization.use_bmuf and self.cfg.distributed_training.ddp_backend != "slow_mo" ): self._check_grad_norms(grad_norm) if not torch.isfinite(grad_norm).all(): # check local gradnorm single GPU case, trigger NanDetector raise FloatingPointError("gradients are Nan/Inf") with torch.autograd.profiler.record_function("optimizer"): # take an optimization step self.task.optimizer_step( self.optimizer, model=self.model, update_num=self.get_num_updates() ) except FloatingPointError: # re-run the forward and backward pass with hooks attached to print # out where it fails self.zero_grad() with NanDetector(self.get_model()): for _, sample in enumerate(samples): sample, _ = self._prepare_sample(sample) self.task.train_step( sample, self.model, self.criterion, self.optimizer, self.get_num_updates(), ignore_grad=False, ) raise except OverflowError as e: overflow = True logger.info(f"NOTE: gradient overflow detected, ignoring gradient, {str(e)}") grad_norm = torch.tensor(0.0).cuda() self.zero_grad() except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) logger.error("OOM during optimization, irrecoverable") raise e # Some distributed wrappers (e.g., SlowMo) need access to the optimizer # after the step if hasattr(self.model, "perform_additional_optimizer_actions"): if hasattr(self.optimizer, "fp32_params"): self.model.perform_additional_optimizer_actions( self.optimizer.optimizer, self.optimizer.fp32_params ) else: self.model.perform_additional_optimizer_actions( self.optimizer.optimizer ) logging_output = None if not overflow or self.cfg.distributed_training.ddp_backend == "slow_mo": self.set_num_updates(self.get_num_updates() + 1) if self.tpu: import torch_xla.core.xla_model as xm # mark step on TPUs self._xla_markstep_and_send_to_cpu() # only log stats every log_interval steps # this causes wps to be misreported when log_interval > 1 logging_output = {} if self.get_num_updates() % self.cfg.common.log_interval == 0: # log memory usage mem_info = xm.get_memory_info(self.device) gb_free = mem_info["kb_free"] / 1024 / 1024 gb_total = mem_info["kb_total"] / 1024 / 1024 metrics.log_scalar( "gb_free", gb_free, priority=1500, round=1, weight=0 ) metrics.log_scalar( "gb_total", gb_total, priority=1600, round=1, weight=0 ) logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs) logging_output = self._reduce_and_log_stats( logging_outputs, sample_size, grad_norm ) # log whenever there's an XLA compilation, since these # slow down training and may indicate opportunities for # optimization self._check_xla_compilation() else: if self.cuda and self.cuda_env is not None: # log minimum free memory over the iteration gb_used = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024 torch.cuda.reset_peak_memory_stats() gb_free = self.cuda_env.total_memory_in_GB - gb_used metrics.log_scalar( "gb_free", gb_free, priority=1500, round=1, weight=0 ) # log stats logging_output = self._reduce_and_log_stats( logging_outputs, sample_size, grad_norm ) # clear CUDA cache to reduce memory fragmentation if ( self.cuda and self.cfg.common.empty_cache_freq > 0 and ( (self.get_num_updates() + self.cfg.common.empty_cache_freq - 1) % self.cfg.common.empty_cache_freq ) == 0 ): torch.cuda.empty_cache() if self.cfg.common.fp16: metrics.log_scalar( "loss_scale", self.optimizer.scaler.loss_scale, priority=700, round=4, weight=0, ) metrics.log_stop_time("train_wall") return logging_output @metrics.aggregate("valid") def valid_step(self, sample, raise_oom=False): """Do forward pass in evaluation mode.""" if self.tpu: import torch_xla.core.xla_model as xm xm.rendezvous("valid_step") # wait for all workers with torch.no_grad(): self.model.eval() self.criterion.eval() sample, is_dummy_batch = self._prepare_sample(sample) try: _loss, sample_size, logging_output = self.task.valid_step( sample, self.model, self.criterion ) except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) if not raise_oom: logger.warning( "ran out of memory in validation step, retrying batch" ) for p in self.model.parameters(): if p.grad is not None: p.grad = None # free some memory if self.cuda: torch.cuda.empty_cache() return self.valid_step(sample, raise_oom=True) raise e logging_outputs = [logging_output] if is_dummy_batch: if torch.is_tensor(sample_size): sample_size.zero_() else: sample_size *= 0.0 # gather logging outputs from all replicas if self.data_parallel_world_size > 1: logging_outputs, (sample_size,) = self._aggregate_logging_outputs( logging_outputs, sample_size, ignore=is_dummy_batch, ) # log validation stats if self.tpu: logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs) logging_output = self._reduce_and_log_stats(logging_outputs, sample_size) return logging_output def zero_grad(self): self.optimizer.zero_grad() def lr_step_begin_epoch(self, epoch): """Adjust the learning rate at the beginning of the epoch.""" self.lr_scheduler.step_begin_epoch(epoch) # prefer updating the LR based on the number of steps return self.lr_step_update() def lr_step(self, epoch, val_loss=None): """Adjust the learning rate at the end of the epoch.""" self.lr_scheduler.step(epoch, val_loss) # prefer updating the LR based on the number of steps return self.lr_step_update() def lr_step_update(self): """Update the learning rate after each update.""" new_lr = self.lr_scheduler.step_update(self.get_num_updates()) if isinstance(new_lr, dict): for k, v in new_lr.items(): metrics.log_scalar(f"lr_{k}", v, weight=0, priority=300) new_lr = new_lr.get("default", next(iter(new_lr.values()))) else: metrics.log_scalar("lr", new_lr, weight=0, priority=300) return new_lr def get_lr(self): """Get the current learning rate.""" return self.optimizer.get_lr() def get_model(self): """Get the (non-wrapped) model instance.""" return self._model def get_criterion(self): """Get the (non-wrapped) criterion instance.""" return self._criterion def get_meter(self, name): """[deprecated] Get a specific meter by name.""" from fairseq import meters if "get_meter" not in self._warn_once: self._warn_once.add("get_meter") utils.deprecation_warning( "Trainer.get_meter is deprecated. Please use fairseq.metrics instead." ) train_meters = metrics.get_meters("train") if train_meters is None: train_meters = {} if name == "train_loss" and "loss" in train_meters: return train_meters["loss"] elif name == "train_nll_loss": # support for legacy train.py, which assumed this meter is # always initialized m = train_meters.get("nll_loss", None) return m or meters.AverageMeter() elif name == "wall": # support for legacy train.py, which assumed this meter is # always initialized m = metrics.get_meter("default", "wall") return m or meters.TimeMeter() elif name == "wps": m = metrics.get_meter("train", "wps") return m or meters.TimeMeter() elif name in {"valid_loss", "valid_nll_loss"}: # support for legacy train.py, which assumed these meters # are always initialized k = name[len("valid_") :] m = metrics.get_meter("valid", k) return m or meters.AverageMeter() elif name == "oom": return meters.AverageMeter() elif name in train_meters: return train_meters[name] return None def get_num_updates(self): """Get the number of parameters updates.""" return self._num_updates def set_num_updates(self, num_updates): """Set the number of parameters updates.""" self._num_updates = num_updates self.lr_step_update() if self.quantizer: self.quantizer.step_update(self._num_updates) metrics.log_scalar("num_updates", self._num_updates, weight=0, priority=200) def clip_grad_norm(self, clip_norm): def agg_norm_fn(total_norm): total_norm = total_norm.cuda().float() ** 2 total_norm = distributed_utils.all_reduce( total_norm, group=self.data_parallel_process_group ) return total_norm ** 0.5 should_agg_norm = ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and ( self.data_parallel_process_group is not None or torch.distributed.is_initialized() ) ) return self.optimizer.clip_grad_norm( clip_norm, aggregate_norm_fn=agg_norm_fn if should_agg_norm else None ) def cumulative_training_time(self): if self._cumulative_training_time is None: # single GPU return self._local_cumulative_training_time() else: return self._cumulative_training_time def _local_cumulative_training_time(self): """Aggregate training time in seconds.""" return time.time() - self._start_time + self._previous_training_time def _prepare_sample(self, sample, is_dummy=False): if sample == "DUMMY": raise Exception( "Trying to use an uninitialized 'dummy' batch. This usually indicates " "that the total number of batches is smaller than the number of " "participating GPUs. Try reducing the batch size or using fewer GPUs." ) if sample is None or len(sample) == 0: assert ( self._dummy_batch is not None and len(self._dummy_batch) > 0 ), "Invalid dummy batch: {}".format(self._dummy_batch) sample, _ = self._prepare_sample(self._dummy_batch, is_dummy=True) return sample, True if self.cuda: if self.pipeline_model_parallel: if "target" in sample: sample["target"] = utils.move_to_cuda( sample["target"], device=self.last_device ) else: sample = utils.move_to_cuda(sample) elif self.tpu and is_dummy: # the dummy batch may not be on the appropriate device sample = utils.move_to_cuda(sample, device=self.device) def apply_half(t): if t.dtype is torch.float32: return t.half() return t def apply_bfloat16(t): if t.dtype is torch.float32: return t.to(dtype=torch.bfloat16) return t if self.cfg.common.fp16: sample = utils.apply_to_sample(apply_half, sample) if self.cfg.common.bf16: sample = utils.apply_to_sample(apply_bfloat16, sample) if self._dummy_batch == "DUMMY": self._dummy_batch = sample return sample, False def _set_seed(self): # Set seed based on args.seed and the update number so that we get # reproducible results when resuming from checkpoints seed = self.cfg.common.seed + self.get_num_updates() utils.set_torch_seed(seed) def _sync_stats(self): # Return True if it's using multiple GPUs and DDP or multiple GPUs with # BMUF and it's a bmuf sync with warmup iterations completed before. if self.data_parallel_world_size == 1: return False elif self.cfg.optimization.use_bmuf: return ( self.get_num_updates() + 1 ) % self.cfg.bmuf.global_sync_iter == 0 and ( self.get_num_updates() + 1 ) > self.cfg.bmuf.warmup_iterations else: return True def _log_oom(self, exc): msg = "OOM: Ran out of memory with exception: {}".format(exc) logger.warning(msg) if torch.cuda.is_available() and hasattr(torch.cuda, "memory_summary"): for device_idx in range(torch.cuda.device_count()): logger.warning(torch.cuda.memory_summary(device=device_idx)) sys.stderr.flush() def _aggregate_logging_outputs( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): if self.task.__class__.logging_outputs_can_be_summed(self.get_criterion()): return self._fast_stat_sync_sum( logging_outputs, *extra_stats_to_sum, ignore=ignore ) else: return self._all_gather_list_sync( logging_outputs, *extra_stats_to_sum, ignore=ignore ) def _all_gather_list_sync( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. all_gather_list_sync is suitable when logging outputs are complex types. """ if self.tpu: raise NotImplementedError if ignore: logging_outputs = [] results = list( zip( *distributed_utils.all_gather_list( [logging_outputs] + list(extra_stats_to_sum), max_size=getattr(self.cfg.common, "all_gather_list_size", 16384), group=self.data_parallel_process_group, ) ) ) logging_outputs, extra_stats_to_sum = results[0], results[1:] logging_outputs = list(chain.from_iterable(logging_outputs)) extra_stats_to_sum = [sum(s) for s in extra_stats_to_sum] return logging_outputs, extra_stats_to_sum def _fast_stat_sync_sum( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. fast_stat_sync_sum is faster than all_gather_list_sync, but is only suitable when logging outputs are scalars and can be summed. Note that *logging_outputs* cannot contain any nested dicts/lists. """ data = {} for i, stat in enumerate(extra_stats_to_sum): data["extra_stats_" + str(i)] = stat if len(logging_outputs) > 0: log_keys = list(logging_outputs[0].keys()) for k in log_keys: if not ignore: v = sum(log[k] for log in logging_outputs if k in log) else: v = logging_outputs[0][k] v = torch.zeros_like(v) if torch.is_tensor(v) else 0 data["logging_outputs_" + k] = v else: log_keys = None data = distributed_utils.all_reduce_dict( data, device=self.device, group=self.data_parallel_process_group ) extra_stats_to_sum = [ data["extra_stats_" + str(i)] for i in range(len(extra_stats_to_sum)) ] if log_keys is not None: logging_outputs = [{k: data["logging_outputs_" + k] for k in log_keys}] else: logging_outputs = [] return logging_outputs, extra_stats_to_sum def _check_grad_norms(self, grad_norm): """Check that grad norms are consistent across workers.""" if self._grad_norm_buf is not None: self._grad_norm_buf.zero_() self._grad_norm_buf[self.data_parallel_rank] = grad_norm distributed_utils.all_reduce( self._grad_norm_buf, group=self.data_parallel_process_group ) def is_consistent(tensor): max_abs_diff = torch.max(torch.abs(tensor - tensor[0])) return ( torch.isfinite(tensor).all() and (max_abs_diff / (tensor[0] + 1e-6) < 1e-6).all() ) if not is_consistent(self._grad_norm_buf): pretty_detail = "\n".join( "rank {:3d} = {:.8f}".format(r, n) for r, n in enumerate(self._grad_norm_buf.tolist()) ) error_detail = "grad_norm across the workers:\n{}\n".format( pretty_detail ) # use FloatingPointError to trigger NanDetector raise FloatingPointError( "Fatal error: gradients are inconsistent between workers. " "Try --ddp-backend=legacy_ddp. " "Or are you mixing up different generation of GPUs in training?" + "\n" + "-" * 80 + "\n{}\n".format(error_detail) + "-" * 80 ) def _reduce_and_log_stats(self, logging_outputs, sample_size, grad_norm=None): if grad_norm is not None and ( not torch.is_tensor(grad_norm) or torch.isfinite(grad_norm) ): metrics.log_speed("ups", 1.0, priority=100, round=2) metrics.log_scalar("gnorm", grad_norm, priority=400, round=3) if self.cfg.optimization.clip_norm > 0: metrics.log_scalar( "clip", torch.where( grad_norm > self.cfg.optimization.clip_norm, grad_norm.new_tensor(100), grad_norm.new_tensor(0), ), priority=500, round=1, ) with metrics.aggregate() as agg: if logging_outputs is not None: self.task.reduce_metrics(logging_outputs, self.get_criterion()) del logging_outputs # extra warning for criterions that don't properly log a loss value if "loss" not in agg: if "loss" not in self._warn_once: self._warn_once.add("loss") logger.warning( "Criterion.reduce_metrics did not log a 'loss' value, " "which may break some functionality" ) metrics.log_scalar("loss", -1) # support legacy interface if self.tpu: logging_output = {} else: logging_output = agg.get_smoothed_values() logging_output["sample_size"] = sample_size for key_to_delete in ["ppl", "wps", "wpb", "bsz"]: if key_to_delete in logging_output: del logging_output[key_to_delete] return logging_output def _check_xla_compilation(self): import torch_xla.debug.metrics as met compile_stats = met.metric_data("CompileTime") if compile_stats is None: return num_xla_compiles = compile_stats[0] if num_xla_compiles > self._num_xla_compiles: logger.warning( "XLA compilation detected on device #{}; too many of these can lead " "to slow training, but we expect a few in the beginning".format( self.cfg.distributed_training.distributed_rank ) ) self._num_xla_compiles = num_xla_compiles def _xla_markstep_and_send_to_cpu(self, data=None): import torch_xla.core.xla_model as xm xm.mark_step() if data is not None: from fairseq.utils import xla_device_to_cpu return xla_device_to_cpu(data) def _catalog_shared_params(module, memo=None, prefix=""): if memo is None: first_call = True memo = {} else: first_call = False for name, param in module._parameters.items(): param_prefix = prefix + ("." if prefix else "") + name if param not in memo: memo[param] = [] memo[param].append(param_prefix) for name, m in module._modules.items(): if m is None: continue submodule_prefix = prefix + ("." if prefix else "") + name _catalog_shared_params(m, memo, submodule_prefix) if first_call: return [x for x in memo.values() if len(x) > 1] def _get_module_by_path(module, path): path = path.split(".") for name in path: module = getattr(module, name) return module def _set_module_by_path(module, path, value): path = path.split(".") for name in path[:-1]: module = getattr(module, name) setattr(module, path[-1], value)
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Train a network across multiple GPUs. """ import contextlib import logging import sys import time from argparse import Namespace from itertools import chain from typing import Any, Dict, List import torch from fairseq import checkpoint_utils, models, optim, utils from fairseq.dataclass.configs import FairseqConfig from fairseq.dataclass.utils import convert_namespace_to_omegaconf from fairseq.distributed import utils as distributed_utils from fairseq.file_io import PathManager from fairseq.logging import meters, metrics from fairseq.nan_detector import NanDetector from fairseq.optim import lr_scheduler from omegaconf import OmegaConf logger = logging.getLogger(__name__) class Trainer(object): """Main class for data parallel training. This class supports synchronous distributed data parallel training, where multiple workers each have a full model replica and gradients are accumulated across workers before each update. We use :class:`~torch.nn.parallel.DistributedDataParallel` to handle communication of the gradients across workers. """ def __init__(self, cfg: FairseqConfig, task, model, criterion, quantizer=None): if isinstance(cfg, Namespace): logger.warning( "argparse.Namespace configuration is deprecated! Automatically converting to OmegaConf" ) cfg = convert_namespace_to_omegaconf(cfg) self.cfg = cfg self.task = task # catalog shared parameters shared_params = _catalog_shared_params(model) self.tpu = cfg.common.tpu self.cuda = torch.cuda.is_available() and not cfg.common.cpu and not self.tpu if self.cuda: self.device = torch.device("cuda") elif self.tpu: self.device = utils.get_tpu_device() else: self.device = torch.device("cpu") if self.cfg.distributed_training.ddp_backend == "fully_sharded": if self.cfg.common.bf16: raise ValueError( "FullyShardedDataParallel is not compatible with --bf16 or " "--memory-efficient-bf16" ) if self.cfg.distributed_training.zero_sharding != "none": raise ValueError( "FullyShardedDataParallel is not compatible with --zero-sharding " "option (it's already built in)" ) else: if self.cfg.distributed_training.cpu_offload: raise ValueError("--cpu-offload requires --ddp-backend=fully_sharded") # copy model and criterion to current device/dtype self._criterion = criterion self._model = model if cfg.distributed_training.ddp_backend != "fully_sharded": if cfg.common.fp16: self._criterion = self._criterion.half() self._model = self._model.half() elif cfg.common.bf16: self._criterion = self._criterion.to(dtype=torch.bfloat16) self._model = self._model.to(dtype=torch.bfloat16) if ( not cfg.distributed_training.pipeline_model_parallel # the DistributedFairseqModel wrapper will handle moving to device, # so only handle cases which don't use the wrapper and not self.use_distributed_wrapper ): self._criterion = self._criterion.to(device=self.device) self._model = self._model.to(device=self.device) self.pipeline_model_parallel = cfg.distributed_training.pipeline_model_parallel self.last_device = None if self.cuda and self.pipeline_model_parallel: self.last_device = torch.device( cfg.distributed_training.pipeline_devices[-1] ) # check that shared parameters are preserved after device transfer for shared_param in shared_params: ref = _get_module_by_path(self._model, shared_param[0]) for path in shared_param[1:]: logger.info( "detected shared parameter: {} <- {}".format(shared_param[0], path) ) _set_module_by_path(self._model, path, ref) self._dummy_batch = None # indicates we don't have a dummy batch at first self._lr_scheduler = None self._num_updates = 0 self._num_xla_compiles = 0 # for TPUs self._optim_history = None self._optimizer = None self._warn_once = set() self._wrapped_criterion = None self._wrapped_model = None # TODO(myleott): support tpu if self.cuda and self.data_parallel_world_size > 1: self._grad_norm_buf = torch.cuda.DoubleTensor(self.data_parallel_world_size) else: self._grad_norm_buf = None self.quantizer = quantizer if self.quantizer is not None: self.quantizer.set_trainer(self) # get detailed cuda environment if self.cuda: self.cuda_env = utils.CudaEnvironment() if self.data_parallel_world_size > 1: self.cuda_env_arr = distributed_utils.all_gather_list( self.cuda_env, group=distributed_utils.get_global_group() ) else: self.cuda_env_arr = [self.cuda_env] if self.data_parallel_rank == 0: utils.CudaEnvironment.pretty_print_cuda_env_list(self.cuda_env_arr) else: self.cuda_env = None self.cuda_env_arr = None metrics.log_start_time("wall", priority=790, round=0) self._start_time = time.time() self._previous_training_time = 0 self._cumulative_training_time = None def reinitialize(self): """Reinitialize the Trainer, typically after model params change.""" self._lr_scheduler = None self._optimizer = None self._wrapped_criterion = None self._wrapped_model = None @property def data_parallel_world_size(self): if self.cfg.distributed_training.distributed_world_size == 1: return 1 return distributed_utils.get_data_parallel_world_size() @property def data_parallel_process_group(self): return distributed_utils.get_data_parallel_group() @property def data_parallel_rank(self): if self.cfg.distributed_training.distributed_world_size == 1: return 0 return distributed_utils.get_data_parallel_rank() @property def is_data_parallel_master(self): # NOTE: this returns true for all model parallel replicas with data # parallel rank 0 return self.data_parallel_rank == 0 @property def use_distributed_wrapper(self) -> bool: return ( self.data_parallel_world_size > 1 and not self.cfg.optimization.use_bmuf ) or ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and self.cfg.distributed_training.cpu_offload ) @property def should_save_checkpoint_on_current_rank(self) -> bool: """Indicates whether to save checkpoints on the current DDP rank.""" if self.cfg.distributed_training.ddp_backend == "fully_sharded": return True else: return self.is_data_parallel_master @property def checkpoint_suffix(self) -> str: """Suffix to add to the checkpoint file name.""" if self.cfg.distributed_training.ddp_backend == "fully_sharded": return self.cfg.checkpoint.checkpoint_suffix + "-shard{0}".format(self.data_parallel_rank) else: return self.cfg.checkpoint.checkpoint_suffix or "" @property def criterion(self): if self._wrapped_criterion is None: if ( utils.has_parameters(self._criterion) and self.use_distributed_wrapper ): self._wrapped_criterion = models.DistributedFairseqModel( self.cfg.distributed_training, self._criterion, process_group=self.data_parallel_process_group, device=self.device, ) else: self._wrapped_criterion = self._criterion return self._wrapped_criterion @property def model(self): if self._wrapped_model is None: if self.use_distributed_wrapper: self._wrapped_model = models.DistributedFairseqModel( self.cfg.distributed_training, self._model, process_group=self.data_parallel_process_group, device=self.device, ) else: self._wrapped_model = self._model return self._wrapped_model @property def optimizer(self): if self._optimizer is None: self._build_optimizer() return self._optimizer @property def lr_scheduler(self): if self._lr_scheduler is None: self._build_optimizer() # this will initialize self._lr_scheduler return self._lr_scheduler def _build_optimizer(self): params = list( filter( lambda p: p.requires_grad, chain(self.model.parameters(), self.criterion.parameters()), ) ) if ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and self.cfg.common.fp16 ): # FullyShardedDataParallel always uses MemoryEfficientFP16 wrapper, # mostly for the grad scaling. But if we don't have the # --memory-efficient-fp16 flag set, then we're effectively doing # regular --fp16 and can allow the use of optimizers that would # otherwise be unsupported by MemoryEfficientFP16Optimizer. allow_unsupported = not self.cfg.common.memory_efficient_fp16 self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer( self.cfg, params, allow_unsupported=allow_unsupported ) elif self.cfg.common.fp16 or self.cfg.common.bf16: if self.cuda and torch.cuda.get_device_capability(0)[0] < 7: logger.info( "NOTE: your device does NOT support faster training with --fp16, " "please switch to FP32 which is likely to be faster" ) if ( self.cfg.common.memory_efficient_fp16 or self.cfg.common.memory_efficient_bf16 ): self._optimizer = optim.MemoryEfficientFP16Optimizer.build_optimizer( self.cfg, params ) else: self._optimizer = optim.FP16Optimizer.build_optimizer(self.cfg, params) else: if self.cuda and torch.cuda.get_device_capability(0)[0] >= 7: logger.info("NOTE: your device may support faster training with --fp16") self._optimizer = optim.build_optimizer(self.cfg.optimizer, params) if self.cfg.distributed_training.ddp_backend == "fully_sharded": assert not self.cfg.optimization.use_bmuf, \ "--ddp-backend=fully_sharded is not compatible with BMUF" assert self._optimizer.supports_flat_params, ( "--ddp-backend=fully_sharded is only compatible with pointwise " "optimizers (e.g., Adam, AdamW, Adadelta, Adamax, SGD, etc.). " "However, the sharding will result in slightly different results when " "using non-pointwise optimizers (e.g., Adagrad, Adafactor, LAMB)" ) if self.cfg.optimization.use_bmuf: self._optimizer = optim.FairseqBMUF( self.cfg.bmuf, self._optimizer, ) if self.cfg.distributed_training.zero_sharding == "os": if ( self.cfg.common.fp16 and not self.cfg.common.memory_efficient_fp16 and not self.cfg.common.memory_efficient_bf16 ) and not self.cfg.common.fp16_no_flatten_grads: raise ValueError( "ZeRO is incomptabile with fp16 and flattened grads. " "Please use --fp16-no-flatten-grads" ) else: optim.shard_(self._optimizer, self.data_parallel_process_group) # We should initialize the learning rate scheduler immediately after # building the optimizer, so that the initial learning rate is set. self._lr_scheduler = lr_scheduler.build_lr_scheduler( self.cfg.lr_scheduler, self.optimizer, ) self._lr_scheduler.step_update(0) def consolidate_optimizer(self): """For OSS, we need to consolidate the state dict.""" if hasattr(self.optimizer.optimizer, "consolidate_state_dict"): self.optimizer.optimizer.consolidate_state_dict() def state_dict(self): state_dict = { "args": None, # legacy "cfg": ( OmegaConf.to_container(self.cfg) if OmegaConf.is_config(self.cfg) else self.cfg ), "model": self.model.state_dict(), "criterion": ( self.criterion.state_dict() if utils.has_parameters(self.criterion) else None ), "optimizer_history": (self._optim_history or []) + [ { "criterion_name": self.get_criterion().__class__.__name__, "optimizer_name": self.optimizer.__class__.__name__, "lr_scheduler_state": self.lr_scheduler.state_dict(), "num_updates": self.get_num_updates(), } ], "task_state": self.task.state_dict() if self.task is not None else {}, "extra_state": { "metrics": metrics.state_dict(), "previous_training_time": self.cumulative_training_time(), } } if not self.cfg.checkpoint.no_save_optimizer_state: state_dict["last_optimizer_state"] = self.optimizer.state_dict() return state_dict def save_checkpoint(self, filename, extra_state): """Save all training state in a checkpoint file.""" logger.info(f"Saving checkpoint to {filename}") # call state_dict on all ranks in case it needs internal communication state_dict = utils.move_to_cpu(self.state_dict()) state_dict["extra_state"].update(extra_state) if self.should_save_checkpoint_on_current_rank: checkpoint_utils.torch_persistent_save( state_dict, filename, async_write=self.cfg.checkpoint.write_checkpoints_asynchronously, ) logger.info(f"Finished saving checkpoint to {filename}") def load_checkpoint( self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None, reset_meters=False, ): """ Load all training state from a checkpoint file. rank = 0 will load the checkpoint, and then broadcast it to all other ranks. """ extra_state, self._optim_history, last_optim_state = None, [], None logger.info(f"Preparing to load checkpoint {filename}") is_distributed = self.data_parallel_world_size > 1 bexists = PathManager.isfile(filename) if bexists: load_on_all_ranks = ( self.cfg.checkpoint.load_checkpoint_on_all_dp_ranks # TPUs don't support broadcast yet, so load checkpoints # on every worker for now or self.tpu # FSDP requires loading checkpoint shards on all ranks or self.cfg.distributed_training.ddp_backend == "fully_sharded" ) if load_on_all_ranks or self.data_parallel_rank == 0: state = checkpoint_utils.load_checkpoint_to_cpu( filename, load_on_all_ranks=load_on_all_ranks ) last_optim_state = state.get("last_optimizer_state", None) # If doing zero_sharding, do not broadcast global optimizer # state. Later we will broadcast sharded states to each rank # to avoid memory from exploding. if ( not load_on_all_ranks and self.cfg.distributed_training.zero_sharding == "os" and "last_optimizer_state" in state and is_distributed ): state["last_optimizer_state"] = "SHARDED" else: last_optim_state = None state = None if is_distributed and not load_on_all_ranks: state = distributed_utils.broadcast_object( state, src_rank=0, group=self.data_parallel_process_group, dist_device=self.device, ) if self.data_parallel_rank > 0: last_optim_state = state.get("last_optimizer_state", None) # load model parameters try: self.model.load_state_dict( state["model"], strict=True, model_cfg=self.cfg.model ) # save memory for later steps del state["model"] if utils.has_parameters(self.get_criterion()): self.get_criterion().load_state_dict( state["criterion"], strict=True ) del state["criterion"] except Exception: raise Exception( "Cannot load model parameters from checkpoint {}; " "please ensure that the architectures match.".format(filename) ) extra_state = state["extra_state"] self._optim_history = state["optimizer_history"] if last_optim_state is not None and not reset_optimizer: # rebuild optimizer after loading model, since params may have changed self._build_optimizer() # only reload optimizer and lr_scheduler if they match last_optim = self._optim_history[-1] assert ( last_optim["criterion_name"] == self.get_criterion().__class__.__name__ ), f"Criterion does not match; please reset the optimizer (--reset-optimizer). {last_optim['criterion_name']} vs {self.get_criterion().__class__.__name__}" assert ( last_optim["optimizer_name"] == self.optimizer.__class__.__name__ ), f"Optimizer does not match; please reset the optimizer (--reset-optimizer). {last_optim['optimizer_name']} vs {self.optimizer.__class__.__name__}" if not reset_lr_scheduler: self.lr_scheduler.load_state_dict(last_optim["lr_scheduler_state"]) if not load_on_all_ranks and is_distributed: last_optim_state = self.optimizer.broadcast_global_state_dict( last_optim_state ) self.optimizer.load_state_dict(last_optim_state, optimizer_overrides) self.set_num_updates(last_optim["num_updates"]) if extra_state is not None: itr_state = extra_state["train_iterator"] epoch = itr_state["epoch"] if "previous_training_time" in extra_state: self._previous_training_time = extra_state["previous_training_time"] self._start_time = time.time() self.lr_step(epoch) if itr_state.get("version", 1) >= 2 and itr_state["iterations_in_epoch"] == 0: # reset meters at start of epoch reset_meters = True if "metrics" in extra_state and not reset_meters: metrics.load_state_dict(extra_state["metrics"]) # reset TimeMeters, since their start times don't make sense anymore for meter in metrics.get_meters("default"): if isinstance(meter, meters.TimeMeter): meter.reset() logger.info( "Loaded checkpoint {} (epoch {} @ {} updates)".format( filename, epoch, self.get_num_updates() ) ) else: logger.info("No existing checkpoint found {}".format(filename)) return extra_state def get_train_iterator( self, epoch, combine=True, load_dataset=True, data_selector=None, shard_batch_itr=True, disable_iterator_cache=False, ): """Return an EpochBatchIterator over the training set for a given epoch.""" if load_dataset: logger.info("loading train data for epoch {}".format(epoch)) self.task.load_dataset( self.cfg.dataset.train_subset, epoch=epoch, combine=combine, data_selector=data_selector, tpu=self.tpu, ) batch_iterator = self.task.get_batch_iterator( dataset=self.task.dataset(self.cfg.dataset.train_subset), max_tokens=self.cfg.dataset.max_tokens, max_sentences=self.cfg.dataset.batch_size, max_positions=utils.resolve_max_positions( self.task.max_positions(), self.model.max_positions(), self.cfg.dataset.max_tokens, ), ignore_invalid_inputs=True, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=self.data_parallel_world_size if shard_batch_itr else 1, shard_id=self.data_parallel_rank if shard_batch_itr else 0, num_workers=self.cfg.dataset.num_workers, epoch=epoch, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache, ) self.reset_dummy_batch(batch_iterator.first_batch) return batch_iterator def get_valid_iterator( self, subset, disable_iterator_cache=False, ): """Return an EpochBatchIterator over given validation subset for a given epoch.""" batch_iterator = self.task.get_batch_iterator( dataset=self.task.dataset(subset), max_tokens=self.cfg.dataset.max_tokens_valid, max_sentences=self.cfg.dataset.batch_size_valid, max_positions=utils.resolve_max_positions( self.task.max_positions(), self.model.max_positions(), ), ignore_invalid_inputs=self.cfg.dataset.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=self.cfg.dataset.required_batch_size_multiple, seed=self.cfg.common.seed, num_shards=self.data_parallel_world_size, shard_id=self.data_parallel_rank, num_workers=self.cfg.dataset.num_workers, # always pass a fixed "epoch" to keep validation data consistent # across training epochs epoch=1, data_buffer_size=self.cfg.dataset.data_buffer_size, disable_iterator_cache=disable_iterator_cache, ) self.reset_dummy_batch(batch_iterator.first_batch) return batch_iterator def begin_epoch(self, epoch): """Called at the beginning of each epoch.""" logger.info("begin training epoch {}".format(epoch)) self.lr_step_begin_epoch(epoch) if self.quantizer is not None: self.quantizer.begin_epoch(epoch) # task specific setup per epoch self.task.begin_epoch(epoch, self.get_model()) if self.tpu: import torch_xla.core.xla_model as xm xm.rendezvous("begin_epoch") # wait for all workers xm.mark_step() def begin_valid_epoch(self, epoch): """Called at the beginning of each validation epoch.""" # task specific setup per validation epoch self.task.begin_valid_epoch(epoch, self.get_model()) def reset_dummy_batch(self, batch): self._dummy_batch = batch @metrics.aggregate("train") def train_step(self, samples, raise_oom=False): """Do forward, backward and parameter update.""" self._set_seed() self.model.train() self.criterion.train() self.zero_grad() metrics.log_start_time("train_wall", priority=800, round=0) # forward and backward pass logging_outputs, sample_size, ooms = [], 0, 0 for i, sample in enumerate(samples): # delayed update loop sample, is_dummy_batch = self._prepare_sample(sample) def maybe_no_sync(): """ Whenever *samples* contains more than one mini-batch, we want to accumulate gradients locally and only call all-reduce in the last backwards pass. """ if ( self.data_parallel_world_size > 1 and hasattr(self.model, "no_sync") and i < len(samples) - 1 ): return self.model.no_sync() else: return contextlib.ExitStack() # dummy contextmanager try: with maybe_no_sync(): # forward and backward loss, sample_size_i, logging_output = self.task.train_step( sample=sample, model=self.model, criterion=self.criterion, optimizer=self.optimizer, update_num=self.get_num_updates(), ignore_grad=is_dummy_batch, ) del loss logging_outputs.append(logging_output) sample_size += sample_size_i # emptying the CUDA cache after the first step can # reduce the chance of OOM if self.cuda and self.get_num_updates() == 0: torch.cuda.empty_cache() except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) if raise_oom: raise e logger.warning( "attempting to recover from OOM in forward/backward pass" ) ooms += 1 self.zero_grad() if self.cuda: torch.cuda.empty_cache() if self.cfg.distributed_training.distributed_world_size == 1: return None else: raise e if self.tpu and i < len(samples) - 1: # tpu-comment: every XLA operation before marking step is # appended to the IR graph, and processing too many batches # before marking step can lead to OOM errors. # To handle gradient accumulation use case, we explicitly # mark step here for every forward pass without a backward pass self._xla_markstep_and_send_to_cpu() if is_dummy_batch: if torch.is_tensor(sample_size): sample_size.zero_() else: sample_size *= 0.0 if torch.is_tensor(sample_size): sample_size = sample_size.float() else: sample_size = float(sample_size) # gather logging outputs from all replicas if self._sync_stats(): train_time = self._local_cumulative_training_time() logging_outputs, ( sample_size, ooms, total_train_time, ) = self._aggregate_logging_outputs( logging_outputs, sample_size, ooms, train_time, ignore=is_dummy_batch ) self._cumulative_training_time = ( total_train_time / self.data_parallel_world_size ) overflow = False try: with torch.autograd.profiler.record_function("reduce-grads"): # reduce gradients across workers self.optimizer.all_reduce_grads(self.model) if utils.has_parameters(self.criterion): self.optimizer.all_reduce_grads(self.criterion) with torch.autograd.profiler.record_function("multiply-grads"): # multiply gradients by (data_parallel_size / sample_size) since # DDP normalizes by the number of data parallel workers for # improved fp16 precision. # Thus we get (sum_of_gradients / sample_size) at the end. # In case of fp16, this step also undoes loss scaling. # (Debugging note: Some optimizers perform this scaling on the # fly, so inspecting model.parameters() or optimizer.params may # still show the original, unscaled gradients.) numer = ( self.data_parallel_world_size if not self.cfg.optimization.use_bmuf or self._sync_stats() else 1 ) self.optimizer.multiply_grads(numer / (sample_size or 1.0)) # Note: (sample_size or 1.0) handles the case of a zero gradient, in a # way that avoids CPU/device transfers in case sample_size is a GPU or # TPU object. The assumption is that the gradient itself is also 0. with torch.autograd.profiler.record_function("clip-grads"): # clip grads grad_norm = self.clip_grad_norm(self.cfg.optimization.clip_norm) # check that grad norms are consistent across workers # on tpu check tensor is slow if not self.tpu: if ( not self.cfg.optimization.use_bmuf and self.cfg.distributed_training.ddp_backend != "slow_mo" ): self._check_grad_norms(grad_norm) if not torch.isfinite(grad_norm).all(): # check local gradnorm single GPU case, trigger NanDetector raise FloatingPointError("gradients are Nan/Inf") with torch.autograd.profiler.record_function("optimizer"): # take an optimization step self.task.optimizer_step( self.optimizer, model=self.model, update_num=self.get_num_updates() ) except FloatingPointError: # re-run the forward and backward pass with hooks attached to print # out where it fails self.zero_grad() with NanDetector(self.get_model()): for _, sample in enumerate(samples): sample, _ = self._prepare_sample(sample) self.task.train_step( sample, self.model, self.criterion, self.optimizer, self.get_num_updates(), ignore_grad=False, ) raise except OverflowError as e: overflow = True logger.info(f"NOTE: gradient overflow detected, ignoring gradient, {str(e)}") grad_norm = torch.tensor(0.0).cuda() self.zero_grad() except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) logger.error("OOM during optimization, irrecoverable") raise e # Some distributed wrappers (e.g., SlowMo) need access to the optimizer # after the step if hasattr(self.model, "perform_additional_optimizer_actions"): if hasattr(self.optimizer, "fp32_params"): self.model.perform_additional_optimizer_actions( self.optimizer.optimizer, self.optimizer.fp32_params ) else: self.model.perform_additional_optimizer_actions( self.optimizer.optimizer ) logging_output = None if not overflow or self.cfg.distributed_training.ddp_backend == "slow_mo": self.set_num_updates(self.get_num_updates() + 1) if self.tpu: import torch_xla.core.xla_model as xm # mark step on TPUs self._xla_markstep_and_send_to_cpu() # only log stats every log_interval steps # this causes wps to be misreported when log_interval > 1 logging_output = {} if self.get_num_updates() % self.cfg.common.log_interval == 0: # log memory usage mem_info = xm.get_memory_info(self.device) gb_free = mem_info["kb_free"] / 1024 / 1024 gb_total = mem_info["kb_total"] / 1024 / 1024 metrics.log_scalar( "gb_free", gb_free, priority=1500, round=1, weight=0 ) metrics.log_scalar( "gb_total", gb_total, priority=1600, round=1, weight=0 ) logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs) logging_output = self._reduce_and_log_stats( logging_outputs, sample_size, grad_norm ) # log whenever there's an XLA compilation, since these # slow down training and may indicate opportunities for # optimization self._check_xla_compilation() else: if self.cuda and self.cuda_env is not None: # log minimum free memory over the iteration gb_used = torch.cuda.max_memory_allocated() / 1024 / 1024 / 1024 torch.cuda.reset_peak_memory_stats() gb_free = self.cuda_env.total_memory_in_GB - gb_used metrics.log_scalar( "gb_free", gb_free, priority=1500, round=1, weight=0 ) # log stats logging_output = self._reduce_and_log_stats( logging_outputs, sample_size, grad_norm ) # clear CUDA cache to reduce memory fragmentation if ( self.cuda and self.cfg.common.empty_cache_freq > 0 and ( (self.get_num_updates() + self.cfg.common.empty_cache_freq - 1) % self.cfg.common.empty_cache_freq ) == 0 ): torch.cuda.empty_cache() if self.cfg.common.fp16: metrics.log_scalar( "loss_scale", self.optimizer.scaler.loss_scale, priority=700, round=4, weight=0, ) metrics.log_stop_time("train_wall") return logging_output @metrics.aggregate("valid") def valid_step(self, sample, raise_oom=False): """Do forward pass in evaluation mode.""" if self.tpu: import torch_xla.core.xla_model as xm xm.rendezvous("valid_step") # wait for all workers with torch.no_grad(): self.model.eval() self.criterion.eval() sample, is_dummy_batch = self._prepare_sample(sample) try: _loss, sample_size, logging_output = self.task.valid_step( sample, self.model, self.criterion ) except RuntimeError as e: if "out of memory" in str(e): self._log_oom(e) if not raise_oom: logger.warning( "ran out of memory in validation step, retrying batch" ) for p in self.model.parameters(): if p.grad is not None: p.grad = None # free some memory if self.cuda: torch.cuda.empty_cache() return self.valid_step(sample, raise_oom=True) raise e logging_outputs = [logging_output] if is_dummy_batch: if torch.is_tensor(sample_size): sample_size.zero_() else: sample_size *= 0.0 # gather logging outputs from all replicas if self.data_parallel_world_size > 1: logging_outputs, (sample_size,) = self._aggregate_logging_outputs( logging_outputs, sample_size, ignore=is_dummy_batch, ) # log validation stats if self.tpu: logging_outputs = self._xla_markstep_and_send_to_cpu(logging_outputs) logging_output = self._reduce_and_log_stats(logging_outputs, sample_size) return logging_output def zero_grad(self): self.optimizer.zero_grad() def lr_step_begin_epoch(self, epoch): """Adjust the learning rate at the beginning of the epoch.""" self.lr_scheduler.step_begin_epoch(epoch) # prefer updating the LR based on the number of steps return self.lr_step_update() def lr_step(self, epoch, val_loss=None): """Adjust the learning rate at the end of the epoch.""" self.lr_scheduler.step(epoch, val_loss) # prefer updating the LR based on the number of steps return self.lr_step_update() def lr_step_update(self): """Update the learning rate after each update.""" new_lr = self.lr_scheduler.step_update(self.get_num_updates()) if isinstance(new_lr, dict): for k, v in new_lr.items(): metrics.log_scalar(f"lr_{k}", v, weight=0, priority=300) new_lr = new_lr.get("default", next(iter(new_lr.values()))) else: metrics.log_scalar("lr", new_lr, weight=0, priority=300) return new_lr def get_lr(self): """Get the current learning rate.""" return self.optimizer.get_lr() def get_model(self): """Get the (non-wrapped) model instance.""" return self._model def get_criterion(self): """Get the (non-wrapped) criterion instance.""" return self._criterion def get_meter(self, name): """[deprecated] Get a specific meter by name.""" from fairseq import meters if "get_meter" not in self._warn_once: self._warn_once.add("get_meter") utils.deprecation_warning( "Trainer.get_meter is deprecated. Please use fairseq.metrics instead." ) train_meters = metrics.get_meters("train") if train_meters is None: train_meters = {} if name == "train_loss" and "loss" in train_meters: return train_meters["loss"] elif name == "train_nll_loss": # support for legacy train.py, which assumed this meter is # always initialized m = train_meters.get("nll_loss", None) return m or meters.AverageMeter() elif name == "wall": # support for legacy train.py, which assumed this meter is # always initialized m = metrics.get_meter("default", "wall") return m or meters.TimeMeter() elif name == "wps": m = metrics.get_meter("train", "wps") return m or meters.TimeMeter() elif name in {"valid_loss", "valid_nll_loss"}: # support for legacy train.py, which assumed these meters # are always initialized k = name[len("valid_") :] m = metrics.get_meter("valid", k) return m or meters.AverageMeter() elif name == "oom": return meters.AverageMeter() elif name in train_meters: return train_meters[name] return None def get_num_updates(self): """Get the number of parameters updates.""" return self._num_updates def set_num_updates(self, num_updates): """Set the number of parameters updates.""" self._num_updates = num_updates self.lr_step_update() if self.quantizer: self.quantizer.step_update(self._num_updates) metrics.log_scalar("num_updates", self._num_updates, weight=0, priority=200) def clip_grad_norm(self, clip_norm): def agg_norm_fn(total_norm): total_norm = total_norm.cuda().float() ** 2 total_norm = distributed_utils.all_reduce( total_norm, group=self.data_parallel_process_group ) return total_norm ** 0.5 should_agg_norm = ( self.cfg.distributed_training.ddp_backend == "fully_sharded" and ( self.data_parallel_process_group is not None or torch.distributed.is_initialized() ) ) return self.optimizer.clip_grad_norm( clip_norm, aggregate_norm_fn=agg_norm_fn if should_agg_norm else None ) def cumulative_training_time(self): if self._cumulative_training_time is None: # single GPU return self._local_cumulative_training_time() else: return self._cumulative_training_time def _local_cumulative_training_time(self): """Aggregate training time in seconds.""" return time.time() - self._start_time + self._previous_training_time def _prepare_sample(self, sample, is_dummy=False): if sample == "DUMMY": raise Exception( "Trying to use an uninitialized 'dummy' batch. This usually indicates " "that the total number of batches is smaller than the number of " "participating GPUs. Try reducing the batch size or using fewer GPUs." ) if sample is None or len(sample) == 0: assert ( self._dummy_batch is not None and len(self._dummy_batch) > 0 ), "Invalid dummy batch: {}".format(self._dummy_batch) sample, _ = self._prepare_sample(self._dummy_batch, is_dummy=True) return sample, True if self.cuda: if self.pipeline_model_parallel: if "target" in sample: sample["target"] = utils.move_to_cuda( sample["target"], device=self.last_device ) else: sample = utils.move_to_cuda(sample) elif self.tpu and is_dummy: # the dummy batch may not be on the appropriate device sample = utils.move_to_cuda(sample, device=self.device) def apply_half(t): if t.dtype is torch.float32: return t.half() return t def apply_bfloat16(t): if t.dtype is torch.float32: return t.to(dtype=torch.bfloat16) return t if self.cfg.common.fp16: sample = utils.apply_to_sample(apply_half, sample) if self.cfg.common.bf16: sample = utils.apply_to_sample(apply_bfloat16, sample) if self._dummy_batch == "DUMMY": self._dummy_batch = sample return sample, False def _set_seed(self): # Set seed based on args.seed and the update number so that we get # reproducible results when resuming from checkpoints seed = self.cfg.common.seed + self.get_num_updates() utils.set_torch_seed(seed) def _sync_stats(self): # Return True if it's using multiple GPUs and DDP or multiple GPUs with # BMUF and it's a bmuf sync with warmup iterations completed before. if self.data_parallel_world_size == 1: return False elif self.cfg.optimization.use_bmuf: return ( self.get_num_updates() + 1 ) % self.cfg.bmuf.global_sync_iter == 0 and ( self.get_num_updates() + 1 ) > self.cfg.bmuf.warmup_iterations else: return True def _log_oom(self, exc): msg = "OOM: Ran out of memory with exception: {}".format(exc) logger.warning(msg) if torch.cuda.is_available() and hasattr(torch.cuda, "memory_summary"): for device_idx in range(torch.cuda.device_count()): logger.warning(torch.cuda.memory_summary(device=device_idx)) sys.stderr.flush() def _aggregate_logging_outputs( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): if self.task.__class__.logging_outputs_can_be_summed(self.get_criterion()): return self._fast_stat_sync_sum( logging_outputs, *extra_stats_to_sum, ignore=ignore ) else: return self._all_gather_list_sync( logging_outputs, *extra_stats_to_sum, ignore=ignore ) def _all_gather_list_sync( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. all_gather_list_sync is suitable when logging outputs are complex types. """ if self.tpu: raise NotImplementedError if ignore: logging_outputs = [] results = list( zip( *distributed_utils.all_gather_list( [logging_outputs] + list(extra_stats_to_sum), max_size=getattr(self.cfg.common, "all_gather_list_size", 16384), group=self.data_parallel_process_group, ) ) ) logging_outputs, extra_stats_to_sum = results[0], results[1:] logging_outputs = list(chain.from_iterable(logging_outputs)) extra_stats_to_sum = [sum(s) for s in extra_stats_to_sum] return logging_outputs, extra_stats_to_sum def _fast_stat_sync_sum( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. fast_stat_sync_sum is faster than all_gather_list_sync, but is only suitable when logging outputs are scalars and can be summed. Note that *logging_outputs* cannot contain any nested dicts/lists. """ data = {} for i, stat in enumerate(extra_stats_to_sum): data["extra_stats_" + str(i)] = stat if len(logging_outputs) > 0: log_keys = list(logging_outputs[0].keys()) for k in log_keys: if not ignore: v = sum(log[k] for log in logging_outputs if k in log) else: v = logging_outputs[0][k] v = torch.zeros_like(v) if torch.is_tensor(v) else 0 data["logging_outputs_" + k] = v else: log_keys = None data = distributed_utils.all_reduce_dict( data, device=self.device, group=self.data_parallel_process_group ) extra_stats_to_sum = [ data["extra_stats_" + str(i)] for i in range(len(extra_stats_to_sum)) ] if log_keys is not None: logging_outputs = [{k: data["logging_outputs_" + k] for k in log_keys}] else: logging_outputs = [] return logging_outputs, extra_stats_to_sum def _check_grad_norms(self, grad_norm): """Check that grad norms are consistent across workers.""" if self._grad_norm_buf is not None: self._grad_norm_buf.zero_() self._grad_norm_buf[self.data_parallel_rank] = grad_norm distributed_utils.all_reduce( self._grad_norm_buf, group=self.data_parallel_process_group ) def is_consistent(tensor): max_abs_diff = torch.max(torch.abs(tensor - tensor[0])) return ( torch.isfinite(tensor).all() and (max_abs_diff / (tensor[0] + 1e-6) < 1e-6).all() ) if not is_consistent(self._grad_norm_buf): pretty_detail = "\n".join( "rank {:3d} = {:.8f}".format(r, n) for r, n in enumerate(self._grad_norm_buf.tolist()) ) error_detail = "grad_norm across the workers:\n{}\n".format( pretty_detail ) # use FloatingPointError to trigger NanDetector raise FloatingPointError( "Fatal error: gradients are inconsistent between workers. " "Try --ddp-backend=legacy_ddp. " "Or are you mixing up different generation of GPUs in training?" + "\n" + "-" * 80 + "\n{}\n".format(error_detail) + "-" * 80 ) def _reduce_and_log_stats(self, logging_outputs, sample_size, grad_norm=None): if grad_norm is not None and ( not torch.is_tensor(grad_norm) or torch.isfinite(grad_norm) ): metrics.log_speed("ups", 1.0, priority=100, round=2) metrics.log_scalar("gnorm", grad_norm, priority=400, round=3) if self.cfg.optimization.clip_norm > 0: metrics.log_scalar( "clip", torch.where( grad_norm > self.cfg.optimization.clip_norm, grad_norm.new_tensor(100), grad_norm.new_tensor(0), ), priority=500, round=1, ) with metrics.aggregate() as agg: if logging_outputs is not None: self.task.reduce_metrics(logging_outputs, self.get_criterion()) del logging_outputs # extra warning for criterions that don't properly log a loss value if "loss" not in agg: if "loss" not in self._warn_once: self._warn_once.add("loss") logger.warning( "Criterion.reduce_metrics did not log a 'loss' value, " "which may break some functionality" ) metrics.log_scalar("loss", -1) # support legacy interface if self.tpu: logging_output = {} else: logging_output = agg.get_smoothed_values() logging_output["sample_size"] = sample_size for key_to_delete in ["ppl", "wps", "wpb", "bsz"]: if key_to_delete in logging_output: del logging_output[key_to_delete] return logging_output def _check_xla_compilation(self): import torch_xla.debug.metrics as met compile_stats = met.metric_data("CompileTime") if compile_stats is None: return num_xla_compiles = compile_stats[0] if num_xla_compiles > self._num_xla_compiles: logger.warning( "XLA compilation detected on device #{}; too many of these can lead " "to slow training, but we expect a few in the beginning".format( self.cfg.distributed_training.distributed_rank ) ) self._num_xla_compiles = num_xla_compiles def _xla_markstep_and_send_to_cpu(self, data=None): import torch_xla.core.xla_model as xm xm.mark_step() if data is not None: from fairseq.utils import xla_device_to_cpu return xla_device_to_cpu(data) def _catalog_shared_params(module, memo=None, prefix=""): if memo is None: first_call = True memo = {} else: first_call = False for name, param in module._parameters.items(): param_prefix = prefix + ("." if prefix else "") + name if param not in memo: memo[param] = [] memo[param].append(param_prefix) for name, m in module._modules.items(): if m is None: continue submodule_prefix = prefix + ("." if prefix else "") + name _catalog_shared_params(m, memo, submodule_prefix) if first_call: return [x for x in memo.values() if len(x) > 1] def _get_module_by_path(module, path): path = path.split(".") for name in path: module = getattr(module, name) return module def _set_module_by_path(module, path, value): path = path.split(".") for name in path[:-1]: module = getattr(module, name) setattr(module, path[-1], value)
import argparse import time import csv import yaml import os import logging from pathlib import Path import numpy as np from tqdm import tqdm from tensorboardX import SummaryWriter import cv2 import matplotlib.pyplot as plt class plot_results(object): def __init__(self, frame_list=[100], mode='base'): # frame_list = [0, 100, 200, 300] # frame_list = [100, 700, 1200] # frame_list = [100] self.frame_list = frame_list print(f"mode = {mode}") self.get_image_names(mode=mode) pass def get_image_names(self, mode='base'): frame_list = self.frame_list plot_folder = "plots/" image_name = None if mode == 'base': prefix = ["Si-Df-k", "Sp-Df-fp-end-k"] plot_name = "mask_conf_" # 'corr_all_' # image_name = [f"{plot_folder}{plot_name}{prefix}{i:06}_{(i+1):06}.png" for i in frame_list] elif mode == 'good' or mode == 'bad': prefix = [f"Si-Df-fp-k_{mode}", f"Sp-Df-fp-end-k_{mode}"] plot_name = "mask_conf_" # "mask_conf_" # 'corr_all_' elif mode == 'freeze': print(f"freeze!") iter_list = [0, 400, 1000] prefix_base = "Sp-Df-f-end-k-freezeDf" plot_name = 'corr_all_random_' # 'corr_all_', "mask_conf_" "epi_dist_all_" "corr_all_random_" print(f"plot_name: {plot_name}") # prefix = [f'{prefix_base}_{iter/1000}k_' for iter in iter_list] # 'Sp-Df-fp-end-k' prefix = [f'{prefix_base}_s{frame_list[0]}_{iter/1000}k' for iter in iter_list] # 'Sp-Df-fp-end-k' image_name = [f"{plot_folder}{plot_name}{p}.png" for p in prefix] # prefix = f'Sp-Df-f-end-k-freezeDf_s{j}_{iter/1000}k' # image_name = [ # f"{plot_folder}{plot_name}{pre}{i:06}_{(i+1):06}.png" # for i in frame_list # for pre in prefix # ] if image_name is None: image_name = [ f"{plot_folder}{plot_name}{pre}_{i}.png" for i in frame_list for pre in prefix ] self.prefix = prefix self.image_name = image_name self.image_data = [] self.plot_name = plot_name print(image_name) def __len__(self): return len(self.image_name) def read_images(self): image_data = [] image_name = self.image_name for i, file in enumerate(image_name): img = cv2.imread(file) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image_data.append(img) print(f"read {i}: {file}") # plt.imshow(img) # plt.show() self.image_data = image_data pass def plot_images( self, row=2, col=2, col_labels=["Baseline - Si-Df-fp", "Ours - Sp-Df-fp-end"], save=True, figsize=(48,12), ext='pdf' ): ## create subgraph for combinations # row, col = 2, 2 img_num = row * col assert self.__len__() >= img_num image_data = self.image_data f, axarr = plt.subplots(row, col, figsize=figsize) # f, axarr = plt.subplots(row, col, figsize=(48, 12)) axarr = axarr.reshape(-1, col) for i in range(img_num): print(f"axarr: {axarr.shape}, i= {i}") axarr[int(i / col), int(i % col)].imshow(image_data[i]) axarr[int(i / col), int(i % col)].axis("off") # axarr[i/2,i%2].imshow(imaget(_datas[1]) # axarr[1,0].imshow(image_datas[2]) # axarr[1,1].imshow(image_datas[3]) for ax, col_name in zip(axarr[0], col_labels): ax.set_title(col_name, fontsize=figsize[0]) f.tight_layout() # f.suptitle(f'{self.prefix}', fontsize=12) savefile = f"{self.plot_name}_{str("_").join(self.prefix)}_{str("_").join([str(f) for f in self.frame_list])}" if save: if ext == 'pdf': file = f"plots/{savefile}.pdf" plt.savefig(file, bbox_inches="tight") else: file = f"plots/{savefile}.png" plt.savefig(file, dpi=300, bbox_inches="tight") logging.info(f"save image: {savefile}") print(f"save image: {file}") else: print(f"not saved!!") # logging.info(f"save image: {file}") plt.show() if __name__ == "__main__": plot_helper = plot_class() plot_helper.read_images() # plot_helper.plot_images(row=3,col=2) plot_helper.plot_images(row=1,col=2) # class plot_class(object): # def __init__(self): # # frame_list = [0, 100, 200, 300] # frame_list = [100, 700, 1200] # # frame_list = [100] # prefix = ['Si-Df-k', 'Sp-Df-fp-end-k'] # plot_folder = 'plots/' # plot_name = 'mask_conf_' # 'corr_all_' # # image_name = [f"{plot_folder}{plot_name}{prefix}{i:06}_{(i+1):06}.png" for i in frame_list] # image_name = [f"{plot_folder}{plot_name}{pre}{i:06}_{(i+1):06}.png" for i in frame_list for pre in prefix ] # self.frame_list = frame_list # self.prefix = prefix # self.image_name = image_name # self.image_data = [] # print(image_name) # pass # def __len__(self): # return len(self.image_name) # def read_images(self): # image_data = [] # image_name = self.image_name # for i, file in enumerate(image_name): # img = cv2.imread(file) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # image_data.append(img) # print(f"read {i}: {file}") # # plt.imshow(img) # # plt.show() # self.image_data = image_data # pass # def plot_images(self, row=2, col=2, col_labels=['Baseline - Si-Df-fp', 'Ours - Sp-Df-fp-end']): # ## create subgraph for combinations # # row, col = 2, 2 # img_num = row*col # assert self.__len__() >= img_num # image_data = self.image_data # f, axarr = plt.subplots(row, col, figsize=(48, 12)) # # f, axarr = plt.subplots(row, col, figsize=(48, 12)) # axarr = axarr.reshape(-1, col) # for i in range(img_num): # print(f'axarr: {axarr.shape}, i= {i}') # axarr[int(i/col),int(i%col)].imshow(image_data[i]) # axarr[int(i/col),int(i%col)].axis('off') # # axarr[i/2,i%2].imshow(imaget(_datas[1]) # # axarr[1,0].imshow(image_datas[2]) # # axarr[1,1].imshow(image_datas[3]) # for ax, col_name in zip(axarr[0], col_labels): # ax.set_title(col_name) # f.tight_layout() # # f.suptitle(f'{self.prefix}', fontsize=12) # savefile = f"{str("_").join(self.prefix)}_{str("_").join([str(f) for f in self.frame_list])}" # file = f"plots/{savefile}.png" # # logging.info(f"save image: {file}") # print(f"save image: {file}") # plt.show() # def plot_imgs(imgs, titles=None, cmap='brg', ylabel='', normalize=False, ax=None, dpi=100): # n = len(imgs) # if not isinstance(cmap, list): # cmap = [cmap]*n # if ax is None: # fig, ax = plt.subplots(1, n, figsize=(6*n, 6), dpi=dpi) # if n == 1: # ax = [ax] # else: # if not isinstance(ax, list): # ax = [ax] # assert len(ax) == len(imgs) # for i in range(n): # if imgs[i].shape[-1] == 3: # imgs[i] = imgs[i][..., ::-1] # BGR to RGB # ax[i].imshow(imgs[i], cmap=plt.get_cmap(cmap[i]), # vmin=None if normalize else 0, # vmax=None if normalize else 1) # if titles: # ax[i].set_title(titles[i]) # ax[i].get_yaxis().set_ticks([]) # ax[i].get_xaxis().set_ticks([]) # for spine in ax[i].spines.values(): # remove frame # spine.set_visible(False) # ax[0].set_ylabel(ylabel) # plt.tight_layout() # # from utils.draw import img_overlap # def img_overlap(img_r, img_g, img_gray): # img_b repeat # img = np.concatenate((img_gray, img_gray, img_gray), axis=0) # img[0, :, :] += img_r[0, :, :] # img[1, :, :] += img_g[0, :, :] # img[img > 1] = 1 # img[img < 0] = 0 # return img # def draw_keypoints(img, corners, color=(0, 255, 0), radius=3, s=3): # ''' # :param img: # image: # numpy [H, W] # :param corners: # Points # numpy [N, 2] # :param color: # :param radius: # :param s: # :return: # overlaying image # numpy [H, W] # ''' # img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[..., np.newaxis], 3, -1) # for c in np.stack(corners).T: # # cv2.circle(img, tuple(s * np.flip(c, 0)), radius, color, thickness=-1) # cv2.circle(img, tuple((s * c[:2]).astype(int)), radius, color, thickness=-1) # return img # # def draw_keypoints(img, corners, color=(0, 255, 0), radius=3, s=3): # # ''' # # :param img: # # np (H, W) # # :param corners: # # np (3, N) # # :param color: # # :param radius: # # :param s: # # :return: # # ''' # # img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[..., np.newaxis], 3, -1) # # for c in np.stack(corners).T: # # # cv2.circle(img, tuple(s * np.flip(c, 0)), radius, color, thickness=-1) # # cv2.circle(img, tuple((s*c[:2]).astype(int)), radius, color, thickness=-1) # # return img # def draw_matches(rgb1, rgb2, match_pairs, filename='matches.png', show=False): # ''' # :param rgb1: # image1 # numpy (H, W) # :param rgb2: # image2 # numpy (H, W) # :param match_pairs: # numpy (keypoiny1 x, keypoint1 y, keypoint2 x, keypoint 2 y) # :return: # None # ''' # from matplotlib import pyplot as plt # h1, w1 = rgb1.shape[:2] # h2, w2 = rgb2.shape[:2] # canvas = np.zeros((max(h1, h2), w1 + w2, 3), dtype=rgb1.dtype) # canvas[:h1, :w1] = rgb1[:,:,np.newaxis] # canvas[:h2, w1:] = rgb2[:,:,np.newaxis] # # fig = plt.figure(frameon=False) # fig = plt.imshow(canvas) # xs = match_pairs[:, [0, 2]] # xs[:, 1] += w1 # ys = match_pairs[:, [1, 3]] # alpha = 1 # sf = 5 # lw = 0.5 # # markersize = 1 # markersize = 2 # plt.plot( # xs.T, ys.T, # alpha=alpha, # linestyle="-", # linewidth=lw, # aa=False, # marker='o', # markersize=markersize, # fillstyle='none', # color=[0.0, 0.8, 0.0], # ); # plt.tight_layout() # plt.savefig(filename, dpi=300, bbox_inches='tight') # print('#Matches = {}'.format(len(match_pairs))) # if show: # plt.show() # # from utils.draw import draw_matches_cv # def draw_matches_cv(data): # keypoints1 = [cv2.KeyPoint(p[1], p[0], 1) for p in data['keypoints1']] # keypoints2 = [cv2.KeyPoint(p[1], p[0], 1) for p in data['keypoints2']] # inliers = data['inliers'].astype(bool) # matches = np.array(data['matches'])[inliers].tolist() # def to3dim(img): # if img.ndim == 2: # img = img[:, :, np.newaxis] # return img # img1 = to3dim(data['image1']) # img2 = to3dim(data['image2']) # img1 = np.concatenate([img1, img1, img1], axis=2) # img2 = np.concatenate([img2, img2, img2], axis=2) # return cv2.drawMatches(img1, keypoints1, img2, keypoints2, matches, # None, matchColor=(0,255,0), singlePointColor=(0, 0, 255)) # def drawBox(points, img, offset=np.array([0,0]), color=(0,255,0)): # # print("origin", points) # offset = offset[::-1] # points = points + offset # points = points.astype(int) # for i in range(len(points)): # img = img + cv2.line(np.zeros_like(img),tuple(points[-1+i]), tuple(points[i]), color,5) # return img
import argparse import time import csv import yaml import os import logging from pathlib import Path import numpy as np from tqdm import tqdm from tensorboardX import SummaryWriter import cv2 import matplotlib.pyplot as plt class plot_results(object): def __init__(self, frame_list=[100], mode='base'): # frame_list = [0, 100, 200, 300] # frame_list = [100, 700, 1200] # frame_list = [100] self.frame_list = frame_list print(f"mode = {mode}") self.get_image_names(mode=mode) pass def get_image_names(self, mode='base'): frame_list = self.frame_list plot_folder = "plots/" image_name = None if mode == 'base': prefix = ["Si-Df-k", "Sp-Df-fp-end-k"] plot_name = "mask_conf_" # 'corr_all_' # image_name = [f"{plot_folder}{plot_name}{prefix}{i:06}_{(i+1):06}.png" for i in frame_list] elif mode == 'good' or mode == 'bad': prefix = [f"Si-Df-fp-k_{mode}", f"Sp-Df-fp-end-k_{mode}"] plot_name = "mask_conf_" # "mask_conf_" # 'corr_all_' elif mode == 'freeze': print(f"freeze!") iter_list = [0, 400, 1000] prefix_base = "Sp-Df-f-end-k-freezeDf" plot_name = 'corr_all_random_' # 'corr_all_', "mask_conf_" "epi_dist_all_" "corr_all_random_" print(f"plot_name: {plot_name}") # prefix = [f'{prefix_base}_{iter/1000}k_' for iter in iter_list] # 'Sp-Df-fp-end-k' prefix = [f'{prefix_base}_s{frame_list[0]}_{iter/1000}k' for iter in iter_list] # 'Sp-Df-fp-end-k' image_name = [f"{plot_folder}{plot_name}{p}.png" for p in prefix] # prefix = f'Sp-Df-f-end-k-freezeDf_s{j}_{iter/1000}k' # image_name = [ # f"{plot_folder}{plot_name}{pre}{i:06}_{(i+1):06}.png" # for i in frame_list # for pre in prefix # ] if image_name is None: image_name = [ f"{plot_folder}{plot_name}{pre}_{i}.png" for i in frame_list for pre in prefix ] self.prefix = prefix self.image_name = image_name self.image_data = [] self.plot_name = plot_name print(image_name) def __len__(self): return len(self.image_name) def read_images(self): image_data = [] image_name = self.image_name for i, file in enumerate(image_name): img = cv2.imread(file) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image_data.append(img) print(f"read {i}: {file}") # plt.imshow(img) # plt.show() self.image_data = image_data pass def plot_images( self, row=2, col=2, col_labels=["Baseline - Si-Df-fp", "Ours - Sp-Df-fp-end"], save=True, figsize=(48,12), ext='pdf' ): ## create subgraph for combinations # row, col = 2, 2 img_num = row * col assert self.__len__() >= img_num image_data = self.image_data f, axarr = plt.subplots(row, col, figsize=figsize) # f, axarr = plt.subplots(row, col, figsize=(48, 12)) axarr = axarr.reshape(-1, col) for i in range(img_num): print(f"axarr: {axarr.shape}, i= {i}") axarr[int(i / col), int(i % col)].imshow(image_data[i]) axarr[int(i / col), int(i % col)].axis("off") # axarr[i/2,i%2].imshow(imaget(_datas[1]) # axarr[1,0].imshow(image_datas[2]) # axarr[1,1].imshow(image_datas[3]) for ax, col_name in zip(axarr[0], col_labels): ax.set_title(col_name, fontsize=figsize[0]) f.tight_layout() # f.suptitle(f'{self.prefix}', fontsize=12) savefile = f"{self.plot_name}_{str('_').join(self.prefix)}_{str('_').join([str(f) for f in self.frame_list])}" if save: if ext == 'pdf': file = f"plots/{savefile}.pdf" plt.savefig(file, bbox_inches="tight") else: file = f"plots/{savefile}.png" plt.savefig(file, dpi=300, bbox_inches="tight") logging.info(f"save image: {savefile}") print(f"save image: {file}") else: print(f"not saved!!") # logging.info(f"save image: {file}") plt.show() if __name__ == "__main__": plot_helper = plot_class() plot_helper.read_images() # plot_helper.plot_images(row=3,col=2) plot_helper.plot_images(row=1,col=2) # class plot_class(object): # def __init__(self): # # frame_list = [0, 100, 200, 300] # frame_list = [100, 700, 1200] # # frame_list = [100] # prefix = ['Si-Df-k', 'Sp-Df-fp-end-k'] # plot_folder = 'plots/' # plot_name = 'mask_conf_' # 'corr_all_' # # image_name = [f"{plot_folder}{plot_name}{prefix}{i:06}_{(i+1):06}.png" for i in frame_list] # image_name = [f"{plot_folder}{plot_name}{pre}{i:06}_{(i+1):06}.png" for i in frame_list for pre in prefix ] # self.frame_list = frame_list # self.prefix = prefix # self.image_name = image_name # self.image_data = [] # print(image_name) # pass # def __len__(self): # return len(self.image_name) # def read_images(self): # image_data = [] # image_name = self.image_name # for i, file in enumerate(image_name): # img = cv2.imread(file) # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # image_data.append(img) # print(f"read {i}: {file}") # # plt.imshow(img) # # plt.show() # self.image_data = image_data # pass # def plot_images(self, row=2, col=2, col_labels=['Baseline - Si-Df-fp', 'Ours - Sp-Df-fp-end']): # ## create subgraph for combinations # # row, col = 2, 2 # img_num = row*col # assert self.__len__() >= img_num # image_data = self.image_data # f, axarr = plt.subplots(row, col, figsize=(48, 12)) # # f, axarr = plt.subplots(row, col, figsize=(48, 12)) # axarr = axarr.reshape(-1, col) # for i in range(img_num): # print(f'axarr: {axarr.shape}, i= {i}') # axarr[int(i/col),int(i%col)].imshow(image_data[i]) # axarr[int(i/col),int(i%col)].axis('off') # # axarr[i/2,i%2].imshow(imaget(_datas[1]) # # axarr[1,0].imshow(image_datas[2]) # # axarr[1,1].imshow(image_datas[3]) # for ax, col_name in zip(axarr[0], col_labels): # ax.set_title(col_name) # f.tight_layout() # # f.suptitle(f'{self.prefix}', fontsize=12) # savefile = f"{str('_').join(self.prefix)}_{str('_').join([str(f) for f in self.frame_list])}" # file = f"plots/{savefile}.png" # # logging.info(f"save image: {file}") # print(f"save image: {file}") # plt.show() # def plot_imgs(imgs, titles=None, cmap='brg', ylabel='', normalize=False, ax=None, dpi=100): # n = len(imgs) # if not isinstance(cmap, list): # cmap = [cmap]*n # if ax is None: # fig, ax = plt.subplots(1, n, figsize=(6*n, 6), dpi=dpi) # if n == 1: # ax = [ax] # else: # if not isinstance(ax, list): # ax = [ax] # assert len(ax) == len(imgs) # for i in range(n): # if imgs[i].shape[-1] == 3: # imgs[i] = imgs[i][..., ::-1] # BGR to RGB # ax[i].imshow(imgs[i], cmap=plt.get_cmap(cmap[i]), # vmin=None if normalize else 0, # vmax=None if normalize else 1) # if titles: # ax[i].set_title(titles[i]) # ax[i].get_yaxis().set_ticks([]) # ax[i].get_xaxis().set_ticks([]) # for spine in ax[i].spines.values(): # remove frame # spine.set_visible(False) # ax[0].set_ylabel(ylabel) # plt.tight_layout() # # from utils.draw import img_overlap # def img_overlap(img_r, img_g, img_gray): # img_b repeat # img = np.concatenate((img_gray, img_gray, img_gray), axis=0) # img[0, :, :] += img_r[0, :, :] # img[1, :, :] += img_g[0, :, :] # img[img > 1] = 1 # img[img < 0] = 0 # return img # def draw_keypoints(img, corners, color=(0, 255, 0), radius=3, s=3): # ''' # :param img: # image: # numpy [H, W] # :param corners: # Points # numpy [N, 2] # :param color: # :param radius: # :param s: # :return: # overlaying image # numpy [H, W] # ''' # img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[..., np.newaxis], 3, -1) # for c in np.stack(corners).T: # # cv2.circle(img, tuple(s * np.flip(c, 0)), radius, color, thickness=-1) # cv2.circle(img, tuple((s * c[:2]).astype(int)), radius, color, thickness=-1) # return img # # def draw_keypoints(img, corners, color=(0, 255, 0), radius=3, s=3): # # ''' # # :param img: # # np (H, W) # # :param corners: # # np (3, N) # # :param color: # # :param radius: # # :param s: # # :return: # # ''' # # img = np.repeat(cv2.resize(img, None, fx=s, fy=s)[..., np.newaxis], 3, -1) # # for c in np.stack(corners).T: # # # cv2.circle(img, tuple(s * np.flip(c, 0)), radius, color, thickness=-1) # # cv2.circle(img, tuple((s*c[:2]).astype(int)), radius, color, thickness=-1) # # return img # def draw_matches(rgb1, rgb2, match_pairs, filename='matches.png', show=False): # ''' # :param rgb1: # image1 # numpy (H, W) # :param rgb2: # image2 # numpy (H, W) # :param match_pairs: # numpy (keypoiny1 x, keypoint1 y, keypoint2 x, keypoint 2 y) # :return: # None # ''' # from matplotlib import pyplot as plt # h1, w1 = rgb1.shape[:2] # h2, w2 = rgb2.shape[:2] # canvas = np.zeros((max(h1, h2), w1 + w2, 3), dtype=rgb1.dtype) # canvas[:h1, :w1] = rgb1[:,:,np.newaxis] # canvas[:h2, w1:] = rgb2[:,:,np.newaxis] # # fig = plt.figure(frameon=False) # fig = plt.imshow(canvas) # xs = match_pairs[:, [0, 2]] # xs[:, 1] += w1 # ys = match_pairs[:, [1, 3]] # alpha = 1 # sf = 5 # lw = 0.5 # # markersize = 1 # markersize = 2 # plt.plot( # xs.T, ys.T, # alpha=alpha, # linestyle="-", # linewidth=lw, # aa=False, # marker='o', # markersize=markersize, # fillstyle='none', # color=[0.0, 0.8, 0.0], # ); # plt.tight_layout() # plt.savefig(filename, dpi=300, bbox_inches='tight') # print('#Matches = {}'.format(len(match_pairs))) # if show: # plt.show() # # from utils.draw import draw_matches_cv # def draw_matches_cv(data): # keypoints1 = [cv2.KeyPoint(p[1], p[0], 1) for p in data['keypoints1']] # keypoints2 = [cv2.KeyPoint(p[1], p[0], 1) for p in data['keypoints2']] # inliers = data['inliers'].astype(bool) # matches = np.array(data['matches'])[inliers].tolist() # def to3dim(img): # if img.ndim == 2: # img = img[:, :, np.newaxis] # return img # img1 = to3dim(data['image1']) # img2 = to3dim(data['image2']) # img1 = np.concatenate([img1, img1, img1], axis=2) # img2 = np.concatenate([img2, img2, img2], axis=2) # return cv2.drawMatches(img1, keypoints1, img2, keypoints2, matches, # None, matchColor=(0,255,0), singlePointColor=(0, 0, 255)) # def drawBox(points, img, offset=np.array([0,0]), color=(0,255,0)): # # print("origin", points) # offset = offset[::-1] # points = points + offset # points = points.astype(int) # for i in range(len(points)): # img = img + cv2.line(np.zeros_like(img),tuple(points[-1+i]), tuple(points[i]), color,5) # return img
from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.errors import UserIsBlocked, PeerIdInvalid from LuciferMoringstar_Robot.database.autofilter_db import is_subscribed, get_file_details from LuciferMoringstar_Robot.database._utils import get_size from translation import LuciferMoringstar from config import BUTTONS, FORCES_SUB, CUSTOM_FILE_CAPTION, START_MSG, DEV_NAME, bot_info, ADMINS @LuciferMoringstar_Robot.on_callback_query() async def cb_handler(client: LuciferMoringstar_Robot, query): clicked = query.from_user.id try: typed = query.message.reply_to_message.from_user.id except: typed = query.from_user.id if (clicked == typed): # # ---------- 🔘 [ | 𝗚𝗥𝗢𝗨𝗣 𝗙𝗜𝗟𝗧𝗘𝗥𝗦 | ] 🔘 ---------- # # if query.data.startswith("nextgroup"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)+1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("backgroup"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)-1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return # # ---------- 🔘 [ | 𝗕𝗢𝗧 𝗣𝗠 𝗙𝗜𝗟𝗧𝗘𝗥𝗦 | ] 🔘 ---------- # # elif query.data.startswith("nextbot"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)+1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("backbot"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)-1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data["total"]}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return # ---------- 📁 [ | 𝗚𝗘𝗧 𝗙𝗜𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data.startswith("lucifermoringstar_robot"): ident, file_id = query.data.split("#") files_ = await get_file_details(file_id) if not files_: return await query.answer('No such file exist.') files = files_[0] title = files.file_name size=get_size(files.file_size) f_caption=files.caption if CUSTOM_FILE_CAPTION: try: f_caption=CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name=title, file_size=size, file_caption=f_caption) except Exception as e: print(e) f_caption=f_caption if f_caption is None: f_caption = LuciferMoringstar.FILE_CAPTIONS.format(mention=query.from_user.mention, title=title, size=size) try: if FORCES_SUB and not await is_subscribed(client, query): await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") return else: await client.send_cached_media( chat_id=query.from_user.id, file_id=file_id, caption=f_caption ) await query.answer('🤖 Check PM, I have Sent Files In Pm 🤖',show_alert = True) except UserIsBlocked: await query.answer('Unblock the bot mahn !',show_alert = True) except PeerIdInvalid: await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") except Exception as e: await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") # ---------- 📁 [ | 𝗣𝗠 𝗙𝗜𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data.startswith("pmfile"): if FORCES_SUB and not await is_subscribed(client, query): await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒",show_alert=True) return ident, file_id = query.data.split("#") filedetails = await get_file_details(file_id) for files in filedetails: title = files.file_name size=get_size(files.file_size) f_caption=files.caption if CUSTOM_FILE_CAPTION: try: f_caption=CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, title=title, file_size=size, file_caption=f_caption) except Exception as e: print(e) f_caption=f_caption if f_caption is None: f_caption = LuciferMoringstar.FILE_CAPTIONS buttons = [[ InlineKeyboardButton('🧑‍💻 Main Channel 🧑‍💻', url='https://t.me/Moviemadh') ]] await query.answer() await client.send_cached_media( chat_id=query.from_user.id, file_id=file_id, caption=f_caption, reply_markup=InlineKeyboardMarkup(buttons) ) # ---------- 📁 [ | 𝗠𝗢𝗗𝗨𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data == "start": if query.from_user.id not in ADMINS: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="help"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("Main Channel", url="https://t.me/Moviemadh"), InlineKeyboardButton("Request Here", url="https://t.me/MM_Request1") ]] else: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="bot_owner"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("Main Channel", url="https://t.me/Moviemadh"), InlineKeyboardButton("Request Here", url="https://t.me/MM_Request1") ]] await query.message.edit(text=START_MSG.format(mention=query.from_user.mention, bot_name=bot_info.BOT_NAME, bot_username=bot_info.BOT_USERNAME), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "help": buttons = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("About 😎", callback_data="about") ]] await query.message.edit(text=LuciferMoringstar.HELP_MSG.format(mention=query.from_user.mention), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "about": buttons = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("Close 🗑️", callback_data="close") ]] await query.message.edit(text=LuciferMoringstar.ABOUT_MSG.format(mention=query.from_user.mention, bot_name=bot_info.BOT_NAME, bot_username=bot_info.BOT_USERNAME, dev_name=DEV_NAME), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "bot_owner": buttons = [[ InlineKeyboardButton('🏠 Home', callback_data="start"), InlineKeyboardButton('About 😎', callback_data="about") ]] await query.message.edit(text=LuciferMoringstar.PR0FESS0R_99.format(mention=query.from_user.mention), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "pages": await query.answer() else: await query.answer("Please Request",show_alert=True)
from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton from pyrogram.errors import UserIsBlocked, PeerIdInvalid from LuciferMoringstar_Robot.database.autofilter_db import is_subscribed, get_file_details from LuciferMoringstar_Robot.database._utils import get_size from translation import LuciferMoringstar from config import BUTTONS, FORCES_SUB, CUSTOM_FILE_CAPTION, START_MSG, DEV_NAME, bot_info, ADMINS @LuciferMoringstar_Robot.on_callback_query() async def cb_handler(client: LuciferMoringstar_Robot, query): clicked = query.from_user.id try: typed = query.message.reply_to_message.from_user.id except: typed = query.from_user.id if (clicked == typed): # # ---------- 🔘 [ | 𝗚𝗥𝗢𝗨𝗣 𝗙𝗜𝗟𝗧𝗘𝗥𝗦 | ] 🔘 ---------- # # if query.data.startswith("nextgroup"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)+1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("backgroup"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backgroup_{int(index)-1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextgroup_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) buttons.append( [InlineKeyboardButton(text="🤖 CHECK MY PM 🤖", url=f"https://telegram.dog/{bot_info.BOT_USERNAME}")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return # # ---------- 🔘 [ | 𝗕𝗢𝗧 𝗣𝗠 𝗙𝗜𝗟𝗧𝗘𝗥𝗦 | ] 🔘 ---------- # # elif query.data.startswith("nextbot"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == int(data["total"]) - 2: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)+1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)+1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)+1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)+2}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return elif query.data.startswith("backbot"): ident, index, keyword = query.data.split("_") try: data = BUTTONS[keyword] except KeyError: await query.answer("This Is My Old Message So Please Request Again 🙏",show_alert=True) return if int(index) == 1: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return else: buttons = data['buttons'][int(index)-1].copy() buttons.append( [InlineKeyboardButton("🔙 Back Page", callback_data=f"backbot_{int(index)-1}_{keyword}"),InlineKeyboardButton("Next Page ➡", callback_data=f"nextbot_{int(index)-1}_{keyword}")] ) buttons.append( [InlineKeyboardButton(f"📃 Pages {int(index)}/{data['total']}", callback_data="pages"), InlineKeyboardButton("Close 🗑️", callback_data="close")] ) await query.edit_message_reply_markup( reply_markup=InlineKeyboardMarkup(buttons) ) return # ---------- 📁 [ | 𝗚𝗘𝗧 𝗙𝗜𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data.startswith("lucifermoringstar_robot"): ident, file_id = query.data.split("#") files_ = await get_file_details(file_id) if not files_: return await query.answer('No such file exist.') files = files_[0] title = files.file_name size=get_size(files.file_size) f_caption=files.caption if CUSTOM_FILE_CAPTION: try: f_caption=CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, file_name=title, file_size=size, file_caption=f_caption) except Exception as e: print(e) f_caption=f_caption if f_caption is None: f_caption = LuciferMoringstar.FILE_CAPTIONS.format(mention=query.from_user.mention, title=title, size=size) try: if FORCES_SUB and not await is_subscribed(client, query): await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") return else: await client.send_cached_media( chat_id=query.from_user.id, file_id=file_id, caption=f_caption ) await query.answer('🤖 Check PM, I have Sent Files In Pm 🤖',show_alert = True) except UserIsBlocked: await query.answer('Unblock the bot mahn !',show_alert = True) except PeerIdInvalid: await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") except Exception as e: await query.answer(url=f"https://t.me/{bot_info.BOT_USERNAME}?start=subscribe") # ---------- 📁 [ | 𝗣𝗠 𝗙𝗜𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data.startswith("pmfile"): if FORCES_SUB and not await is_subscribed(client, query): await query.answer("I Like Your Smartness, But Don't Be Oversmart 😒",show_alert=True) return ident, file_id = query.data.split("#") filedetails = await get_file_details(file_id) for files in filedetails: title = files.file_name size=get_size(files.file_size) f_caption=files.caption if CUSTOM_FILE_CAPTION: try: f_caption=CUSTOM_FILE_CAPTION.format(mention=query.from_user.mention, title=title, file_size=size, file_caption=f_caption) except Exception as e: print(e) f_caption=f_caption if f_caption is None: f_caption = LuciferMoringstar.FILE_CAPTIONS buttons = [[ InlineKeyboardButton('🧑‍💻 Main Channel 🧑‍💻', url='https://t.me/Moviemadh') ]] await query.answer() await client.send_cached_media( chat_id=query.from_user.id, file_id=file_id, caption=f_caption, reply_markup=InlineKeyboardMarkup(buttons) ) # ---------- 📁 [ | 𝗠𝗢𝗗𝗨𝗟𝗘𝗦 | ] 📁 ---------- # elif query.data == "start": if query.from_user.id not in ADMINS: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="help"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("Main Channel", url="https://t.me/Moviemadh"), InlineKeyboardButton("Request Here", url="https://t.me/MM_Request1") ]] else: buttons = [[ InlineKeyboardButton("➕️ Add me to Your Chat ➕️", url=f"http://t.me/{bot_info.BOT_USERNAME}?startgroup=true") ],[ InlineKeyboardButton("ℹ️ Help", callback_data="bot_owner"), InlineKeyboardButton("😎 About", callback_data="about") ],[ InlineKeyboardButton("Main Channel", url="https://t.me/Moviemadh"), InlineKeyboardButton("Request Here", url="https://t.me/MM_Request1") ]] await query.message.edit(text=START_MSG.format(mention=query.from_user.mention, bot_name=bot_info.BOT_NAME, bot_username=bot_info.BOT_USERNAME), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "help": buttons = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("About 😎", callback_data="about") ]] await query.message.edit(text=LuciferMoringstar.HELP_MSG.format(mention=query.from_user.mention), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "about": buttons = [[ InlineKeyboardButton("🏠 Home", callback_data="start"), InlineKeyboardButton("Close 🗑️", callback_data="close") ]] await query.message.edit(text=LuciferMoringstar.ABOUT_MSG.format(mention=query.from_user.mention, bot_name=bot_info.BOT_NAME, bot_username=bot_info.BOT_USERNAME, dev_name=DEV_NAME), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "bot_owner": buttons = [[ InlineKeyboardButton('🏠 Home', callback_data="start"), InlineKeyboardButton('About 😎', callback_data="about") ]] await query.message.edit(text=LuciferMoringstar.PR0FESS0R_99.format(mention=query.from_user.mention), reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=True) elif query.data == "pages": await query.answer() else: await query.answer("Please Request",show_alert=True)
import speech_recognition as sr from pydub import AudioSegment import os from datetime import date import sounddevice as sd from scipy.io.wavfile import write from random import choice, randint import pyttsx3 import time import webbrowser from playsound import playsound # Commands hello = ["hi", "Hi", "hello", "Hello", "wsg", "Wsg", "WSG", "sup", "Sup", "hey", "Hey", "hi!", "Hi!", "hello!", "Hello!", "wsg!", "Wsg!", "WSG!", "sup!", "Sup!", "hey!", "Hey!", "hi :)", "Hi :)", "hello :)", "Hello :)", "wsg :)", "Wsg :)", "WSG :)", "sup :)", "Sup :)", "hey :)", "Hey :)", "hi! :)", "Hi! :)", "hello! :)", "Hello! :)", "wsg! :)", "Wsg! :)", "WSG! :)", "sup! :)", "Sup! :)", "hey! :)", "Hey! :)", "Ello", "ello", "'Ello", "'ello"] bye = ["bye", "Bye", "goodbye", "Goodbye", "good bye", "Good Bye", "see you", "See you", "later", "Later", "byee", "Byee", "byeee", "Byeee"] insult = ["fucktard", "idot", "idiot", "dumbass", "motherfucker", "stupid", "gay", "fucker", "Fucktard", "Idot", "Idiot", "Dumbass", "Motherfucker", "Stupid", "Gay", "Fucker" "ur fat", "Ur fat", "your fat", "Your fat", "youre fat", "youre fat", "faggot", "retard", "bitch", "whore", "thot", "fat", "fatty", "ur gay", "Ur gay", "your gay", "youre gay", "Youre gay", "Fag", "fag", "Loser", "loser"] compliment = ["gg", "good job", "nice", "great", "awesome", "good", "your hot", "ur hot", "youre hot", "youre awesome", "youre cool", "Nice"] hi = ["Sup", "Hello", "Hi", "good morning", "Good morning", "Good afternoon", "good afternoon", "good evening", "Good evening"] hi2 = ["Sup", "Hello", "Hi"] gn = ["Good night", "good night"] yes = ["yes", "Sure!", "sure", "of course", "yeah"] no = ["yeah no", "no", "heck no"] thankYou = ["thank you", "Thank you", "Thanks", "thanks", "Thank you", "thank you", "thx!", "Thx!", "Ty!", "ty!", "Thanks!", "thanks!", "Thank u", "thank u"] startTimer = ["Can you start a timer", "Can you start a timer?", "can you start a timer", "can you start a timer?", "please start a timer", "Please start a timer", "timer start", "Timer start", "start timer", "Start timer", "can you please start a timer?", "can you start a timer please", "Can you start a timer please", "can you start a timer please?", "Can you start a timer please?"] endTimer = ["End the timer please", "end the timer please", "please end the timer", "Please end the timer", "timer end", "Timer end", "End timer", "end timer", "Stop the timer please", "stop the timer please", "please stop the timer", "Please stop the timer", "timer stop", "Timer stop", "Stop timer", "stop timer"] howMany = ["How many", "how many", "how many?", "How many?"] canIJoin = ["can i join", "Can i join", "Can i join?", "can i join?", "can I join", "Can I join", "Can I join?", "can I join?"] howAreYou = ["How are you", "how are you", "How are you?", "how are you?", "How are you doing", "how are you doing", "how are you doing?", "How are you doing?", "How are u", "how are u", "How are u?", "how are u?"] howImDoing = ["Ok so far", "Pretty good", "Good", "Great"] wyd = ["What are you doing", "what are you doing", "Wyd", "wyd", "WYD", "What are you doing?", "what are you doing?", "Wyd?", "wyd?", "WYD?"] wid = ["Smoking crack", "Coding", "Talking to people", "Nothing right now", "Playing piano", "Invading poland", "Making tacos"] invpoland = ["wanna go invade poland", "Wanna go invade poland", "Wanna go invade poland?", "wanna go invade poland?", "want to go invade poland"] ily = ["i love you", "I love you", "ily", "Ily", "ILY", "i <3 you", "I <3 you", "i <3 u", "i love u", "I love u"] isFren = ["Are you a friend", "are you a friend", "Are you a friend?", "are you a friend?", "Are you fren", "are you fren", "Are you a fren?", "are you a fren?", "Are you a fren", "are you a fren", "Are you a fren?", "are you a fren?", "Are you fren?", "are you fren?", "are you fren", "Are you fren"] whatCanYouDo = ["What can you do", "what can you do", "what can you do?", "What can you do?", "What do you do?", "what do you do?", "cmd use", "Cmd use", "!use"] theDate = ["What is the date", "what is the date", "what is today", "What is today", "can you please tell me the date", "Can you please tell me the date", "what is the date today", "What is the date today", "What is the date?", "what is the date?", "what is today?", "What is today?", "can you please tell me the date?", "Can you please tell me the date?", "what is the date today?", "What is the date today?"] enable_speech = ["enable speech", "speech enable", "speech on"] disable_speech = ["disable speech", "speech disable", "speech off"] enable_man = ["enable manual", "manual enable", "manual on"] disable_man = ["disable manual", "manual disable", "manual off"] openSite = ["Open site", "open site", "website", "site", "site open"] engine = pyttsx3.init() fs = 44100 seconds = 3 strtTime = 0 endtime = 0 manual = False speech = True bot_name = ['ivan', 'hey ivan', 'boot ivan', 'help ivan', 'Yo ivan wake up'] toSay = '' count = 0 window = Tk() try: os.remove('output.wav', 'transcript.wav') except: pass print("Started!") def main(): global count while count < 3: myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) # Save as WAV file sound = AudioSegment.from_wav('output.wav') sound.export('transcript.wav', format="wav") AUDIO_FILE = "transcript.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: global speech global manual global strtTime global endtime global toSay audio = r.record(source) try: transcribed = r.recognize_google(audio) except: transcribed = "Sorry, i did not understand" engine.say(transcribed) engine.runAndWait() if manual == True: transcribed = input("Manual Command> ") try: print("Transcription: " + transcribed) text = transcribed.lower() if text in theDate: toSay = (date.today()) elif text in openSite: engine.say("What site do you want to open?") engine.runAndWait() myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) # Save as WAV file AUDIO_FILE = "output.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) speech = True try: transcribed = r.recognize_google(audio) except: transcribed = "I couldn't understand what you said" engine.say(transcribed) engine.runAndWait() print(transcribed) engine.say("Opening site.") engine.runAndWait() if transcribed != "I couldn't understand what you said": url = f'https://www.{transcribed}.org' webbrowser.open(url) if transcribed.lower() != 'python': url = f'https://www.{transcribed}.com' webbrowser.open(url) elif text in compliment: toSay = choice(thankYou) elif text in whatCanYouDo: toSay = f"I am {bot_name}. I can answer questions and run commands as you wish! Just remember i was made by a thirteen year old and a twelve year old" elif text in isFren: toSay = "Of course, im always here to help" elif text in canIJoin: toSay = 'Sure' elif text in insult: toSay = "You do know i don't get offended, right?" elif text in enable_man: manual = True elif text in disable_man: manual = False elif text in ily: playsound('yugay.wav') elif text in wyd: toSay = choice(wid) elif text in thankYou: toSay = "You're welcome" elif text in howMany: toSay = str(randint(1, 50)) elif text in howAreYou: toSay = choice(howImDoing) elif text in invpoland: toSay = "Sure" elif text in hi: toSay = choice(hi2) elif text in hello: toSay = choice(hi2) elif text in bye: toSay = choice(bye) elif text in startTimer: strtTime == time.time() toSay = 'Ok' elif text in endTimer: endtime == time.time() toSay = (f'Ok, Time is {str(endtime - strtTime)}') elif text in enable_speech: global speech speech = True toSay = "Ok" elif text in disable_speech: global speech speech = False toSay = "Ok" elif text == 'what is the time': t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time) else: toSay = "Unknown command" print(toSay) if speech == True: engine.say(toSay) engine.runAndWait() else: count += 1 pass input("") except: pass # input("Continue? ") count = 0 while True: myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) sound = AudioSegment.from_wav("output.wav") sound.export("transcript.wav", format="wav") AUDIO_FILE = "transcript.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) speech = True try: transcribed = r.recognize_google(audio) except: pass try: if transcribed.lower() in bot_name and transcribed: print("Voice Acivated") engine.say(f"Hello {os.getenv("USERNAME")}, how may i help") engine.runAndWait() main() except: pass
import speech_recognition as sr from pydub import AudioSegment import os from datetime import date import sounddevice as sd from scipy.io.wavfile import write from random import choice, randint import pyttsx3 import time import webbrowser from playsound import playsound # Commands hello = ["hi", "Hi", "hello", "Hello", "wsg", "Wsg", "WSG", "sup", "Sup", "hey", "Hey", "hi!", "Hi!", "hello!", "Hello!", "wsg!", "Wsg!", "WSG!", "sup!", "Sup!", "hey!", "Hey!", "hi :)", "Hi :)", "hello :)", "Hello :)", "wsg :)", "Wsg :)", "WSG :)", "sup :)", "Sup :)", "hey :)", "Hey :)", "hi! :)", "Hi! :)", "hello! :)", "Hello! :)", "wsg! :)", "Wsg! :)", "WSG! :)", "sup! :)", "Sup! :)", "hey! :)", "Hey! :)", "Ello", "ello", "'Ello", "'ello"] bye = ["bye", "Bye", "goodbye", "Goodbye", "good bye", "Good Bye", "see you", "See you", "later", "Later", "byee", "Byee", "byeee", "Byeee"] insult = ["fucktard", "idot", "idiot", "dumbass", "motherfucker", "stupid", "gay", "fucker", "Fucktard", "Idot", "Idiot", "Dumbass", "Motherfucker", "Stupid", "Gay", "Fucker" "ur fat", "Ur fat", "your fat", "Your fat", "youre fat", "youre fat", "faggot", "retard", "bitch", "whore", "thot", "fat", "fatty", "ur gay", "Ur gay", "your gay", "youre gay", "Youre gay", "Fag", "fag", "Loser", "loser"] compliment = ["gg", "good job", "nice", "great", "awesome", "good", "your hot", "ur hot", "youre hot", "youre awesome", "youre cool", "Nice"] hi = ["Sup", "Hello", "Hi", "good morning", "Good morning", "Good afternoon", "good afternoon", "good evening", "Good evening"] hi2 = ["Sup", "Hello", "Hi"] gn = ["Good night", "good night"] yes = ["yes", "Sure!", "sure", "of course", "yeah"] no = ["yeah no", "no", "heck no"] thankYou = ["thank you", "Thank you", "Thanks", "thanks", "Thank you", "thank you", "thx!", "Thx!", "Ty!", "ty!", "Thanks!", "thanks!", "Thank u", "thank u"] startTimer = ["Can you start a timer", "Can you start a timer?", "can you start a timer", "can you start a timer?", "please start a timer", "Please start a timer", "timer start", "Timer start", "start timer", "Start timer", "can you please start a timer?", "can you start a timer please", "Can you start a timer please", "can you start a timer please?", "Can you start a timer please?"] endTimer = ["End the timer please", "end the timer please", "please end the timer", "Please end the timer", "timer end", "Timer end", "End timer", "end timer", "Stop the timer please", "stop the timer please", "please stop the timer", "Please stop the timer", "timer stop", "Timer stop", "Stop timer", "stop timer"] howMany = ["How many", "how many", "how many?", "How many?"] canIJoin = ["can i join", "Can i join", "Can i join?", "can i join?", "can I join", "Can I join", "Can I join?", "can I join?"] howAreYou = ["How are you", "how are you", "How are you?", "how are you?", "How are you doing", "how are you doing", "how are you doing?", "How are you doing?", "How are u", "how are u", "How are u?", "how are u?"] howImDoing = ["Ok so far", "Pretty good", "Good", "Great"] wyd = ["What are you doing", "what are you doing", "Wyd", "wyd", "WYD", "What are you doing?", "what are you doing?", "Wyd?", "wyd?", "WYD?"] wid = ["Smoking crack", "Coding", "Talking to people", "Nothing right now", "Playing piano", "Invading poland", "Making tacos"] invpoland = ["wanna go invade poland", "Wanna go invade poland", "Wanna go invade poland?", "wanna go invade poland?", "want to go invade poland"] ily = ["i love you", "I love you", "ily", "Ily", "ILY", "i <3 you", "I <3 you", "i <3 u", "i love u", "I love u"] isFren = ["Are you a friend", "are you a friend", "Are you a friend?", "are you a friend?", "Are you fren", "are you fren", "Are you a fren?", "are you a fren?", "Are you a fren", "are you a fren", "Are you a fren?", "are you a fren?", "Are you fren?", "are you fren?", "are you fren", "Are you fren"] whatCanYouDo = ["What can you do", "what can you do", "what can you do?", "What can you do?", "What do you do?", "what do you do?", "cmd use", "Cmd use", "!use"] theDate = ["What is the date", "what is the date", "what is today", "What is today", "can you please tell me the date", "Can you please tell me the date", "what is the date today", "What is the date today", "What is the date?", "what is the date?", "what is today?", "What is today?", "can you please tell me the date?", "Can you please tell me the date?", "what is the date today?", "What is the date today?"] enable_speech = ["enable speech", "speech enable", "speech on"] disable_speech = ["disable speech", "speech disable", "speech off"] enable_man = ["enable manual", "manual enable", "manual on"] disable_man = ["disable manual", "manual disable", "manual off"] openSite = ["Open site", "open site", "website", "site", "site open"] engine = pyttsx3.init() fs = 44100 seconds = 3 strtTime = 0 endtime = 0 manual = False speech = True bot_name = ['ivan', 'hey ivan', 'boot ivan', 'help ivan', 'Yo ivan wake up'] toSay = '' count = 0 window = Tk() try: os.remove('output.wav', 'transcript.wav') except: pass print("Started!") def main(): global count while count < 3: myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) # Save as WAV file sound = AudioSegment.from_wav('output.wav') sound.export('transcript.wav', format="wav") AUDIO_FILE = "transcript.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: global speech global manual global strtTime global endtime global toSay audio = r.record(source) try: transcribed = r.recognize_google(audio) except: transcribed = "Sorry, i did not understand" engine.say(transcribed) engine.runAndWait() if manual == True: transcribed = input("Manual Command> ") try: print("Transcription: " + transcribed) text = transcribed.lower() if text in theDate: toSay = (date.today()) elif text in openSite: engine.say("What site do you want to open?") engine.runAndWait() myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) # Save as WAV file AUDIO_FILE = "output.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) speech = True try: transcribed = r.recognize_google(audio) except: transcribed = "I couldn't understand what you said" engine.say(transcribed) engine.runAndWait() print(transcribed) engine.say("Opening site.") engine.runAndWait() if transcribed != "I couldn't understand what you said": url = f'https://www.{transcribed}.org' webbrowser.open(url) if transcribed.lower() != 'python': url = f'https://www.{transcribed}.com' webbrowser.open(url) elif text in compliment: toSay = choice(thankYou) elif text in whatCanYouDo: toSay = f"I am {bot_name}. I can answer questions and run commands as you wish! Just remember i was made by a thirteen year old and a twelve year old" elif text in isFren: toSay = "Of course, im always here to help" elif text in canIJoin: toSay = 'Sure' elif text in insult: toSay = "You do know i don't get offended, right?" elif text in enable_man: manual = True elif text in disable_man: manual = False elif text in ily: playsound('yugay.wav') elif text in wyd: toSay = choice(wid) elif text in thankYou: toSay = "You're welcome" elif text in howMany: toSay = str(randint(1, 50)) elif text in howAreYou: toSay = choice(howImDoing) elif text in invpoland: toSay = "Sure" elif text in hi: toSay = choice(hi2) elif text in hello: toSay = choice(hi2) elif text in bye: toSay = choice(bye) elif text in startTimer: strtTime == time.time() toSay = 'Ok' elif text in endTimer: endtime == time.time() toSay = (f'Ok, Time is {str(endtime - strtTime)}') elif text in enable_speech: global speech speech = True toSay = "Ok" elif text in disable_speech: global speech speech = False toSay = "Ok" elif text == 'what is the time': t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time) else: toSay = "Unknown command" print(toSay) if speech == True: engine.say(toSay) engine.runAndWait() else: count += 1 pass input("") except: pass # input("Continue? ") count = 0 while True: myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2) sd.wait() write('output.wav', fs, myrecording) sound = AudioSegment.from_wav("output.wav") sound.export("transcript.wav", format="wav") AUDIO_FILE = "transcript.wav" r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) speech = True try: transcribed = r.recognize_google(audio) except: pass try: if transcribed.lower() in bot_name and transcribed: print("Voice Acivated") engine.say(f"Hello {os.getenv('USERNAME')}, how may i help") engine.runAndWait() main() except: pass
#! /usr/bin/env python3 """ Bishbot - https://github.com/ldgregory/bishbot Leif Gregory <leif@devtek.org> space.py v0.1 Tested to Python v3.7.3 Description: Bot commands for the Space channel Changelog: 20200603 - Initial code Copyright 2020 Leif Gregory Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import json import requests from discord.ext import commands class Space(commands.Cog): def __init__(self, bot): self.bot = bot # Events @commands.Cog.listener() async def on_ready(self): print('- Space Cog loaded') @commands.command(name='launches', description='Show the next five launches', help='Show the next five launches', ignore_extra=True, hidden=False, enabled=True) async def launches(self, ctx): response = requests.get('https://fdo.rocketlaunch.live/json/launches/next/5') data = json.loads(response.text) launches = '**Here are the next five launches**\n\n' for result in data['result']: launches += f"- {result["quicktext"]}\n" await ctx.channel.send(launches) def setup(bot): bot.add_cog(Space(bot))
#! /usr/bin/env python3 """ Bishbot - https://github.com/ldgregory/bishbot Leif Gregory <leif@devtek.org> space.py v0.1 Tested to Python v3.7.3 Description: Bot commands for the Space channel Changelog: 20200603 - Initial code Copyright 2020 Leif Gregory Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import json import requests from discord.ext import commands class Space(commands.Cog): def __init__(self, bot): self.bot = bot # Events @commands.Cog.listener() async def on_ready(self): print('- Space Cog loaded') @commands.command(name='launches', description='Show the next five launches', help='Show the next five launches', ignore_extra=True, hidden=False, enabled=True) async def launches(self, ctx): response = requests.get('https://fdo.rocketlaunch.live/json/launches/next/5') data = json.loads(response.text) launches = '**Here are the next five launches**\n\n' for result in data['result']: launches += f"- {result['quicktext']}\n" await ctx.channel.send(launches) def setup(bot): bot.add_cog(Space(bot))
# Calcular o IMC de uma pessoa cores = { 'limpo':'\033[m', 'verde':'\033[32m', 'amarelo':'\033[33m', } linha = f'{cores['amarelo']}-=' * 26 + f'{cores['limpo']}' print(linha) print('Vamos calcular seu IMC!') print(linha) peso_kg = str(input('Preciso saber seu peso, em Quilogramas: ')).strip() alt_metros = str(input('Agora, preciso saber sua altura, em metros: ')).strip() print(linha) peso_kg = float(peso_kg.split()[0]) alt_metros = float(alt_metros.split()[0]) imc_pessoa = peso_kg / (alt_metros ** 2) if imc_pessoa >= 0 and imc_pessoa < 18.5: imc_class = 'Peso Baixo' elif imc_pessoa >= 18.5 and imc_pessoa <= 24.9: imc_class = 'Peso Normal' elif imc_pessoa >= 25 and imc_pessoa <= 29.9: imc_class = 'Sobre Peso' elif imc_pessoa >= 30 and imc_pessoa <= 34.9: imc_class = 'Obesidade (Grau I)' elif imc_pessoa >= 35 and imc_pessoa <= 39.9: imc_class = 'Obesidade Severa (Grau II)' else: imc_class = 'Obesidade Mórbida (Grau III)' print(f'Seu {cores['verde']}IMC é {imc_pessoa:.2f}{cores['limpo']} e sua {cores['verde']}classificação é {imc_class}{cores['limpo']}') print(linha)
# Calcular o IMC de uma pessoa cores = { 'limpo':'\033[m', 'verde':'\033[32m', 'amarelo':'\033[33m', } linha = f'{cores["amarelo"]}-=' * 26 + f'{cores["limpo"]}' print(linha) print('Vamos calcular seu IMC!') print(linha) peso_kg = str(input('Preciso saber seu peso, em Quilogramas: ')).strip() alt_metros = str(input('Agora, preciso saber sua altura, em metros: ')).strip() print(linha) peso_kg = float(peso_kg.split()[0]) alt_metros = float(alt_metros.split()[0]) imc_pessoa = peso_kg / (alt_metros ** 2) if imc_pessoa >= 0 and imc_pessoa < 18.5: imc_class = 'Peso Baixo' elif imc_pessoa >= 18.5 and imc_pessoa <= 24.9: imc_class = 'Peso Normal' elif imc_pessoa >= 25 and imc_pessoa <= 29.9: imc_class = 'Sobre Peso' elif imc_pessoa >= 30 and imc_pessoa <= 34.9: imc_class = 'Obesidade (Grau I)' elif imc_pessoa >= 35 and imc_pessoa <= 39.9: imc_class = 'Obesidade Severa (Grau II)' else: imc_class = 'Obesidade Mórbida (Grau III)' print(f'Seu {cores["verde"]}IMC é {imc_pessoa:.2f}{cores["limpo"]} e sua {cores["verde"]}classificação é {imc_class}{cores["limpo"]}') print(linha)
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ from utils.GlobalVars import * from recbole.config import Config, EvalSetting from recbole.sampler import Sampler, RepeatableSampler, KGSampler from recbole.utils import ModelType, init_logger, get_model, get_trainer, init_seed, InputType from recbole.utils.utils import set_color from recbole.data.utils import get_data_loader from recbole.data import save_split_dataloaders from RobustnessGymDataset import RobustnessGymDataset from logging import getLogger, shutdown import importlib import pprint as pprint import pickle def create_dataset(config): """ Initializes RobustnessGymDataset for each recommendation system type in RecBole. Args: config (Config): Config file indicating MODEL_TYPE and model. Returns: RobustnessGymDataset instance. """ dataset_module = importlib.import_module('recbole.data.dataset') if hasattr(dataset_module, config['model'] + 'Dataset'): return getattr(dataset_module, config['model'] + 'Dataset')(config) else: model_type = config['MODEL_TYPE'] if model_type == ModelType.SEQUENTIAL: from recbole.data.dataset import SequentialDataset SequentialDataset.__bases__ = (RobustnessGymDataset,) return SequentialDataset(config) elif model_type == ModelType.KNOWLEDGE: from recbole.data.dataset import KnowledgeBasedDataset KnowledgeBasedDataset.__bases__ = (RobustnessGymDataset,) return KnowledgeBasedDataset(config) elif model_type == ModelType.SOCIAL: from recbole.data.dataset import SocialDataset SocialDataset.__bases__ = (RobustnessGymDataset,) return SocialDataset(config) elif model_type == ModelType.DECISIONTREE: from recbole.data.dataset import DecisionTreeDataset DecisionTreeDataset.__bases__ = (RobustnessGymDataset,) return DecisionTreeDataset(config) else: return RobustnessGymDataset(config) def get_transformed_train(config, train_kwargs, train_dataloader, robustness_testing_datasets): """ Converts training data set created by transformations into dataloader object. Uses same config settings as original training data. Args: train_kwargs (dict): Training dataset config train_dataloader (Dataloader): Training dataloader config (Config): General config robustness_testing_datasets (dict): Modified datasets resulting from robustness tests Returns: transformed_train (Dataloader) """ transformed_train = None if "transformation_train" in robustness_testing_datasets: transformation_kwargs = { 'config': config, 'dataset': robustness_testing_datasets['transformation_train'], 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } try: transformation_kwargs['sampler'] = train_kwargs['sampler'] transformation_kwargs['neg_sample_args'] = train_kwargs['neg_sample_args'] transformed_train = train_dataloader(**transformation_kwargs) except: transformed_train = train_dataloader(**transformation_kwargs) return transformed_train def get_sparsity_train(config, train_kwargs, train_dataloader, robustness_testing_datasets): """ Converts training data set created by sparsity into dataloader object. Uses same config settings as original training data. Args: train_kwargs (dict): Training dataset config train_dataloader (Dataloader): Training dataloader config (Config): General config robustness_testing_datasets (dict): Modified datasets resulting from robustness tests Returns: sparsity_train (Dataloader) """ sparsity_train = None if "sparsity" in robustness_testing_datasets: sparsity_kwargs = { 'config': config, 'dataset': robustness_testing_datasets['sparsity'], 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } try: sparsity_kwargs['sampler'] = train_kwargs['sampler'] sparsity_kwargs['neg_sample_args'] = train_kwargs['neg_sample_args'] sparsity_train = train_dataloader(**sparsity_kwargs) except: sparsity_train = train_dataloader(**sparsity_kwargs) return sparsity_train def get_distributional_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ slice_test = None if 'distributional_slice' in robustness_testing_datasets: slice_kwargs = {'dataset': robustness_testing_datasets['distributional_slice']} if 'sampler' in test_kwargs: slice_kwargs['sampler'] = test_kwargs['sampler'] slice_kwargs.update(eval_kwargs) slice_test = test_dataloader(**slice_kwargs) return slice_test def get_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ slice_test = None if 'slice' in robustness_testing_datasets: slice_kwargs = {'dataset': robustness_testing_datasets['slice']} if 'sampler' in test_kwargs: slice_kwargs['sampler'] = test_kwargs['sampler'] slice_kwargs.update(eval_kwargs) slice_test = test_dataloader(**slice_kwargs) return slice_test def get_transformation_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ transformation_test = None if 'transformation' in robustness_testing_datasets: transformation_kwargs = {'dataset': robustness_testing_datasets['transformation']} if 'sampler' in test_kwargs: transformation_kwargs['sampler'] = test_kwargs['sampler'] transformation_kwargs.update(eval_kwargs) transformation_test = test_dataloader(**transformation_kwargs) return transformation_test def data_preparation(config, dataset, save=False): """ Builds datasets, including datasets built by applying robustness tests, configures train, validation, test sets, converts to tensors. Overloads RecBole data_preparation - we include the preparation of the robustness test train/test/valid sets here. Args: config (Config): dataset (RobustnessGymDataset): save (bool): Returns: """ model_type = config['MODEL_TYPE'] model = config['model'] es = EvalSetting(config) original_datasets, robustness_testing_datasets = dataset.build(es) train_dataset, valid_dataset, test_dataset = original_datasets phases = ['train', 'valid', 'test'] sampler = None logger = getLogger() train_neg_sample_args = config['train_neg_sample_args'] eval_neg_sample_args = es.neg_sample_args # Training train_kwargs = { 'config': config, 'dataset': train_dataset, 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } if train_neg_sample_args['strategy'] != 'none': if dataset.label_field in dataset.inter_feat: raise ValueError( f'`training_neg_sample_num` should be 0 ' f'if inter_feat have label_field [{dataset.label_field}].' ) if model_type != ModelType.SEQUENTIAL: sampler = Sampler(phases, original_datasets, train_neg_sample_args['distribution']) else: sampler = RepeatableSampler(phases, dataset, train_neg_sample_args['distribution']) if model not in ["MultiVAE", "MultiDAE", "MacridVAE", "CDAE", "ENMF", "RaCT", "RecVAE"]: train_kwargs['sampler'] = sampler.set_phase('train') train_kwargs['neg_sample_args'] = train_neg_sample_args if model_type == ModelType.KNOWLEDGE: kg_sampler = KGSampler(dataset, train_neg_sample_args['distribution']) train_kwargs['kg_sampler'] = kg_sampler dataloader = get_data_loader('train', config, train_neg_sample_args) logger.info( set_color('Build', 'pink') + set_color(f' [{dataloader.__name__}]', 'yellow') + ' for ' + set_color('[train]', 'yellow') + ' with format ' + set_color(f'[{train_kwargs['dl_format']}]', 'yellow') ) if train_neg_sample_args['strategy'] != 'none': logger.info( set_color('[train]', 'pink') + set_color(' Negative Sampling', 'blue') + f': {train_neg_sample_args}' ) else: logger.info(set_color('[train]', 'pink') + set_color(' No Negative Sampling', 'yellow')) logger.info( set_color('[train]', 'pink') + set_color(' batch_size', 'cyan') + ' = ' + set_color(f'[{train_kwargs['batch_size']}]', 'yellow') + ', ' + set_color('shuffle', 'cyan') + ' = ' + set_color(f'[{train_kwargs['shuffle']}]\n', 'yellow') ) train_data = dataloader(**train_kwargs) transformed_train = get_transformed_train(config, train_kwargs, dataloader, robustness_testing_datasets) sparsity_train = get_sparsity_train(config, train_kwargs, dataloader, robustness_testing_datasets) # Evaluation eval_kwargs = { 'config': config, 'batch_size': config['eval_batch_size'], 'dl_format': InputType.POINTWISE, 'shuffle': False, } valid_kwargs = {'dataset': valid_dataset} test_kwargs = {'dataset': test_dataset} if eval_neg_sample_args['strategy'] != 'none': if dataset.label_field in dataset.inter_feat: raise ValueError( f'It can not validate with `{es.es_str[1]}` ' f'when inter_feat have label_field [{dataset.label_field}].' ) if sampler is None: if model_type != ModelType.SEQUENTIAL: sampler = Sampler(phases, original_datasets, eval_neg_sample_args['distribution']) else: sampler = RepeatableSampler(phases, dataset, eval_neg_sample_args['distribution']) else: sampler.set_distribution(eval_neg_sample_args['distribution']) eval_kwargs['neg_sample_args'] = eval_neg_sample_args valid_kwargs['sampler'] = sampler.set_phase('valid') test_kwargs['sampler'] = sampler.set_phase('test') valid_kwargs.update(eval_kwargs) test_kwargs.update(eval_kwargs) dataloader = get_data_loader('evaluation', config, eval_neg_sample_args) logger.info( set_color('Build', 'pink') + set_color(f' [{dataloader.__name__}]', 'yellow') + ' for ' + set_color('[evaluation]', 'yellow') + ' with format ' + set_color(f'[{eval_kwargs['dl_format']}]', 'yellow') ) logger.info(es) logger.info( set_color('[evaluation]', 'pink') + set_color(' batch_size', 'cyan') + ' = ' + set_color(f'[{eval_kwargs['batch_size']}]', 'yellow') + ', ' + set_color('shuffle', 'cyan') + ' = ' + set_color(f'[{eval_kwargs['shuffle']}]\n', 'yellow') ) valid_data = dataloader(**valid_kwargs) test_data = dataloader(**test_kwargs) transformed_test = None if 'transformation_test' in robustness_testing_datasets: transformed_test_kwargs = test_kwargs transformed_test_kwargs['dataset'] = robustness_testing_datasets['transformation_test'] transformed_test = dataloader(**transformed_test_kwargs) slice_test = get_slice_test(eval_kwargs, test_kwargs, dataloader, robustness_testing_datasets) distributional_slice_test = get_distributional_slice_test(eval_kwargs, test_kwargs, dataloader, robustness_testing_datasets) if save: save_split_dataloaders(config, dataloaders=(train_data, valid_data, test_data)) robustness_testing_data = {'slice': slice_test, 'distributional_slice': distributional_slice_test, 'transformation_train': transformed_train, 'transformation_test': transformed_test, 'sparsity': sparsity_train} return train_data, valid_data, test_data, robustness_testing_data def get_config_dict(robustness_tests, base_config_dict): """ Combines robustness_test and train_config_dict into a single config_dict. Args: robustness_tests (dict): robustness test config dict base_config_dict (dict): train/data/eval/model/hyperparam config dict Returns: config_dict (dict): config dict """ config_dict = {} if robustness_tests is not None: if base_config_dict is not None: config_dict = {**robustness_tests, **base_config_dict} else: config_dict = robustness_tests else: if base_config_dict is not None: config_dict = base_config_dict return config_dict def train_and_test(model, dataset, robustness_tests=None, base_config_dict=None, save_model=True): """ Train a recommendation model and run robustness tests. Args: model (str): Name of model to be trained. dataset (str): Dataset name; must match the dataset's folder name located in 'data_path' path. base_config_dict: Configuration dictionary. If no config passed, takes default values. save_model (bool): Determines whether or not to externally save the model after training. robustness_tests (dict): Configuration dictionary for robustness tests. Returns: """ config_dict = get_config_dict(robustness_tests, base_config_dict) config = Config(model=model, dataset=dataset, config_dict=config_dict) init_seed(config['seed'], config['reproducibility']) logger = getLogger() if len(logger.handlers) != 0: logger.removeHandler(logger.handlers[1]) init_logger(config) logger.info(config) # dataset filtering dataset = create_dataset(config) logger.info(dataset) # dataset splitting train_data, valid_data, test_data, robustness_testing_data = data_preparation(config, dataset, save=True) for robustness_test in robustness_testing_data: if robustness_testing_data[robustness_test] is not None: logger.info(set_color('Robustness Test', 'yellow') + f': {robustness_test}') # model loading and initialization model = get_model(config['model'])(config, train_data).to(config['device']) logger.info(model) # trainer loading and initialization trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, model) # model training best_valid_score, best_valid_result = trainer.fit( train_data, valid_data, saved=save_model, show_progress=config['show_progress'] ) # model evaluation test_result = trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('best valid ', 'yellow') + f': {best_valid_result}') logger.info(set_color('test result', 'yellow') + f': {test_result}') test_result_transformation, test_result_sparsity, \ test_result_slice, test_result_distributional_slice = None, None, None, None if robustness_testing_data['slice'] is not None: test_result_slice = trainer.evaluate(robustness_testing_data['slice'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for slice', 'yellow') + f': {test_result_slice}') if robustness_testing_data['distributional_slice'] is not None: test_result_distributional_slice = trainer.evaluate(robustness_testing_data['distributional_slice'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for distributional slice', 'yellow') + f': ' f'{test_result_distributional_slice}') if robustness_testing_data['transformation_test'] is not None: test_result_transformation = trainer.evaluate(robustness_testing_data['transformation_test'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for transformation on test', 'yellow') + f': {test_result_transformation}') if robustness_testing_data['transformation_train'] is not None: transformation_model = get_model(config['model'])(config, robustness_testing_data['transformation_train']).to( config['device']) logger.info(transformation_model) transformation_trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, transformation_model) best_valid_score_transformation, best_valid_result_transformation = transformation_trainer.fit( robustness_testing_data['transformation_train'], valid_data, saved=save_model, show_progress=config['show_progress']) test_result_transformation = transformation_trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info( set_color('best valid for transformed training set', 'yellow') + f': {best_valid_result_transformation}') logger.info(set_color('test result for transformed training set', 'yellow') + f': {test_result_transformation}') if robustness_testing_data['sparsity'] is not None: sparsity_model = get_model(config['model'])(config, robustness_testing_data['sparsity']).to(config['device']) logger.info(sparsity_model) sparsity_trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, sparsity_model) best_valid_score_sparsity, best_valid_result_sparsity = sparsity_trainer.fit( robustness_testing_data['sparsity'], valid_data, saved=save_model, show_progress=config['show_progress']) test_result_sparsity = sparsity_trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('best valid for sparsified training set', 'yellow') + f': {best_valid_result_sparsity}') logger.info(set_color('test result for sparsified training set', 'yellow') + f': {test_result_sparsity}') logger.handlers.clear() shutdown() del logger return { 'test_result': test_result, 'distributional_test_result': test_result_distributional_slice, 'transformation_test_result': test_result_transformation, 'sparsity_test_result': test_result_sparsity, 'slice_test_result': test_result_slice } def test(model, dataset, model_path, dataloader_path=None, robustness_tests=None, base_config_dict=None): """ Test a pre-trained model from file path. Note that the only robustness test applicable here is slicing. Args: model (str): Name of model. dataset (str): Name of dataset. model_path (str): Path to saved model. robustness_tests (dict): Configuration dictionary for robustness tests. base_config_dict (dict): Configuration dictionary for data/model/training/evaluation. Returns: """ config_dict = get_config_dict(robustness_tests, base_config_dict) config = Config(model=model, dataset=dataset, config_dict=config_dict) init_seed(config['seed'], config['reproducibility']) # logger initialization logger = getLogger() if len(logger.handlers) != 0: logger.removeHandler(logger.handlers[1]) init_logger(config) # dataset filtering dataset = create_dataset(config) logger.info(dataset) # dataset splitting if dataloader_path is None: train_data, _, test_data, robustness_testing_data = data_preparation(config, dataset, save=False) else: train_data, valid_data, test_data = pickle.load(open(SAVED_DIR + dataloader_path, "rb")) robustness_testing_data = {"slice": None, "transformation": None, "sparsity": None} # model loading and initialization model = get_model(config['model'])(config, train_data).to(config['device']) logger.info(model) # trainer loading and initialization trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, model) # model evaluation test_result = trainer.evaluate(test_data, load_best_model=True, model_file=model_path, show_progress=config['show_progress']) logger.info(set_color('test result', 'yellow') + f': {test_result}') test_result_slice = None if robustness_testing_data['slice'] is not None: test_result_slice = trainer.evaluate(robustness_testing_data['slice'], load_best_model=True, model_file=model_path, show_progress=config['show_progress']) logger.info(set_color('test result for slice', 'yellow') + f': {test_result_slice}') return { 'test_result': test_result, 'slice_test_result': test_result_slice } if __name__ == '__main__': all_results = {} for model in ["BPR"]: dataset = "ml-100k" base_config_dict = { 'data_path': DATASETS_DIR, 'show_progress': False, 'save_dataset': True, 'load_col': {'inter': ['user_id', 'item_id', 'rating', 'timestamp'], 'user': ['user_id', 'age', 'gender', 'occupation'], 'item': ['item_id', 'release_year', 'class']} } # robustness_dict = { # uncomment and add robustness test specifications here # } results = train_and_test(model=model, dataset=dataset, robustness_tests=robustness_dict, base_config_dict=base_config_dict)
""" /* * Copyright (c) 2021, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ """ from utils.GlobalVars import * from recbole.config import Config, EvalSetting from recbole.sampler import Sampler, RepeatableSampler, KGSampler from recbole.utils import ModelType, init_logger, get_model, get_trainer, init_seed, InputType from recbole.utils.utils import set_color from recbole.data.utils import get_data_loader from recbole.data import save_split_dataloaders from RobustnessGymDataset import RobustnessGymDataset from logging import getLogger, shutdown import importlib import pprint as pprint import pickle def create_dataset(config): """ Initializes RobustnessGymDataset for each recommendation system type in RecBole. Args: config (Config): Config file indicating MODEL_TYPE and model. Returns: RobustnessGymDataset instance. """ dataset_module = importlib.import_module('recbole.data.dataset') if hasattr(dataset_module, config['model'] + 'Dataset'): return getattr(dataset_module, config['model'] + 'Dataset')(config) else: model_type = config['MODEL_TYPE'] if model_type == ModelType.SEQUENTIAL: from recbole.data.dataset import SequentialDataset SequentialDataset.__bases__ = (RobustnessGymDataset,) return SequentialDataset(config) elif model_type == ModelType.KNOWLEDGE: from recbole.data.dataset import KnowledgeBasedDataset KnowledgeBasedDataset.__bases__ = (RobustnessGymDataset,) return KnowledgeBasedDataset(config) elif model_type == ModelType.SOCIAL: from recbole.data.dataset import SocialDataset SocialDataset.__bases__ = (RobustnessGymDataset,) return SocialDataset(config) elif model_type == ModelType.DECISIONTREE: from recbole.data.dataset import DecisionTreeDataset DecisionTreeDataset.__bases__ = (RobustnessGymDataset,) return DecisionTreeDataset(config) else: return RobustnessGymDataset(config) def get_transformed_train(config, train_kwargs, train_dataloader, robustness_testing_datasets): """ Converts training data set created by transformations into dataloader object. Uses same config settings as original training data. Args: train_kwargs (dict): Training dataset config train_dataloader (Dataloader): Training dataloader config (Config): General config robustness_testing_datasets (dict): Modified datasets resulting from robustness tests Returns: transformed_train (Dataloader) """ transformed_train = None if "transformation_train" in robustness_testing_datasets: transformation_kwargs = { 'config': config, 'dataset': robustness_testing_datasets['transformation_train'], 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } try: transformation_kwargs['sampler'] = train_kwargs['sampler'] transformation_kwargs['neg_sample_args'] = train_kwargs['neg_sample_args'] transformed_train = train_dataloader(**transformation_kwargs) except: transformed_train = train_dataloader(**transformation_kwargs) return transformed_train def get_sparsity_train(config, train_kwargs, train_dataloader, robustness_testing_datasets): """ Converts training data set created by sparsity into dataloader object. Uses same config settings as original training data. Args: train_kwargs (dict): Training dataset config train_dataloader (Dataloader): Training dataloader config (Config): General config robustness_testing_datasets (dict): Modified datasets resulting from robustness tests Returns: sparsity_train (Dataloader) """ sparsity_train = None if "sparsity" in robustness_testing_datasets: sparsity_kwargs = { 'config': config, 'dataset': robustness_testing_datasets['sparsity'], 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } try: sparsity_kwargs['sampler'] = train_kwargs['sampler'] sparsity_kwargs['neg_sample_args'] = train_kwargs['neg_sample_args'] sparsity_train = train_dataloader(**sparsity_kwargs) except: sparsity_train = train_dataloader(**sparsity_kwargs) return sparsity_train def get_distributional_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ slice_test = None if 'distributional_slice' in robustness_testing_datasets: slice_kwargs = {'dataset': robustness_testing_datasets['distributional_slice']} if 'sampler' in test_kwargs: slice_kwargs['sampler'] = test_kwargs['sampler'] slice_kwargs.update(eval_kwargs) slice_test = test_dataloader(**slice_kwargs) return slice_test def get_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ slice_test = None if 'slice' in robustness_testing_datasets: slice_kwargs = {'dataset': robustness_testing_datasets['slice']} if 'sampler' in test_kwargs: slice_kwargs['sampler'] = test_kwargs['sampler'] slice_kwargs.update(eval_kwargs) slice_test = test_dataloader(**slice_kwargs) return slice_test def get_transformation_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets): """ Args: test_dataloader: test_kwargs: eval_kwargs (dict): test_dataloader (Dataloader): robustness_testing_datasets (dict): Returns: """ transformation_test = None if 'transformation' in robustness_testing_datasets: transformation_kwargs = {'dataset': robustness_testing_datasets['transformation']} if 'sampler' in test_kwargs: transformation_kwargs['sampler'] = test_kwargs['sampler'] transformation_kwargs.update(eval_kwargs) transformation_test = test_dataloader(**transformation_kwargs) return transformation_test def data_preparation(config, dataset, save=False): """ Builds datasets, including datasets built by applying robustness tests, configures train, validation, test sets, converts to tensors. Overloads RecBole data_preparation - we include the preparation of the robustness test train/test/valid sets here. Args: config (Config): dataset (RobustnessGymDataset): save (bool): Returns: """ model_type = config['MODEL_TYPE'] model = config['model'] es = EvalSetting(config) original_datasets, robustness_testing_datasets = dataset.build(es) train_dataset, valid_dataset, test_dataset = original_datasets phases = ['train', 'valid', 'test'] sampler = None logger = getLogger() train_neg_sample_args = config['train_neg_sample_args'] eval_neg_sample_args = es.neg_sample_args # Training train_kwargs = { 'config': config, 'dataset': train_dataset, 'batch_size': config['train_batch_size'], 'dl_format': config['MODEL_INPUT_TYPE'], 'shuffle': True, } if train_neg_sample_args['strategy'] != 'none': if dataset.label_field in dataset.inter_feat: raise ValueError( f'`training_neg_sample_num` should be 0 ' f'if inter_feat have label_field [{dataset.label_field}].' ) if model_type != ModelType.SEQUENTIAL: sampler = Sampler(phases, original_datasets, train_neg_sample_args['distribution']) else: sampler = RepeatableSampler(phases, dataset, train_neg_sample_args['distribution']) if model not in ["MultiVAE", "MultiDAE", "MacridVAE", "CDAE", "ENMF", "RaCT", "RecVAE"]: train_kwargs['sampler'] = sampler.set_phase('train') train_kwargs['neg_sample_args'] = train_neg_sample_args if model_type == ModelType.KNOWLEDGE: kg_sampler = KGSampler(dataset, train_neg_sample_args['distribution']) train_kwargs['kg_sampler'] = kg_sampler dataloader = get_data_loader('train', config, train_neg_sample_args) logger.info( set_color('Build', 'pink') + set_color(f' [{dataloader.__name__}]', 'yellow') + ' for ' + set_color('[train]', 'yellow') + ' with format ' + set_color(f'[{train_kwargs["dl_format"]}]', 'yellow') ) if train_neg_sample_args['strategy'] != 'none': logger.info( set_color('[train]', 'pink') + set_color(' Negative Sampling', 'blue') + f': {train_neg_sample_args}' ) else: logger.info(set_color('[train]', 'pink') + set_color(' No Negative Sampling', 'yellow')) logger.info( set_color('[train]', 'pink') + set_color(' batch_size', 'cyan') + ' = ' + set_color(f'[{train_kwargs["batch_size"]}]', 'yellow') + ', ' + set_color('shuffle', 'cyan') + ' = ' + set_color(f'[{train_kwargs["shuffle"]}]\n', 'yellow') ) train_data = dataloader(**train_kwargs) transformed_train = get_transformed_train(config, train_kwargs, dataloader, robustness_testing_datasets) sparsity_train = get_sparsity_train(config, train_kwargs, dataloader, robustness_testing_datasets) # Evaluation eval_kwargs = { 'config': config, 'batch_size': config['eval_batch_size'], 'dl_format': InputType.POINTWISE, 'shuffle': False, } valid_kwargs = {'dataset': valid_dataset} test_kwargs = {'dataset': test_dataset} if eval_neg_sample_args['strategy'] != 'none': if dataset.label_field in dataset.inter_feat: raise ValueError( f'It can not validate with `{es.es_str[1]}` ' f'when inter_feat have label_field [{dataset.label_field}].' ) if sampler is None: if model_type != ModelType.SEQUENTIAL: sampler = Sampler(phases, original_datasets, eval_neg_sample_args['distribution']) else: sampler = RepeatableSampler(phases, dataset, eval_neg_sample_args['distribution']) else: sampler.set_distribution(eval_neg_sample_args['distribution']) eval_kwargs['neg_sample_args'] = eval_neg_sample_args valid_kwargs['sampler'] = sampler.set_phase('valid') test_kwargs['sampler'] = sampler.set_phase('test') valid_kwargs.update(eval_kwargs) test_kwargs.update(eval_kwargs) dataloader = get_data_loader('evaluation', config, eval_neg_sample_args) logger.info( set_color('Build', 'pink') + set_color(f' [{dataloader.__name__}]', 'yellow') + ' for ' + set_color('[evaluation]', 'yellow') + ' with format ' + set_color(f'[{eval_kwargs["dl_format"]}]', 'yellow') ) logger.info(es) logger.info( set_color('[evaluation]', 'pink') + set_color(' batch_size', 'cyan') + ' = ' + set_color(f'[{eval_kwargs["batch_size"]}]', 'yellow') + ', ' + set_color('shuffle', 'cyan') + ' = ' + set_color(f'[{eval_kwargs["shuffle"]}]\n', 'yellow') ) valid_data = dataloader(**valid_kwargs) test_data = dataloader(**test_kwargs) transformed_test = None if 'transformation_test' in robustness_testing_datasets: transformed_test_kwargs = test_kwargs transformed_test_kwargs['dataset'] = robustness_testing_datasets['transformation_test'] transformed_test = dataloader(**transformed_test_kwargs) slice_test = get_slice_test(eval_kwargs, test_kwargs, dataloader, robustness_testing_datasets) distributional_slice_test = get_distributional_slice_test(eval_kwargs, test_kwargs, dataloader, robustness_testing_datasets) if save: save_split_dataloaders(config, dataloaders=(train_data, valid_data, test_data)) robustness_testing_data = {'slice': slice_test, 'distributional_slice': distributional_slice_test, 'transformation_train': transformed_train, 'transformation_test': transformed_test, 'sparsity': sparsity_train} return train_data, valid_data, test_data, robustness_testing_data def get_config_dict(robustness_tests, base_config_dict): """ Combines robustness_test and train_config_dict into a single config_dict. Args: robustness_tests (dict): robustness test config dict base_config_dict (dict): train/data/eval/model/hyperparam config dict Returns: config_dict (dict): config dict """ config_dict = {} if robustness_tests is not None: if base_config_dict is not None: config_dict = {**robustness_tests, **base_config_dict} else: config_dict = robustness_tests else: if base_config_dict is not None: config_dict = base_config_dict return config_dict def train_and_test(model, dataset, robustness_tests=None, base_config_dict=None, save_model=True): """ Train a recommendation model and run robustness tests. Args: model (str): Name of model to be trained. dataset (str): Dataset name; must match the dataset's folder name located in 'data_path' path. base_config_dict: Configuration dictionary. If no config passed, takes default values. save_model (bool): Determines whether or not to externally save the model after training. robustness_tests (dict): Configuration dictionary for robustness tests. Returns: """ config_dict = get_config_dict(robustness_tests, base_config_dict) config = Config(model=model, dataset=dataset, config_dict=config_dict) init_seed(config['seed'], config['reproducibility']) logger = getLogger() if len(logger.handlers) != 0: logger.removeHandler(logger.handlers[1]) init_logger(config) logger.info(config) # dataset filtering dataset = create_dataset(config) logger.info(dataset) # dataset splitting train_data, valid_data, test_data, robustness_testing_data = data_preparation(config, dataset, save=True) for robustness_test in robustness_testing_data: if robustness_testing_data[robustness_test] is not None: logger.info(set_color('Robustness Test', 'yellow') + f': {robustness_test}') # model loading and initialization model = get_model(config['model'])(config, train_data).to(config['device']) logger.info(model) # trainer loading and initialization trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, model) # model training best_valid_score, best_valid_result = trainer.fit( train_data, valid_data, saved=save_model, show_progress=config['show_progress'] ) # model evaluation test_result = trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('best valid ', 'yellow') + f': {best_valid_result}') logger.info(set_color('test result', 'yellow') + f': {test_result}') test_result_transformation, test_result_sparsity, \ test_result_slice, test_result_distributional_slice = None, None, None, None if robustness_testing_data['slice'] is not None: test_result_slice = trainer.evaluate(robustness_testing_data['slice'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for slice', 'yellow') + f': {test_result_slice}') if robustness_testing_data['distributional_slice'] is not None: test_result_distributional_slice = trainer.evaluate(robustness_testing_data['distributional_slice'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for distributional slice', 'yellow') + f': ' f'{test_result_distributional_slice}') if robustness_testing_data['transformation_test'] is not None: test_result_transformation = trainer.evaluate(robustness_testing_data['transformation_test'], load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('test result for transformation on test', 'yellow') + f': {test_result_transformation}') if robustness_testing_data['transformation_train'] is not None: transformation_model = get_model(config['model'])(config, robustness_testing_data['transformation_train']).to( config['device']) logger.info(transformation_model) transformation_trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, transformation_model) best_valid_score_transformation, best_valid_result_transformation = transformation_trainer.fit( robustness_testing_data['transformation_train'], valid_data, saved=save_model, show_progress=config['show_progress']) test_result_transformation = transformation_trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info( set_color('best valid for transformed training set', 'yellow') + f': {best_valid_result_transformation}') logger.info(set_color('test result for transformed training set', 'yellow') + f': {test_result_transformation}') if robustness_testing_data['sparsity'] is not None: sparsity_model = get_model(config['model'])(config, robustness_testing_data['sparsity']).to(config['device']) logger.info(sparsity_model) sparsity_trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, sparsity_model) best_valid_score_sparsity, best_valid_result_sparsity = sparsity_trainer.fit( robustness_testing_data['sparsity'], valid_data, saved=save_model, show_progress=config['show_progress']) test_result_sparsity = sparsity_trainer.evaluate(test_data, load_best_model=save_model, show_progress=config['show_progress']) logger.info(set_color('best valid for sparsified training set', 'yellow') + f': {best_valid_result_sparsity}') logger.info(set_color('test result for sparsified training set', 'yellow') + f': {test_result_sparsity}') logger.handlers.clear() shutdown() del logger return { 'test_result': test_result, 'distributional_test_result': test_result_distributional_slice, 'transformation_test_result': test_result_transformation, 'sparsity_test_result': test_result_sparsity, 'slice_test_result': test_result_slice } def test(model, dataset, model_path, dataloader_path=None, robustness_tests=None, base_config_dict=None): """ Test a pre-trained model from file path. Note that the only robustness test applicable here is slicing. Args: model (str): Name of model. dataset (str): Name of dataset. model_path (str): Path to saved model. robustness_tests (dict): Configuration dictionary for robustness tests. base_config_dict (dict): Configuration dictionary for data/model/training/evaluation. Returns: """ config_dict = get_config_dict(robustness_tests, base_config_dict) config = Config(model=model, dataset=dataset, config_dict=config_dict) init_seed(config['seed'], config['reproducibility']) # logger initialization logger = getLogger() if len(logger.handlers) != 0: logger.removeHandler(logger.handlers[1]) init_logger(config) # dataset filtering dataset = create_dataset(config) logger.info(dataset) # dataset splitting if dataloader_path is None: train_data, _, test_data, robustness_testing_data = data_preparation(config, dataset, save=False) else: train_data, valid_data, test_data = pickle.load(open(SAVED_DIR + dataloader_path, "rb")) robustness_testing_data = {"slice": None, "transformation": None, "sparsity": None} # model loading and initialization model = get_model(config['model'])(config, train_data).to(config['device']) logger.info(model) # trainer loading and initialization trainer = get_trainer(config['MODEL_TYPE'], config['model'])(config, model) # model evaluation test_result = trainer.evaluate(test_data, load_best_model=True, model_file=model_path, show_progress=config['show_progress']) logger.info(set_color('test result', 'yellow') + f': {test_result}') test_result_slice = None if robustness_testing_data['slice'] is not None: test_result_slice = trainer.evaluate(robustness_testing_data['slice'], load_best_model=True, model_file=model_path, show_progress=config['show_progress']) logger.info(set_color('test result for slice', 'yellow') + f': {test_result_slice}') return { 'test_result': test_result, 'slice_test_result': test_result_slice } if __name__ == '__main__': all_results = {} for model in ["BPR"]: dataset = "ml-100k" base_config_dict = { 'data_path': DATASETS_DIR, 'show_progress': False, 'save_dataset': True, 'load_col': {'inter': ['user_id', 'item_id', 'rating', 'timestamp'], 'user': ['user_id', 'age', 'gender', 'occupation'], 'item': ['item_id', 'release_year', 'class']} } # robustness_dict = { # uncomment and add robustness test specifications here # } results = train_and_test(model=model, dataset=dataset, robustness_tests=robustness_dict, base_config_dict=base_config_dict)
from typing import Iterable, Optional from app.integrations.mailchimp import exceptions from app.integrations.mailchimp.http import MailchimpHTTP from app.integrations.mailchimp.member import MailchimpMember from users.models import User class AppMailchimp: def __init__(self): self.http = MailchimpHTTP() def subscribe_django_user(self, list_id: str, user: User, tags: Optional[Iterable] = None): member = MailchimpMember.from_django_user(user) self.mass_subscribe( list_id=list_id, members=[member], ) if tags is not None: self.set_tags( list_id=list_id, member=member, tags=tags, ) def mass_subscribe(self, list_id: str, members: Iterable[MailchimpMember]): member_list = list() for member in members: member_list.append({ **member.to_mailchimp(), 'status': 'subscribed', }) response = self.http.post( url=f'lists/{list_id}', payload={ 'members': member_list, 'update_existing': True, }, ) if len(response['errors']): raise exceptions.MailchimpSubscriptionFailed(', '.join([f'{err['email_address']}: {err['error']} ({err['error_code']})' for err in response['errors']])) def set_tags(self, list_id: str, member: MailchimpMember, tags: Iterable[str]): self.http.post( url=f'/lists/{list_id}/members/{member.subscriber_hash}/tags', payload={ 'tags': [{'name': tag, 'status': 'active'} for tag in tags], }, expected_status_code=204, ) __all__ = [ AppMailchimp, ]
from typing import Iterable, Optional from app.integrations.mailchimp import exceptions from app.integrations.mailchimp.http import MailchimpHTTP from app.integrations.mailchimp.member import MailchimpMember from users.models import User class AppMailchimp: def __init__(self): self.http = MailchimpHTTP() def subscribe_django_user(self, list_id: str, user: User, tags: Optional[Iterable] = None): member = MailchimpMember.from_django_user(user) self.mass_subscribe( list_id=list_id, members=[member], ) if tags is not None: self.set_tags( list_id=list_id, member=member, tags=tags, ) def mass_subscribe(self, list_id: str, members: Iterable[MailchimpMember]): member_list = list() for member in members: member_list.append({ **member.to_mailchimp(), 'status': 'subscribed', }) response = self.http.post( url=f'lists/{list_id}', payload={ 'members': member_list, 'update_existing': True, }, ) if len(response['errors']): raise exceptions.MailchimpSubscriptionFailed(', '.join([f'{err["email_address"]}: {err["error"]} ({err["error_code"]})' for err in response['errors']])) def set_tags(self, list_id: str, member: MailchimpMember, tags: Iterable[str]): self.http.post( url=f'/lists/{list_id}/members/{member.subscriber_hash}/tags', payload={ 'tags': [{'name': tag, 'status': 'active'} for tag in tags], }, expected_status_code=204, ) __all__ = [ AppMailchimp, ]
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, division, print_function import json import logging import math import os import random import warnings from multiprocessing import cpu_count import numpy as np from scipy.stats import mode, pearsonr from sklearn.metrics import ( confusion_matrix, label_ranking_average_precision_score, matthews_corrcoef, mean_squared_error, ) from tqdm.auto import tqdm, trange import pandas as pd import torch from simpletransformers.classification.classification_utils import InputExample, convert_examples_to_features from simpletransformers.classification.transformer_models.albert_model import AlbertForSequenceClassification from simpletransformers.classification.transformer_models.bert_model import BertForSequenceClassification from simpletransformers.classification.transformer_models.camembert_model import CamembertForSequenceClassification from simpletransformers.classification.transformer_models.distilbert_model import DistilBertForSequenceClassification from simpletransformers.classification.transformer_models.flaubert_model import FlaubertForSequenceClassification from simpletransformers.classification.transformer_models.roberta_model import RobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlm_model import XLMForSequenceClassification from simpletransformers.classification.transformer_models.xlm_roberta_model import XLMRobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlnet_model import XLNetForSequenceClassification from simpletransformers.config.global_args import global_args from simpletransformers.custom_models.models import ElectraForSequenceClassification from tensorboardX import SummaryWriter from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from transformers import ( WEIGHTS_NAME, AdamW, AlbertConfig, AlbertTokenizer, BertConfig, BertTokenizer, CamembertConfig, CamembertTokenizer, DistilBertConfig, DistilBertTokenizer, ElectraConfig, ElectraTokenizer, FlaubertConfig, FlaubertTokenizer, RobertaConfig, RobertaTokenizer, XLMConfig, XLMRobertaConfig, XLMRobertaTokenizer, XLMTokenizer, XLNetConfig, XLNetTokenizer, get_linear_schedule_with_warmup, ) try: import wandb wandb_available = True except ImportError: wandb_available = False logger = logging.getLogger(__name__) class ClassificationModel: def __init__( self, model_type, model_name, num_labels=None, weight=None, args=None, use_cuda=True, cuda_device=-1, **kwargs, ): """ Initializes a ClassificationModel model. Args: model_type: The type of model (bert, xlnet, xlm, roberta, distilbert) model_name: The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model files. num_labels (optional): The number of labels or classes in the dataset. weight (optional): A list of length num_labels containing the weights to assign to each label for loss calculation. args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args. use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only. cuda_device (optional): Specific GPU that should be used. Will use the first available GPU by default. **kwargs (optional): For providing proxies, force_download, resume_download, cache_dir and other options specific to the 'from_pretrained' implementation where this will be supplied. """ # noqa: ignore flake8" MODEL_CLASSES = { "bert": (BertConfig, BertForSequenceClassification, BertTokenizer), "xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer), "xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer), "roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer), "distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer), "albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer), "camembert": (CamembertConfig, CamembertForSequenceClassification, CamembertTokenizer), "xlmroberta": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer), "flaubert": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer), "electra": (ElectraConfig, ElectraForSequenceClassification, ElectraTokenizer), } if args and "manual_seed" in args: random.seed(args["manual_seed"]) np.random.seed(args["manual_seed"]) torch.manual_seed(args["manual_seed"]) if "n_gpu" in args and args["n_gpu"] > 0: torch.cuda.manual_seed_all(args["manual_seed"]) self.args = { "sliding_window": False, "tie_value": 1, "stride": 0.8, "regression": False, } self.args.update(global_args) saved_model_args = self._load_model_args(model_name) if saved_model_args: self.args.update(saved_model_args) if args: self.args.update(args) config_class, model_class, tokenizer_class = MODEL_CLASSES[model_type] if num_labels: self.config = config_class.from_pretrained(model_name, num_labels=num_labels, **self.args["config"]) self.num_labels = num_labels else: self.config = config_class.from_pretrained(model_name, **self.args["config"]) self.num_labels = self.config.num_labels self.weight = weight if use_cuda: if torch.cuda.is_available(): if cuda_device == -1: self.device = torch.device("cuda") else: self.device = torch.device(f"cuda:{cuda_device}") else: raise ValueError( "'use_cuda' set to True when cuda is unavailable." " Make sure CUDA is available or set use_cuda=False." ) else: self.device = "cpu" if self.weight: self.model = model_class.from_pretrained( model_name, config=self.config, weight=torch.Tensor(self.weight).to(self.device), **kwargs, ) else: self.model = model_class.from_pretrained(model_name, config=self.config, **kwargs) self.results = {} if not use_cuda: self.args["fp16"] = False self.tokenizer = tokenizer_class.from_pretrained( model_name, do_lower_case=self.args["do_lower_case"], **kwargs ) self.args["model_name"] = model_name self.args["model_type"] = model_type if model_type in ["camembert", "xlmroberta"]: warnings.warn( f"use_multiprocessing automatically disabled as {model_type}" " fails when using multiprocessing for feature conversion." ) self.args["use_multiprocessing"] = False if self.args["wandb_project"] and not wandb_available: warnings.warn("wandb_project specified but wandb is not available. Wandb disabled.") self.args["wandb_project"] = None def train_model( self, train_df, multi_label=False, output_dir=None, show_running_loss=True, args=None, eval_df=None, verbose=True, **kwargs, ): """ Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be trained on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used. show_running_loss (optional): Set to False to prevent running loss from being printed to console. Defaults to True. args (optional): Optional changes to the args dict of the model. Any changes made will persist for the model. eval_df (optional): A DataFrame against which evaluation will be performed when evaluate_during_training is enabled. Is required if evaluate_during_training is enabled. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: None """ # noqa: ignore flake8" if args: self.args.update(args) if self.args["silent"]: show_running_loss = False if self.args["evaluate_during_training"] and eval_df is None: raise ValueError( "evaluate_during_training is enabled but eval_df is not specified." " Pass eval_df to model.train_model() if using evaluate_during_training." ) if not output_dir: output_dir = self.args["output_dir"] if os.path.exists(output_dir) and os.listdir(output_dir) and not self.args["overwrite_output_dir"]: raise ValueError( "Output directory ({}) already exists and is not empty." " Use --overwrite_output_dir to overcome.".format(output_dir) ) self._move_model_to_device() if "text" in train_df.columns and "labels" in train_df.columns: train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df["text"], train_df["labels"])) ] elif "text_a" in train_df.columns and "text_b" in train_df.columns: train_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(train_df["text_a"], train_df["text_b"], train_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df.iloc[:, 0], train_df.iloc[:, 1])) ] train_dataset = self.load_and_cache_examples(train_examples, verbose=verbose) os.makedirs(output_dir, exist_ok=True) global_step, tr_loss = self.train( train_dataset, output_dir, multi_label=multi_label, show_running_loss=show_running_loss, eval_df=eval_df, verbose=verbose, **kwargs, ) # model_to_save = self.model.module if hasattr(self.model, "module") else self.model # model_to_save.save_pretrained(output_dir) # self.tokenizer.save_pretrained(output_dir) # torch.save(self.args, os.path.join(output_dir, "training_args.bin")) self._save_model() if verbose: logger.info(" Training of {} model complete. Saved to {}.".format(self.args["model_type"], output_dir)) def train( self, train_dataset, output_dir, multi_label=False, show_running_loss=True, eval_df=None, verbose=True, **kwargs, ): """ Trains the model on train_dataset. Utility function to be used by the train_model() method. Not intended to be used directly. """ device = self.device model = self.model args = self.args tb_writer = SummaryWriter(logdir=args["tensorboard_dir"]) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args["train_batch_size"]) t_total = len(train_dataloader) // args["gradient_accumulation_steps"] * args["num_train_epochs"] no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args["weight_decay"], }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] warmup_steps = math.ceil(t_total * args["warmup_ratio"]) args["warmup_steps"] = warmup_steps if args["warmup_steps"] == 0 else args["warmup_steps"] optimizer = AdamW(optimizer_grouped_parameters, lr=args["learning_rate"], eps=args["adam_epsilon"]) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args["warmup_steps"], num_training_steps=t_total ) if args["fp16"]: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args["fp16_opt_level"]) if args["n_gpu"] > 1: model = torch.nn.DataParallel(model) global_step = 0 tr_loss, logging_loss = 0.0, 0.0 model.zero_grad() train_iterator = trange(int(args["num_train_epochs"]), desc="Epoch", disable=args["silent"], mininterval=0) epoch_number = 0 best_eval_metric = None early_stopping_counter = 0 steps_trained_in_current_epoch = 0 epochs_trained = 0 if args["model_name"] and os.path.exists(args["model_name"]): try: # set global_step to gobal_step of last saved checkpoint from model path checkpoint_suffix = args["model_name"].split("/")[-1].split("-") if len(checkpoint_suffix) > 2: checkpoint_suffix = checkpoint_suffix[1] else: checkpoint_suffix = checkpoint_suffix[-1] global_step = int(checkpoint_suffix) epochs_trained = global_step // (len(train_dataloader) // args["gradient_accumulation_steps"]) steps_trained_in_current_epoch = global_step % ( len(train_dataloader) // args["gradient_accumulation_steps"] ) logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(" Continuing training from epoch %d", epochs_trained) logger.info(" Continuing training from global step %d", global_step) logger.info(" Will skip the first %d steps in the current epoch", steps_trained_in_current_epoch) except ValueError: logger.info(" Starting fine-tuning.") if args["evaluate_during_training"]: training_progress_scores = self._create_training_progress_scores(multi_label, **kwargs) if args["wandb_project"]: wandb.init(project=args["wandb_project"], config={**args}, **args["wandb_kwargs"]) wandb.watch(self.model) model.train() for _ in train_iterator: if epochs_trained > 0: epochs_trained -= 1 continue # epoch_iterator = tqdm(train_dataloader, desc="Iteration") for step, batch in enumerate(tqdm(train_dataloader, desc="Current iteration", disable=args["silent"])): if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue batch = tuple(t.to(device) for t in batch) inputs = self._get_inputs_dict(batch) outputs = model(**inputs) # model outputs are always tuple in pytorch-transformers (see doc) loss = outputs[0] if args["n_gpu"] > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training current_loss = loss.item() if show_running_loss: print("\rRunning loss: %f" % loss, end="") if args["gradient_accumulation_steps"] > 1: loss = loss / args["gradient_accumulation_steps"] if args["fp16"]: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() # torch.nn.utils.clip_grad_norm_( # amp.master_params(optimizer), args["max_grad_norm"] # ) else: loss.backward() # torch.nn.utils.clip_grad_norm_( # model.parameters(), args["max_grad_norm"] # ) tr_loss += loss.item() if (step + 1) % args["gradient_accumulation_steps"] == 0: if args["fp16"]: torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args["max_grad_norm"]) else: torch.nn.utils.clip_grad_norm_(model.parameters(), args["max_grad_norm"]) optimizer.step() scheduler.step() # Update learning rate schedule model.zero_grad() global_step += 1 if args["logging_steps"] > 0 and global_step % args["logging_steps"] == 0: # Log metrics tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step) tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args["logging_steps"], global_step) logging_loss = tr_loss if args["wandb_project"]: wandb.log( { "Training loss": current_loss, "lr": scheduler.get_lr()[0], "global_step": global_step, } ) if args["save_steps"] > 0 and global_step % args["save_steps"] == 0: # Save model checkpoint output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) self._save_model(output_dir_current, optimizer, scheduler, model=model) if args["evaluate_during_training"] and ( args["evaluate_during_training_steps"] > 0 and global_step % args["evaluate_during_training_steps"] == 0 ): # Only evaluate when single GPU otherwise metrics may not average well results, _, _ = self.eval_model( eval_df, verbose=verbose and args["evaluate_during_training_verbose"], silent=True, **kwargs, ) for key, value in results.items(): tb_writer.add_scalar("eval_{}".format(key), value, global_step) output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) if args["save_eval_checkpoints"]: self._save_model(output_dir_current, optimizer, scheduler, model=model, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv( os.path.join(args["output_dir"], "training_progress_scores.csv"), index=False, ) if args["wandb_project"]: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) if best_eval_metric and args["early_stopping_metric_minimize"]: if ( results[args["early_stopping_metric"]] - best_eval_metric < args["early_stopping_delta"] ): best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args["use_early_stopping"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args["early_stopping_metric"]}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args["early_stopping_patience"]}") else: if verbose: logger.info( f" Patience of {args["early_stopping_patience"]} steps reached" ) logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step else: if ( results[args["early_stopping_metric"]] - best_eval_metric > args["early_stopping_delta"] ): best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args["use_early_stopping"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args["early_stopping_metric"]}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args["early_stopping_patience"]}") else: if verbose: logger.info( f" Patience of {args["early_stopping_patience"]} steps reached" ) logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step epoch_number += 1 output_dir_current = os.path.join(output_dir, "checkpoint-{}-epoch-{}".format(global_step, epoch_number)) if args["save_model_every_epoch"] or args["evaluate_during_training"]: os.makedirs(output_dir_current, exist_ok=True) if args["save_model_every_epoch"]: self._save_model(output_dir_current, optimizer, scheduler, model=model) if args["evaluate_during_training"]: results, _, _ = self.eval_model( eval_df, verbose=verbose and args["evaluate_during_training_verbose"], silent=True, **kwargs ) self._save_model(output_dir_current, optimizer, scheduler, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv(os.path.join(args["output_dir"], "training_progress_scores.csv"), index=False) if args["wandb_project"]: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) if best_eval_metric and args["early_stopping_metric_minimize"]: if results[args["early_stopping_metric"]] - best_eval_metric < args["early_stopping_delta"]: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args["use_early_stopping"] and args["early_stopping_consider_epochs"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args["early_stopping_metric"]}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args["early_stopping_patience"]}") else: if verbose: logger.info(f" Patience of {args["early_stopping_patience"]} steps reached") logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step else: if results[args["early_stopping_metric"]] - best_eval_metric > args["early_stopping_delta"]: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args["use_early_stopping"] and args["early_stopping_consider_epochs"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args["early_stopping_metric"]}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args["early_stopping_patience"]}") else: if verbose: logger.info(f" Patience of {args["early_stopping_patience"]} steps reached") logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step return global_step, tr_loss / global_step def eval_model(self, eval_df, multi_label=False, output_dir=None, verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be evaluated on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used. verbose: If verbose, results will be printed to the console on completion of evaluation. silent: If silent, tqdm progress bars will be hidden. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. model_outputs: List of model outputs for each row in eval_df wrong_preds: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" if not output_dir: output_dir = self.args["output_dir"] self._move_model_to_device() result, model_outputs, wrong_preds = self.evaluate( eval_df, output_dir, multi_label=multi_label, verbose=verbose, silent=silent, **kwargs ) self.results.update(result) if verbose: logger.info(self.results) return result, model_outputs, wrong_preds def evaluate(self, eval_df, output_dir, multi_label=False, prefix="", verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly. """ device = self.device model = self.model args = self.args eval_output_dir = output_dir results = {} if "text" in eval_df.columns and "labels" in eval_df.columns: eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df["text"], eval_df["labels"])) ] elif "text_a" in eval_df.columns and "text_b" in eval_df.columns: eval_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(eval_df["text_a"], eval_df["text_b"], eval_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df.iloc[:, 0], eval_df.iloc[:, 1])) ] if args["sliding_window"]: eval_dataset, window_counts = self.load_and_cache_examples( eval_examples, evaluate=True, verbose=verbose, silent=silent ) else: eval_dataset = self.load_and_cache_examples(eval_examples, evaluate=True, verbose=verbose, silent=silent) os.makedirs(eval_output_dir, exist_ok=True) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args["eval_batch_size"]) eval_loss = 0.0 nb_eval_steps = 0 preds = None out_label_ids = None model.eval() for batch in tqdm(eval_dataloader, disable=args["silent"] or silent): batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args["sliding_window"]: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] out_label_ids = [ out_label_ids[i] for i in range(len(out_label_ids)) if i in [window[0] for window in window_ranges] ] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: mode_pred, counts = mode(pred_row) if len(counts) > 1 and counts[0] == counts[1]: final_preds.append(args["tie_value"]) else: final_preds.append(mode_pred[0]) preds = np.array(final_preds) elif not multi_label and args["regression"] is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if not multi_label: preds = np.argmax(preds, axis=1) result, wrong = self.compute_metrics(preds, out_label_ids, eval_examples, **kwargs) result["eval_loss"] = eval_loss results.update(result) output_eval_file = os.path.join(eval_output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(result.keys()): writer.write("{} = {}\n".format(key, str(result[key]))) return results, model_outputs, wrong def load_and_cache_examples( self, examples, evaluate=False, no_cache=False, multi_label=False, verbose=True, silent=False ): """ Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for train() and eval() methods. Not intended to be used directly. """ process_count = self.args["process_count"] tokenizer = self.tokenizer args = self.args if not no_cache: no_cache = args["no_cache"] if not multi_label and args["regression"]: output_mode = "regression" else: output_mode = "classification" os.makedirs(self.args["cache_dir"], exist_ok=True) mode = "dev" if evaluate else "train" cached_features_file = os.path.join( args["cache_dir"], "cached_{}_{}_{}_{}_{}".format( mode, args["model_type"], args["max_seq_length"], self.num_labels, len(examples), ), ) if os.path.exists(cached_features_file) and ( (not args["reprocess_input_data"] and not no_cache) or (mode == "dev" and args["use_cached_eval_features"] and not no_cache) ): features = torch.load(cached_features_file) if verbose: logger.info(f" Features loaded from cache at {cached_features_file}") else: if verbose: logger.info(f" Converting to features started. Cache is not used.") if args["sliding_window"]: logger.info(" Sliding window enabled") features = convert_examples_to_features( examples, args["max_seq_length"], tokenizer, output_mode, # XLNet has a CLS token at the end cls_token_at_end=bool(args["model_type"] in ["xlnet"]), cls_token=tokenizer.cls_token, cls_token_segment_id=2 if args["model_type"] in ["xlnet"] else 0, sep_token=tokenizer.sep_token, # RoBERTa uses an extra separator b/w pairs of sentences, # cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805 sep_token_extra=bool(args["model_type"] in ["roberta", "camembert", "xlmroberta"]), # PAD on the left for XLNet pad_on_left=bool(args["model_type"] in ["xlnet"]), pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0], pad_token_segment_id=4 if args["model_type"] in ["xlnet"] else 0, process_count=process_count, multi_label=multi_label, silent=args["silent"] or silent, use_multiprocessing=args["use_multiprocessing"], sliding_window=args["sliding_window"], flatten=not evaluate, stride=args["stride"], ) if verbose and args["sliding_window"]: logger.info(f" {len(features)} features created from {len(examples)} samples.") if not no_cache: torch.save(features, cached_features_file) if args["sliding_window"] and evaluate: window_counts = [len(sample) for sample in features] features = [feature for feature_set in features for feature in feature_set] all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) if output_mode == "classification": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long) elif output_mode == "regression": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids) if args["sliding_window"] and evaluate: return dataset, window_counts else: return dataset def compute_metrics(self, preds, labels, eval_examples, multi_label=False, **kwargs): """ Computes the evaluation metrics for the model predictions. Args: preds: Model predictions labels: Ground truth labels eval_examples: List of examples on which evaluation was performed **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. (Matthews correlation coefficient, tp, tn, fp, fn) wrong: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" assert len(preds) == len(labels) extra_metrics = {} for metric, func in kwargs.items(): extra_metrics[metric] = func(labels, preds) mismatched = labels != preds wrong = [i for (i, v) in zip(eval_examples, mismatched) if v.any()] if multi_label: label_ranking_score = label_ranking_average_precision_score(labels, preds) return {**{"LRAP": label_ranking_score}, **extra_metrics}, wrong elif self.args["regression"]: return {**extra_metrics}, wrong mcc = matthews_corrcoef(labels, preds) if self.model.num_labels == 2: tn, fp, fn, tp = confusion_matrix(labels, preds, labels=[0, 1]).ravel() return ( {**{"mcc": mcc, "tp": tp, "tn": tn, "fp": fp, "fn": fn}, **extra_metrics}, wrong, ) else: return {**{"mcc": mcc}, **extra_metrics}, wrong def predict(self, to_predict, multi_label=False): """ Performs predictions on a list of text. Args: to_predict: A python list of text (str) to be sent to the model for prediction. Returns: preds: A python list of the predictions (0 or 1) for each text. model_outputs: A python list of the raw model outputs for each text. """ device = self.device model = self.model args = self.args self._move_model_to_device() if multi_label: eval_examples = [ InputExample(i, text, None, [0 for i in range(self.num_labels)]) for i, text in enumerate(to_predict) ] else: if isinstance(to_predict[0], list): eval_examples = [InputExample(i, text[0], text[1], 0) for i, text in enumerate(to_predict)] else: eval_examples = [InputExample(i, text, None, 0) for i, text in enumerate(to_predict)] if args["sliding_window"]: eval_dataset, window_counts = self.load_and_cache_examples(eval_examples, evaluate=True, no_cache=True) else: eval_dataset = self.load_and_cache_examples( eval_examples, evaluate=True, multi_label=multi_label, no_cache=True ) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args["eval_batch_size"]) eval_loss = 0.0 nb_eval_steps = 0 preds = None out_label_ids = None if self.config.output_hidden_states: for batch in tqdm(eval_dataloader, disable=args["silent"]): model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] embedding_outputs, layer_hidden_states = outputs[2][0], outputs[2][1:] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() all_layer_hidden_states = [state.detach().cpu().numpy() for state in layer_hidden_states] all_embedding_outputs = embedding_outputs.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) all_layer_hidden_states = np.append( [state.detach().cpu().numpy() for state in layer_hidden_states], axis=0 ) all_embedding_outputs = np.append(embedding_outputs.detach().cpu().numpy(), axis=0) else: for batch in tqdm(eval_dataloader, disable=args["silent"]): model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args["sliding_window"]: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: mode_pred, counts = mode(pred_row) if len(counts) > 1 and counts[0] == counts[1]: final_preds.append(args["tie_value"]) else: final_preds.append(mode_pred[0]) preds = np.array(final_preds) elif not multi_label and args["regression"] is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if multi_label: if isinstance(args["threshold"], list): threshold_values = args["threshold"] preds = [ [self._threshold(pred, threshold_values[i]) for i, pred in enumerate(example)] for example in preds ] else: preds = [[self._threshold(pred, args["threshold"]) for pred in example] for example in preds] else: preds = np.argmax(preds, axis=1) if self.config.output_hidden_states: return preds, model_outputs, all_embedding_outputs, all_layer_hidden_states else: return preds, model_outputs def _threshold(self, x, threshold): if x >= threshold: return 1 return 0 def _move_model_to_device(self): self.model.to(self.device) def _get_inputs_dict(self, batch): inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} # XLM, DistilBERT and RoBERTa don't use segment_ids if self.args["model_type"] != "distilbert": inputs["token_type_ids"] = batch[2] if self.args["model_type"] in ["bert", "xlnet", "albert"] else None return inputs def _get_last_metrics(self, metric_values): return {metric: values[-1] for metric, values in metric_values.items()} def _create_training_progress_scores(self, multi_label, **kwargs): extra_metrics = {key: [] for key in kwargs} if multi_label: training_progress_scores = { "global_step": [], "LRAP": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: if self.model.num_labels == 2: training_progress_scores = { "global_step": [], "tp": [], "tn": [], "fp": [], "fn": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } elif self.model.num_labels == 1: training_progress_scores = { "global_step": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: training_progress_scores = { "global_step": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } return training_progress_scores def _save_model(self, output_dir=None, optimizer=None, scheduler=None, model=None, results=None): if not output_dir: output_dir = self.args["output_dir"] os.makedirs(output_dir, exist_ok=True) if model and not self.args["no_save"]: # Take care of distributed/parallel training model_to_save = model.module if hasattr(model, "module") else model model_to_save.save_pretrained(output_dir) self.tokenizer.save_pretrained(output_dir) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) if optimizer and scheduler: torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) self._save_model_args(output_dir) if results: output_eval_file = os.path.join(output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(results.keys()): writer.write("{} = {}\n".format(key, str(results[key]))) def _save_model_args(self, output_dir): os.makedirs(output_dir, exist_ok=True) with open(os.path.join(output_dir, "model_args.json"), "w") as f: json.dump(self.args, f) def _load_model_args(self, input_dir): model_args_file = os.path.join(input_dir, "model_args.json") if os.path.isfile(model_args_file): with open(model_args_file, "r") as f: model_args = json.load(f) return model_args
#!/usr/bin/env python # coding: utf-8 from __future__ import absolute_import, division, print_function import json import logging import math import os import random import warnings from multiprocessing import cpu_count import numpy as np from scipy.stats import mode, pearsonr from sklearn.metrics import ( confusion_matrix, label_ranking_average_precision_score, matthews_corrcoef, mean_squared_error, ) from tqdm.auto import tqdm, trange import pandas as pd import torch from simpletransformers.classification.classification_utils import InputExample, convert_examples_to_features from simpletransformers.classification.transformer_models.albert_model import AlbertForSequenceClassification from simpletransformers.classification.transformer_models.bert_model import BertForSequenceClassification from simpletransformers.classification.transformer_models.camembert_model import CamembertForSequenceClassification from simpletransformers.classification.transformer_models.distilbert_model import DistilBertForSequenceClassification from simpletransformers.classification.transformer_models.flaubert_model import FlaubertForSequenceClassification from simpletransformers.classification.transformer_models.roberta_model import RobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlm_model import XLMForSequenceClassification from simpletransformers.classification.transformer_models.xlm_roberta_model import XLMRobertaForSequenceClassification from simpletransformers.classification.transformer_models.xlnet_model import XLNetForSequenceClassification from simpletransformers.config.global_args import global_args from simpletransformers.custom_models.models import ElectraForSequenceClassification from tensorboardX import SummaryWriter from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distributed import DistributedSampler from transformers import ( WEIGHTS_NAME, AdamW, AlbertConfig, AlbertTokenizer, BertConfig, BertTokenizer, CamembertConfig, CamembertTokenizer, DistilBertConfig, DistilBertTokenizer, ElectraConfig, ElectraTokenizer, FlaubertConfig, FlaubertTokenizer, RobertaConfig, RobertaTokenizer, XLMConfig, XLMRobertaConfig, XLMRobertaTokenizer, XLMTokenizer, XLNetConfig, XLNetTokenizer, get_linear_schedule_with_warmup, ) try: import wandb wandb_available = True except ImportError: wandb_available = False logger = logging.getLogger(__name__) class ClassificationModel: def __init__( self, model_type, model_name, num_labels=None, weight=None, args=None, use_cuda=True, cuda_device=-1, **kwargs, ): """ Initializes a ClassificationModel model. Args: model_type: The type of model (bert, xlnet, xlm, roberta, distilbert) model_name: The exact architecture and trained weights to use. This may be a Hugging Face Transformers compatible pre-trained model, a community model, or the path to a directory containing model files. num_labels (optional): The number of labels or classes in the dataset. weight (optional): A list of length num_labels containing the weights to assign to each label for loss calculation. args (optional): Default args will be used if this parameter is not provided. If provided, it should be a dict containing the args that should be changed in the default args. use_cuda (optional): Use GPU if available. Setting to False will force model to use CPU only. cuda_device (optional): Specific GPU that should be used. Will use the first available GPU by default. **kwargs (optional): For providing proxies, force_download, resume_download, cache_dir and other options specific to the 'from_pretrained' implementation where this will be supplied. """ # noqa: ignore flake8" MODEL_CLASSES = { "bert": (BertConfig, BertForSequenceClassification, BertTokenizer), "xlnet": (XLNetConfig, XLNetForSequenceClassification, XLNetTokenizer), "xlm": (XLMConfig, XLMForSequenceClassification, XLMTokenizer), "roberta": (RobertaConfig, RobertaForSequenceClassification, RobertaTokenizer), "distilbert": (DistilBertConfig, DistilBertForSequenceClassification, DistilBertTokenizer), "albert": (AlbertConfig, AlbertForSequenceClassification, AlbertTokenizer), "camembert": (CamembertConfig, CamembertForSequenceClassification, CamembertTokenizer), "xlmroberta": (XLMRobertaConfig, XLMRobertaForSequenceClassification, XLMRobertaTokenizer), "flaubert": (FlaubertConfig, FlaubertForSequenceClassification, FlaubertTokenizer), "electra": (ElectraConfig, ElectraForSequenceClassification, ElectraTokenizer), } if args and "manual_seed" in args: random.seed(args["manual_seed"]) np.random.seed(args["manual_seed"]) torch.manual_seed(args["manual_seed"]) if "n_gpu" in args and args["n_gpu"] > 0: torch.cuda.manual_seed_all(args["manual_seed"]) self.args = { "sliding_window": False, "tie_value": 1, "stride": 0.8, "regression": False, } self.args.update(global_args) saved_model_args = self._load_model_args(model_name) if saved_model_args: self.args.update(saved_model_args) if args: self.args.update(args) config_class, model_class, tokenizer_class = MODEL_CLASSES[model_type] if num_labels: self.config = config_class.from_pretrained(model_name, num_labels=num_labels, **self.args["config"]) self.num_labels = num_labels else: self.config = config_class.from_pretrained(model_name, **self.args["config"]) self.num_labels = self.config.num_labels self.weight = weight if use_cuda: if torch.cuda.is_available(): if cuda_device == -1: self.device = torch.device("cuda") else: self.device = torch.device(f"cuda:{cuda_device}") else: raise ValueError( "'use_cuda' set to True when cuda is unavailable." " Make sure CUDA is available or set use_cuda=False." ) else: self.device = "cpu" if self.weight: self.model = model_class.from_pretrained( model_name, config=self.config, weight=torch.Tensor(self.weight).to(self.device), **kwargs, ) else: self.model = model_class.from_pretrained(model_name, config=self.config, **kwargs) self.results = {} if not use_cuda: self.args["fp16"] = False self.tokenizer = tokenizer_class.from_pretrained( model_name, do_lower_case=self.args["do_lower_case"], **kwargs ) self.args["model_name"] = model_name self.args["model_type"] = model_type if model_type in ["camembert", "xlmroberta"]: warnings.warn( f"use_multiprocessing automatically disabled as {model_type}" " fails when using multiprocessing for feature conversion." ) self.args["use_multiprocessing"] = False if self.args["wandb_project"] and not wandb_available: warnings.warn("wandb_project specified but wandb is not available. Wandb disabled.") self.args["wandb_project"] = None def train_model( self, train_df, multi_label=False, output_dir=None, show_running_loss=True, args=None, eval_df=None, verbose=True, **kwargs, ): """ Trains the model using 'train_df' Args: train_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be trained on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used. show_running_loss (optional): Set to False to prevent running loss from being printed to console. Defaults to True. args (optional): Optional changes to the args dict of the model. Any changes made will persist for the model. eval_df (optional): A DataFrame against which evaluation will be performed when evaluate_during_training is enabled. Is required if evaluate_during_training is enabled. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: None """ # noqa: ignore flake8" if args: self.args.update(args) if self.args["silent"]: show_running_loss = False if self.args["evaluate_during_training"] and eval_df is None: raise ValueError( "evaluate_during_training is enabled but eval_df is not specified." " Pass eval_df to model.train_model() if using evaluate_during_training." ) if not output_dir: output_dir = self.args["output_dir"] if os.path.exists(output_dir) and os.listdir(output_dir) and not self.args["overwrite_output_dir"]: raise ValueError( "Output directory ({}) already exists and is not empty." " Use --overwrite_output_dir to overcome.".format(output_dir) ) self._move_model_to_device() if "text" in train_df.columns and "labels" in train_df.columns: train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df["text"], train_df["labels"])) ] elif "text_a" in train_df.columns and "text_b" in train_df.columns: train_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(train_df["text_a"], train_df["text_b"], train_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) train_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(train_df.iloc[:, 0], train_df.iloc[:, 1])) ] train_dataset = self.load_and_cache_examples(train_examples, verbose=verbose) os.makedirs(output_dir, exist_ok=True) global_step, tr_loss = self.train( train_dataset, output_dir, multi_label=multi_label, show_running_loss=show_running_loss, eval_df=eval_df, verbose=verbose, **kwargs, ) # model_to_save = self.model.module if hasattr(self.model, "module") else self.model # model_to_save.save_pretrained(output_dir) # self.tokenizer.save_pretrained(output_dir) # torch.save(self.args, os.path.join(output_dir, "training_args.bin")) self._save_model() if verbose: logger.info(" Training of {} model complete. Saved to {}.".format(self.args["model_type"], output_dir)) def train( self, train_dataset, output_dir, multi_label=False, show_running_loss=True, eval_df=None, verbose=True, **kwargs, ): """ Trains the model on train_dataset. Utility function to be used by the train_model() method. Not intended to be used directly. """ device = self.device model = self.model args = self.args tb_writer = SummaryWriter(logdir=args["tensorboard_dir"]) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args["train_batch_size"]) t_total = len(train_dataloader) // args["gradient_accumulation_steps"] * args["num_train_epochs"] no_decay = ["bias", "LayerNorm.weight"] optimizer_grouped_parameters = [ { "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "weight_decay": args["weight_decay"], }, { "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "weight_decay": 0.0, }, ] warmup_steps = math.ceil(t_total * args["warmup_ratio"]) args["warmup_steps"] = warmup_steps if args["warmup_steps"] == 0 else args["warmup_steps"] optimizer = AdamW(optimizer_grouped_parameters, lr=args["learning_rate"], eps=args["adam_epsilon"]) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=args["warmup_steps"], num_training_steps=t_total ) if args["fp16"]: try: from apex import amp except ImportError: raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") model, optimizer = amp.initialize(model, optimizer, opt_level=args["fp16_opt_level"]) if args["n_gpu"] > 1: model = torch.nn.DataParallel(model) global_step = 0 tr_loss, logging_loss = 0.0, 0.0 model.zero_grad() train_iterator = trange(int(args["num_train_epochs"]), desc="Epoch", disable=args["silent"], mininterval=0) epoch_number = 0 best_eval_metric = None early_stopping_counter = 0 steps_trained_in_current_epoch = 0 epochs_trained = 0 if args["model_name"] and os.path.exists(args["model_name"]): try: # set global_step to gobal_step of last saved checkpoint from model path checkpoint_suffix = args["model_name"].split("/")[-1].split("-") if len(checkpoint_suffix) > 2: checkpoint_suffix = checkpoint_suffix[1] else: checkpoint_suffix = checkpoint_suffix[-1] global_step = int(checkpoint_suffix) epochs_trained = global_step // (len(train_dataloader) // args["gradient_accumulation_steps"]) steps_trained_in_current_epoch = global_step % ( len(train_dataloader) // args["gradient_accumulation_steps"] ) logger.info(" Continuing training from checkpoint, will skip to saved global_step") logger.info(" Continuing training from epoch %d", epochs_trained) logger.info(" Continuing training from global step %d", global_step) logger.info(" Will skip the first %d steps in the current epoch", steps_trained_in_current_epoch) except ValueError: logger.info(" Starting fine-tuning.") if args["evaluate_during_training"]: training_progress_scores = self._create_training_progress_scores(multi_label, **kwargs) if args["wandb_project"]: wandb.init(project=args["wandb_project"], config={**args}, **args["wandb_kwargs"]) wandb.watch(self.model) model.train() for _ in train_iterator: if epochs_trained > 0: epochs_trained -= 1 continue # epoch_iterator = tqdm(train_dataloader, desc="Iteration") for step, batch in enumerate(tqdm(train_dataloader, desc="Current iteration", disable=args["silent"])): if steps_trained_in_current_epoch > 0: steps_trained_in_current_epoch -= 1 continue batch = tuple(t.to(device) for t in batch) inputs = self._get_inputs_dict(batch) outputs = model(**inputs) # model outputs are always tuple in pytorch-transformers (see doc) loss = outputs[0] if args["n_gpu"] > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training current_loss = loss.item() if show_running_loss: print("\rRunning loss: %f" % loss, end="") if args["gradient_accumulation_steps"] > 1: loss = loss / args["gradient_accumulation_steps"] if args["fp16"]: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() # torch.nn.utils.clip_grad_norm_( # amp.master_params(optimizer), args["max_grad_norm"] # ) else: loss.backward() # torch.nn.utils.clip_grad_norm_( # model.parameters(), args["max_grad_norm"] # ) tr_loss += loss.item() if (step + 1) % args["gradient_accumulation_steps"] == 0: if args["fp16"]: torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args["max_grad_norm"]) else: torch.nn.utils.clip_grad_norm_(model.parameters(), args["max_grad_norm"]) optimizer.step() scheduler.step() # Update learning rate schedule model.zero_grad() global_step += 1 if args["logging_steps"] > 0 and global_step % args["logging_steps"] == 0: # Log metrics tb_writer.add_scalar("lr", scheduler.get_lr()[0], global_step) tb_writer.add_scalar("loss", (tr_loss - logging_loss) / args["logging_steps"], global_step) logging_loss = tr_loss if args["wandb_project"]: wandb.log( { "Training loss": current_loss, "lr": scheduler.get_lr()[0], "global_step": global_step, } ) if args["save_steps"] > 0 and global_step % args["save_steps"] == 0: # Save model checkpoint output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) self._save_model(output_dir_current, optimizer, scheduler, model=model) if args["evaluate_during_training"] and ( args["evaluate_during_training_steps"] > 0 and global_step % args["evaluate_during_training_steps"] == 0 ): # Only evaluate when single GPU otherwise metrics may not average well results, _, _ = self.eval_model( eval_df, verbose=verbose and args["evaluate_during_training_verbose"], silent=True, **kwargs, ) for key, value in results.items(): tb_writer.add_scalar("eval_{}".format(key), value, global_step) output_dir_current = os.path.join(output_dir, "checkpoint-{}".format(global_step)) if args["save_eval_checkpoints"]: self._save_model(output_dir_current, optimizer, scheduler, model=model, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv( os.path.join(args["output_dir"], "training_progress_scores.csv"), index=False, ) if args["wandb_project"]: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) if best_eval_metric and args["early_stopping_metric_minimize"]: if ( results[args["early_stopping_metric"]] - best_eval_metric < args["early_stopping_delta"] ): best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args["use_early_stopping"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args['early_stopping_metric']}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args['early_stopping_patience']}") else: if verbose: logger.info( f" Patience of {args['early_stopping_patience']} steps reached" ) logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step else: if ( results[args["early_stopping_metric"]] - best_eval_metric > args["early_stopping_delta"] ): best_eval_metric = results[args["early_stopping_metric"]] self._save_model( args["best_model_dir"], optimizer, scheduler, model=model, results=results ) early_stopping_counter = 0 else: if args["use_early_stopping"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args['early_stopping_metric']}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args['early_stopping_patience']}") else: if verbose: logger.info( f" Patience of {args['early_stopping_patience']} steps reached" ) logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step epoch_number += 1 output_dir_current = os.path.join(output_dir, "checkpoint-{}-epoch-{}".format(global_step, epoch_number)) if args["save_model_every_epoch"] or args["evaluate_during_training"]: os.makedirs(output_dir_current, exist_ok=True) if args["save_model_every_epoch"]: self._save_model(output_dir_current, optimizer, scheduler, model=model) if args["evaluate_during_training"]: results, _, _ = self.eval_model( eval_df, verbose=verbose and args["evaluate_during_training_verbose"], silent=True, **kwargs ) self._save_model(output_dir_current, optimizer, scheduler, results=results) training_progress_scores["global_step"].append(global_step) training_progress_scores["train_loss"].append(current_loss) for key in results: training_progress_scores[key].append(results[key]) report = pd.DataFrame(training_progress_scores) report.to_csv(os.path.join(args["output_dir"], "training_progress_scores.csv"), index=False) if args["wandb_project"]: wandb.log(self._get_last_metrics(training_progress_scores)) if not best_eval_metric: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) if best_eval_metric and args["early_stopping_metric_minimize"]: if results[args["early_stopping_metric"]] - best_eval_metric < args["early_stopping_delta"]: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args["use_early_stopping"] and args["early_stopping_consider_epochs"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args['early_stopping_metric']}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args['early_stopping_patience']}") else: if verbose: logger.info(f" Patience of {args['early_stopping_patience']} steps reached") logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step else: if results[args["early_stopping_metric"]] - best_eval_metric > args["early_stopping_delta"]: best_eval_metric = results[args["early_stopping_metric"]] self._save_model(args["best_model_dir"], optimizer, scheduler, model=model, results=results) early_stopping_counter = 0 else: if args["use_early_stopping"] and args["early_stopping_consider_epochs"]: if early_stopping_counter < args["early_stopping_patience"]: early_stopping_counter += 1 if verbose: logger.info(f" No improvement in {args['early_stopping_metric']}") logger.info(f" Current step: {early_stopping_counter}") logger.info(f" Early stopping patience: {args['early_stopping_patience']}") else: if verbose: logger.info(f" Patience of {args['early_stopping_patience']} steps reached") logger.info(" Training terminated.") train_iterator.close() return global_step, tr_loss / global_step return global_step, tr_loss / global_step def eval_model(self, eval_df, multi_label=False, output_dir=None, verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Saves results to output_dir. Args: eval_df: Pandas Dataframe containing at least two columns. If the Dataframe has a header, it should contain a 'text' and a 'labels' column. If no header is present, the Dataframe should contain at least two columns, with the first column containing the text, and the second column containing the label. The model will be evaluated on this Dataframe. output_dir: The directory where model files will be saved. If not given, self.args['output_dir'] will be used. verbose: If verbose, results will be printed to the console on completion of evaluation. silent: If silent, tqdm progress bars will be hidden. **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. model_outputs: List of model outputs for each row in eval_df wrong_preds: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" if not output_dir: output_dir = self.args["output_dir"] self._move_model_to_device() result, model_outputs, wrong_preds = self.evaluate( eval_df, output_dir, multi_label=multi_label, verbose=verbose, silent=silent, **kwargs ) self.results.update(result) if verbose: logger.info(self.results) return result, model_outputs, wrong_preds def evaluate(self, eval_df, output_dir, multi_label=False, prefix="", verbose=True, silent=False, **kwargs): """ Evaluates the model on eval_df. Utility function to be used by the eval_model() method. Not intended to be used directly. """ device = self.device model = self.model args = self.args eval_output_dir = output_dir results = {} if "text" in eval_df.columns and "labels" in eval_df.columns: eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df["text"], eval_df["labels"])) ] elif "text_a" in eval_df.columns and "text_b" in eval_df.columns: eval_examples = [ InputExample(i, text_a, text_b, label) for i, (text_a, text_b, label) in enumerate( zip(eval_df["text_a"], eval_df["text_b"], eval_df["labels"]) ) ] else: warnings.warn( "Dataframe headers not specified. Falling back to using column 0 as text and column 1 as labels." ) eval_examples = [ InputExample(i, text, None, label) for i, (text, label) in enumerate(zip(eval_df.iloc[:, 0], eval_df.iloc[:, 1])) ] if args["sliding_window"]: eval_dataset, window_counts = self.load_and_cache_examples( eval_examples, evaluate=True, verbose=verbose, silent=silent ) else: eval_dataset = self.load_and_cache_examples(eval_examples, evaluate=True, verbose=verbose, silent=silent) os.makedirs(eval_output_dir, exist_ok=True) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args["eval_batch_size"]) eval_loss = 0.0 nb_eval_steps = 0 preds = None out_label_ids = None model.eval() for batch in tqdm(eval_dataloader, disable=args["silent"] or silent): batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args["sliding_window"]: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] out_label_ids = [ out_label_ids[i] for i in range(len(out_label_ids)) if i in [window[0] for window in window_ranges] ] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: mode_pred, counts = mode(pred_row) if len(counts) > 1 and counts[0] == counts[1]: final_preds.append(args["tie_value"]) else: final_preds.append(mode_pred[0]) preds = np.array(final_preds) elif not multi_label and args["regression"] is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if not multi_label: preds = np.argmax(preds, axis=1) result, wrong = self.compute_metrics(preds, out_label_ids, eval_examples, **kwargs) result["eval_loss"] = eval_loss results.update(result) output_eval_file = os.path.join(eval_output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(result.keys()): writer.write("{} = {}\n".format(key, str(result[key]))) return results, model_outputs, wrong def load_and_cache_examples( self, examples, evaluate=False, no_cache=False, multi_label=False, verbose=True, silent=False ): """ Converts a list of InputExample objects to a TensorDataset containing InputFeatures. Caches the InputFeatures. Utility function for train() and eval() methods. Not intended to be used directly. """ process_count = self.args["process_count"] tokenizer = self.tokenizer args = self.args if not no_cache: no_cache = args["no_cache"] if not multi_label and args["regression"]: output_mode = "regression" else: output_mode = "classification" os.makedirs(self.args["cache_dir"], exist_ok=True) mode = "dev" if evaluate else "train" cached_features_file = os.path.join( args["cache_dir"], "cached_{}_{}_{}_{}_{}".format( mode, args["model_type"], args["max_seq_length"], self.num_labels, len(examples), ), ) if os.path.exists(cached_features_file) and ( (not args["reprocess_input_data"] and not no_cache) or (mode == "dev" and args["use_cached_eval_features"] and not no_cache) ): features = torch.load(cached_features_file) if verbose: logger.info(f" Features loaded from cache at {cached_features_file}") else: if verbose: logger.info(f" Converting to features started. Cache is not used.") if args["sliding_window"]: logger.info(" Sliding window enabled") features = convert_examples_to_features( examples, args["max_seq_length"], tokenizer, output_mode, # XLNet has a CLS token at the end cls_token_at_end=bool(args["model_type"] in ["xlnet"]), cls_token=tokenizer.cls_token, cls_token_segment_id=2 if args["model_type"] in ["xlnet"] else 0, sep_token=tokenizer.sep_token, # RoBERTa uses an extra separator b/w pairs of sentences, # cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805 sep_token_extra=bool(args["model_type"] in ["roberta", "camembert", "xlmroberta"]), # PAD on the left for XLNet pad_on_left=bool(args["model_type"] in ["xlnet"]), pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0], pad_token_segment_id=4 if args["model_type"] in ["xlnet"] else 0, process_count=process_count, multi_label=multi_label, silent=args["silent"] or silent, use_multiprocessing=args["use_multiprocessing"], sliding_window=args["sliding_window"], flatten=not evaluate, stride=args["stride"], ) if verbose and args["sliding_window"]: logger.info(f" {len(features)} features created from {len(examples)} samples.") if not no_cache: torch.save(features, cached_features_file) if args["sliding_window"] and evaluate: window_counts = [len(sample) for sample in features] features = [feature for feature_set in features for feature in feature_set] all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long) all_segment_ids = torch.tensor([f.segment_ids for f in features], dtype=torch.long) if output_mode == "classification": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long) elif output_mode == "regression": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) dataset = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids) if args["sliding_window"] and evaluate: return dataset, window_counts else: return dataset def compute_metrics(self, preds, labels, eval_examples, multi_label=False, **kwargs): """ Computes the evaluation metrics for the model predictions. Args: preds: Model predictions labels: Ground truth labels eval_examples: List of examples on which evaluation was performed **kwargs: Additional metrics that should be used. Pass in the metrics as keyword arguments (name of metric: function to use). E.g. f1=sklearn.metrics.f1_score. A metric function should take in two parameters. The first parameter will be the true labels, and the second parameter will be the predictions. Returns: result: Dictionary containing evaluation results. (Matthews correlation coefficient, tp, tn, fp, fn) wrong: List of InputExample objects corresponding to each incorrect prediction by the model """ # noqa: ignore flake8" assert len(preds) == len(labels) extra_metrics = {} for metric, func in kwargs.items(): extra_metrics[metric] = func(labels, preds) mismatched = labels != preds wrong = [i for (i, v) in zip(eval_examples, mismatched) if v.any()] if multi_label: label_ranking_score = label_ranking_average_precision_score(labels, preds) return {**{"LRAP": label_ranking_score}, **extra_metrics}, wrong elif self.args["regression"]: return {**extra_metrics}, wrong mcc = matthews_corrcoef(labels, preds) if self.model.num_labels == 2: tn, fp, fn, tp = confusion_matrix(labels, preds, labels=[0, 1]).ravel() return ( {**{"mcc": mcc, "tp": tp, "tn": tn, "fp": fp, "fn": fn}, **extra_metrics}, wrong, ) else: return {**{"mcc": mcc}, **extra_metrics}, wrong def predict(self, to_predict, multi_label=False): """ Performs predictions on a list of text. Args: to_predict: A python list of text (str) to be sent to the model for prediction. Returns: preds: A python list of the predictions (0 or 1) for each text. model_outputs: A python list of the raw model outputs for each text. """ device = self.device model = self.model args = self.args self._move_model_to_device() if multi_label: eval_examples = [ InputExample(i, text, None, [0 for i in range(self.num_labels)]) for i, text in enumerate(to_predict) ] else: if isinstance(to_predict[0], list): eval_examples = [InputExample(i, text[0], text[1], 0) for i, text in enumerate(to_predict)] else: eval_examples = [InputExample(i, text, None, 0) for i, text in enumerate(to_predict)] if args["sliding_window"]: eval_dataset, window_counts = self.load_and_cache_examples(eval_examples, evaluate=True, no_cache=True) else: eval_dataset = self.load_and_cache_examples( eval_examples, evaluate=True, multi_label=multi_label, no_cache=True ) eval_sampler = SequentialSampler(eval_dataset) eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args["eval_batch_size"]) eval_loss = 0.0 nb_eval_steps = 0 preds = None out_label_ids = None if self.config.output_hidden_states: for batch in tqdm(eval_dataloader, disable=args["silent"]): model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] embedding_outputs, layer_hidden_states = outputs[2][0], outputs[2][1:] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() all_layer_hidden_states = [state.detach().cpu().numpy() for state in layer_hidden_states] all_embedding_outputs = embedding_outputs.detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) all_layer_hidden_states = np.append( [state.detach().cpu().numpy() for state in layer_hidden_states], axis=0 ) all_embedding_outputs = np.append(embedding_outputs.detach().cpu().numpy(), axis=0) else: for batch in tqdm(eval_dataloader, disable=args["silent"]): model.eval() batch = tuple(t.to(device) for t in batch) with torch.no_grad(): inputs = self._get_inputs_dict(batch) outputs = model(**inputs) tmp_eval_loss, logits = outputs[:2] if multi_label: logits = logits.sigmoid() eval_loss += tmp_eval_loss.mean().item() nb_eval_steps += 1 if preds is None: preds = logits.detach().cpu().numpy() out_label_ids = inputs["labels"].detach().cpu().numpy() else: preds = np.append(preds, logits.detach().cpu().numpy(), axis=0) out_label_ids = np.append(out_label_ids, inputs["labels"].detach().cpu().numpy(), axis=0) eval_loss = eval_loss / nb_eval_steps if args["sliding_window"]: count = 0 window_ranges = [] for n_windows in window_counts: window_ranges.append([count, count + n_windows]) count += n_windows preds = [preds[window_range[0] : window_range[1]] for window_range in window_ranges] model_outputs = preds preds = [np.argmax(pred, axis=1) for pred in preds] final_preds = [] for pred_row in preds: mode_pred, counts = mode(pred_row) if len(counts) > 1 and counts[0] == counts[1]: final_preds.append(args["tie_value"]) else: final_preds.append(mode_pred[0]) preds = np.array(final_preds) elif not multi_label and args["regression"] is True: preds = np.squeeze(preds) model_outputs = preds else: model_outputs = preds if multi_label: if isinstance(args["threshold"], list): threshold_values = args["threshold"] preds = [ [self._threshold(pred, threshold_values[i]) for i, pred in enumerate(example)] for example in preds ] else: preds = [[self._threshold(pred, args["threshold"]) for pred in example] for example in preds] else: preds = np.argmax(preds, axis=1) if self.config.output_hidden_states: return preds, model_outputs, all_embedding_outputs, all_layer_hidden_states else: return preds, model_outputs def _threshold(self, x, threshold): if x >= threshold: return 1 return 0 def _move_model_to_device(self): self.model.to(self.device) def _get_inputs_dict(self, batch): inputs = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} # XLM, DistilBERT and RoBERTa don't use segment_ids if self.args["model_type"] != "distilbert": inputs["token_type_ids"] = batch[2] if self.args["model_type"] in ["bert", "xlnet", "albert"] else None return inputs def _get_last_metrics(self, metric_values): return {metric: values[-1] for metric, values in metric_values.items()} def _create_training_progress_scores(self, multi_label, **kwargs): extra_metrics = {key: [] for key in kwargs} if multi_label: training_progress_scores = { "global_step": [], "LRAP": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: if self.model.num_labels == 2: training_progress_scores = { "global_step": [], "tp": [], "tn": [], "fp": [], "fn": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } elif self.model.num_labels == 1: training_progress_scores = { "global_step": [], "train_loss": [], "eval_loss": [], **extra_metrics, } else: training_progress_scores = { "global_step": [], "mcc": [], "train_loss": [], "eval_loss": [], **extra_metrics, } return training_progress_scores def _save_model(self, output_dir=None, optimizer=None, scheduler=None, model=None, results=None): if not output_dir: output_dir = self.args["output_dir"] os.makedirs(output_dir, exist_ok=True) if model and not self.args["no_save"]: # Take care of distributed/parallel training model_to_save = model.module if hasattr(model, "module") else model model_to_save.save_pretrained(output_dir) self.tokenizer.save_pretrained(output_dir) torch.save(self.args, os.path.join(output_dir, "training_args.bin")) if optimizer and scheduler: torch.save(optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt")) torch.save(scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt")) self._save_model_args(output_dir) if results: output_eval_file = os.path.join(output_dir, "eval_results.txt") with open(output_eval_file, "w") as writer: for key in sorted(results.keys()): writer.write("{} = {}\n".format(key, str(results[key]))) def _save_model_args(self, output_dir): os.makedirs(output_dir, exist_ok=True) with open(os.path.join(output_dir, "model_args.json"), "w") as f: json.dump(self.args, f) def _load_model_args(self, input_dir): model_args_file = os.path.join(input_dir, "model_args.json") if os.path.isfile(model_args_file): with open(model_args_file, "r") as f: model_args = json.load(f) return model_args
# Constellation Control Server # A centralized server for controlling museum exhibit components # Written by Morgan Rehnberg, Fort Worth Museum of Science and History # Released under the MIT license # Standard modules from http.server import HTTPServer, SimpleHTTPRequestHandler from socketserver import ThreadingMixIn import logging import datetime import configparser import json import os import mimetypes import cgi import signal import socket import sys import shutil import traceback import threading import pickle import urllib.request import time import re # Non-standard modules import dateutil.parser # Constellation modules import config import constellation_exhibit as c_exhibit import constellation_issues as c_issues import constellation_maintenance as c_maint import constellation_projector as c_proj import constellation_schedule as c_sched import constellation_tracker as c_track class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Stub which triggers dispatch of requests into individual threads.""" daemon_threads = True class RequestHandler(SimpleHTTPRequestHandler): """Handle incoming requests to the control server""" def send_current_configuration(self, id_): """Function to respond to a POST with a dictionary defining the current exhibit configuration""" json_string = json.dumps(c_exhibit.get_exhibit_component(id_).config) if len(c_exhibit.get_exhibit_component(id_).config["commands"]) > 0: # Clear the command list now that we have sent c_exhibit.get_exhibit_component(id_).config["commands"] = [] self.wfile.write(bytes(json_string, encoding="UTF-8")) def send_webpage_update(self): """Function to collect the current exhibit status, format it, and send it back to the web client to update the page""" component_dict_list = [] for item in config.componentList: temp = {"id": item.id, "type": item.type} if "content" in item.config: temp["content"] = item.config["content"] if "error" in item.config: temp["error"] = item.config["error"] if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] if "AnyDeskID" in item.config: temp["AnyDeskID"] = item.config["AnyDeskID"] temp["class"] = "exhibitComponent" temp["status"] = item.current_status() temp["ip_address"] = item.ip temp["helperPort"] = item.helperPort temp["helperAddress"] = item.helperAddress component_dict_list.append(temp) for item in config.projectorList: temp = {"id": item.id, "type": 'PROJECTOR', "ip_address": item.ip} if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] temp["class"] = "exhibitComponent" temp["status"] = item.state["status"] component_dict_list.append(temp) for item in config.wakeOnLANList: temp = {"id": item.id, "type": 'WAKE_ON_LAN', "ip_address": item.ip} if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] temp["class"] = "exhibitComponent" temp["status"] = item.state["status"] component_dict_list.append(temp) # Also include an object with the status of the overall gallery temp = {"class": "gallery", "currentExhibit": config.currentExhibit, "availableExhibits": config.exhibit_list, "galleryName": gallery_name, "updateAvailable": str(software_update_available).lower()} component_dict_list.append(temp) # Also include an object containing the current issues temp = {"class": "issues", "issueList": [x.details for x in config.issueList], "lastUpdateDate": config.issueList_last_update_date, "assignable_staff": config.assignable_staff} component_dict_list.append(temp) # Also include an object containing the current schedule with config.scheduleLock: temp = {"class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} component_dict_list.append(temp) json_string = json.dumps(component_dict_list, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) def log_request(self, code='-', size='-'): # Override to suppress the automatic logging pass def copy_byte_range(self, infile, start=None, stop=None, bufsize=16 * 1024): """Like shutil.copyfileobj, but only copy a range of the streams. Both start and stop are inclusive. """ if start is not None: infile.seek(start) while 1: to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize) buf = infile.read(to_read) if not buf: break self.wfile.write(buf) def handle_range_request(self, f): """Handle a GET request using a byte range. Inspired by https://github.com/danvk/RangeHTTPServer """ try: self.range = parse_byte_range(self.headers['Range']) except ValueError: self.send_error(400, 'Invalid byte range') return first, last = self.range fs = os.fstat(f.fileno()) file_len = fs[6] if first >= file_len: self.send_error(416, 'Requested Range Not Satisfiable') return None ctype = self.guess_type(self.translate_path(self.path)) if last is None or last >= file_len: last = file_len - 1 response_length = last - first + 1 try: self.send_response(206) self.send_header('Content-type', ctype) self.send_header('Accept-Ranges', 'bytes') self.send_header('Content-Range', 'bytes %s-%s/%s' % (first, last, file_len)) self.send_header('Content-Length', str(response_length)) self.send_header('Last-Modified', self.date_time_string(fs.st_mtime)) self.end_headers() self.copy_byte_range(f) except IOError as e: print(e) def do_GET(self): # Receive a GET request and respond with a console webpage # print("+++++++++++++++") # print("BEGIN GET") print(f" Active threads: {threading.active_count()} ", end="\r", flush=True) # print(f" path = {self.path}") # Strip out any options from the query string self.path = self.path.split("?")[0] if self.path.lower().endswith("html") or self.path == "/": if self.path == "/": file_path = os.path.join(config.APP_PATH, "webpage.html") if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, "webpage.html") f = open(file_path, "r", encoding='UTF-8') else: if self.path.startswith("/"): self.path = self.path[1:] file_path = os.path.join(config.APP_PATH, self.path) if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, self.path) f = open(file_path, "r", encoding='UTF-8') page = str(f.read()) # Build the address that the webpage should contact to reach this server address_to_insert = "'http://" + str(ip_address) + ":" + str(server_port) + "'" # Then, insert that into the document page = page.replace("INSERT_SERVERIP_HERE", address_to_insert) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(page, encoding="UTF-8")) f.close() # print("END GET") # print("+++++++++++++++") return else: # Open the file requested and send it mimetype = mimetypes.guess_type(self.path, strict=False)[0] if self.path[0] == '/': # Strip out leading /, as it screws up os.path.join self.path = self.path[1:] try: file_path = os.path.join(config.APP_PATH, self.path) if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, self.path) with open(file_path, 'rb') as f: if "Range" in self.headers: self.handle_range_request(f) else: try: self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() # print(f" Writing data to client") self.wfile.write(f.read()) except BrokenPipeError: print("Connection closed prematurely") # print("END GET") # print("+++++++++++++++") return except IOError: self.send_error(404, f"File Not Found: {self.path}") with config.logLock: logging.error("GET for unexpected file %s", self.path) # print("END GET") # print("+++++++++++++++") def do_OPTIONS(self): """Respond to an OPTIONS request""" # print("---------------") # print("BEGIN OPTIONS") self.send_response(200, "OK") self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization') self.send_header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') self.send_header('Access-Control-Allow-Credentials', 'true') self.end_headers() # print("END OPTIONS") # print("---------------") def do_POST(self): """Receives pings from client devices and respond with any updated information""" # print("===============") # print("BEGIN POST") print(f" Active threads: {threading.active_count()} ", end="\r", flush=True) self.send_response(200, "OK") self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization') self.send_header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') self.send_header('Access-Control-Allow-Credentials', 'true') self.end_headers() # Get the data from the request try: ctype, pdict = cgi.parse_header(self.headers.get('content-type')) except: print("DO_POST: Error: Are we missing the Content-Type header?") with config.logLock: logging.warning("POST received without content-type header") print(self.headers) return if ctype == "multipart/form-data": # File upload try: pdict['boundary'] = bytes(pdict['boundary'], "utf-8") content_len = int(self.headers.get('Content-length')) pdict['CONTENT-LENGTH'] = content_len fields = cgi.parse_multipart(self.rfile, pdict) file = fields.get('file')[0] action = fields.get("action")[0] if action == "uploadIssueMedia": content_path = os.path.join(config.APP_PATH, "issues", "media") _, extension = os.path.splitext(fields.get("filename")[0]) # Create a new filename so we never have collisions new_filename = str(time.time()).replace(".", "") + extension filepath = os.path.join(content_path, new_filename) print(f"Saving uploaded file to {filepath}") with config.issueMediaLock: with open(filepath, "wb") as f: f.write(file) else: print("Unknown file upload action:", action) return json_string = json.dumps({"success": True, "filename": new_filename}) except: json_string = json.dumps({"success": False}) try: self.wfile.write(bytes(json_string, encoding="UTF-8")) except BrokenPipeError: pass elif ctype == "application/json": # print(" application/json") # Unpack the data length = int(self.headers['Content-length']) data_str = self.rfile.read(length).decode("utf-8") try: # JSON data = json.loads(data_str) except json.decoder.JSONDecodeError: # not JSON data = {} split = data_str.split("&") for seg in split: split2 = seg.split("=") data[split2[0]] = split2[1] try: ping_class = data["class"] except KeyError: print("Error: ping received without class field") response = {"success": False, "reason": "Request missing 'class' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return # print(f" class = {ping_class}") if ping_class == "webpage": try: action = data["action"] except KeyError: print("Error: webpage ping received without action field") # print("END POST") # print("===============") response = {"success": True, "reason": "Missing required field 'action'."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return # print(f" action = {action}") if action == "fetchUpdate": self.send_webpage_update() elif action == "fetchProjectorUpdate": if "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id'.", "status": None} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return proj = c_proj.get_projector(data["id"]) if proj is not None: response_dict = {"success": True, "state": proj.state} else: response_dict = {"success": False, "reason": f"Projector {data["id"]} does not exist", "status": "DELETE"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "reloadConfiguration": load_default_configuration() json_string = json.dumps({"success": True}) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "queueCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_exhibit.get_exhibit_component(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "queueProjectorCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_proj.get_projector(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "queueWOLCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_exhibit.get_wake_on_LAN_component(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "updateSchedule": # This command handles both adding a new scheduled action # and editing an existing action if "name" not in data or "timeToSet" not in data or "actionToSet" not in data or "targetToSet" not in data or "isAddition" not in data: response_dict = {"success": False, "reason": "Missing one or more required keys"} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) return try: time_to_set = dateutil.parser.parse(data['timeToSet']).time() except dateutil.parser._parser.ParserError: response_dict = {"success": False, "reason": "Unknown date format"} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) return error = False error_message = "" line_to_set = f"{data["timeToSet"]} = {data["actionToSet"]}" if data["targetToSet"] is None: line_to_set += "\n" else: line_to_set += f", {data["targetToSet"]}\n" sched_dir = os.path.join(config.APP_PATH, "schedules") path = os.path.join(sched_dir, data["name"] + ".ini") if data["isAddition"]: # Check if this time already exists error = c_sched.check_if_schedule_time_exists(path, time_to_set) if not error: with config.scheduleLock: with open(path, 'a', encoding="UTF-8") as f: f.write(line_to_set) else: error_message = "An action with this time already exists" elif "timeToReplace" in data: output_text = "" time_to_replace = dateutil.parser.parse(data['timeToReplace']).time() print("replacing schedule", time_to_replace, time_to_set, c_sched.check_if_schedule_time_exists(path, time_to_set)) # We need to make sure we are not editing this entry to have # the same time as another entry if time_to_set == time_to_replace: okay_to_edit = True else: okay_to_edit = not c_sched.check_if_schedule_time_exists(path, time_to_set) if okay_to_edit: with config.scheduleLock: # Iterate the file to replace the line we are changing with open(path, 'r', encoding='UTF-8') as f: for line in f.readlines(): split = line.split("=") if len(split) == 2: # We have a valid ini line if dateutil.parser.parse(split[0]).time() != time_to_replace: # This line doesn't match, so keep it as is output_text += line else: output_text += line_to_set else: output_text += line with open(path, 'w', encoding='UTF-8') as f: f.write(output_text) else: error = True error_message = "An action with this time already exists" response_dict = {} if not error: # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict["class"] = "schedule" response_dict["updateTime"] = config.scheduleUpdateTime response_dict["schedule"] = config.scheduleList response_dict["nextEvent"] = config.nextEvent response_dict["success"] = True else: response_dict["success"] = False response_dict["reason"] = error_message json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == 'refreshSchedule': # This command reloads the schedule from disk. Normal schedule # changes are passed during fetchUpdate c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "convertSchedule": if "date" not in data or "from" not in data: response = {"success": False, "reason": "Request missing 'date' or 'from' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return sched_dir = os.path.join(config.APP_PATH, "schedules") with config.scheduleLock: shutil.copy(os.path.join(sched_dir, data["from"].lower() + ".ini"), os.path.join(sched_dir, data["date"] + ".ini")) # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "deleteSchedule": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return with config.scheduleLock: sched_dir = os.path.join(config.APP_PATH, "schedules") os.remove(os.path.join(sched_dir, data["name"] + ".ini")) # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "deleteScheduleAction": if "from" not in data or "time" not in data: response = {"success": False, "reason": "Request missing 'from' or 'time' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return c_sched.delete_schedule_action(data["from"], data["time"]) c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "setExhibit": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return print("Changing exhibit to:", data["name"]) c_exhibit.read_exhibit_configuration(data["name"], update_default=True) # Update the components that the configuration has changed for component in config.componentList: component.update_configuration() response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "createExhibit": if "name" not in data or data["name"] == "": response = {"success": False, "reason": "Request missing 'name' field or name is blank."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return clone = None if "cloneFrom" in data and data["cloneFrom"] != "": clone = data["cloneFrom"] c_exhibit.create_new_exhibit(data["name"], clone) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "deleteExhibit": if "name" not in data or data["name"] == "": response = {"success": False, "reason": "Request missing 'name' field or name is empty."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return c_exhibit.delete_exhibit(data["name"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "setComponentContent": if "id" not in data or "content" not in data: response = {"success": False, "reason": "Request missing 'id' or 'content' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return content_to_set = data["content"] print(f"Changing content for {data["id"]}:", content_to_set) if not isinstance(content_to_set, list): content_to_set = [data["content"]] c_exhibit.set_component_content(data['id'], content_to_set) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "getHelpText": try: readme_path = os.path.join(config.APP_PATH, "README.md") with open(readme_path, 'r', encoding='UTF-8') as f: text = f.read() self.wfile.write(bytes(text, encoding="UTF-8")) except FileNotFoundError: with config.logLock: logging.error("Unable to read README.md") elif action == "createIssue": if "details" in data: with config.issueLock: new_issue = c_issues.Issue(data["details"]) config.issueList.append(new_issue) c_issues.save_issueList() response_dict = {"success": True} else: response_dict = {"success": False, "reason": "Must include field 'details'"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "editIssue": if "details" in data and "id" in data["details"]: c_issues.edit_issue(data["details"]) c_issues.save_issueList() response_dict = {"success": True} else: response_dict = { "success": False, "reason": "Must include field 'details' with property 'id'" } self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "deleteIssue": if "id" in data: c_issues.remove_issue(data["id"]) c_issues.save_issueList() response_dict = {"success": True, "reason": ""} else: response_dict = {"success": False, "reason": "Must include field 'id'"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "getIssueList": response = { "success": True, "issueList": [x.details for x in config.issueList] } self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "issueMediaDelete": if "filename" not in data: response = {"success": False, "reason": "Request missing 'filename' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return this_id = None if "id" in data: this_id = data["id"] c_issues.delete_issue_media_file(data["filename"], owner=this_id) response = {"success": True} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == 'updateMaintenanceStatus': if "id" not in data or "status" not in data or "notes" not in data: response = {"success": False, "reason": "Request missing 'id', 'status', or 'notes' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") record = {"id": data["id"], "date": datetime.datetime.now().isoformat(), "status": data['status'], "notes": data["notes"]} with config.maintenanceLock: try: with open(file_path, 'a', encoding='UTF-8') as f: f.write(json.dumps(record) + "\n") success = True reason = "" except FileNotFoundError: success = False reason = f"File path {file_path} does not exist" except PermissionError: success = False reason = f"You do not have write permission for the file {file_path}" response_dict = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == 'deleteMaintenanceRecord': if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return else: file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") with config.maintenanceLock: response = delete_file(file_path) self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == 'getMaintenanceStatus': if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") with config.maintenanceLock: response_dict = c_maint.get_maintenance_report(file_path) self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "getAllMaintenanceStatuses": record_list = [] maintenance_path = os.path.join(config.APP_PATH, "maintenance-logs") for file in os.listdir(maintenance_path): if file.lower().endswith(".txt"): with config.maintenanceLock: file_path = os.path.join(maintenance_path, file) record_list.append(c_maint.get_maintenance_report(file_path)) response_dict = {"success": True, "records": record_list} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) else: print(f"Error: Unknown webpage command received: {action}") with config.logLock: logging.error(f"Unknown webpage command received: {action}") elif ping_class == "exhibitComponent": if "action" in data: # not a ping action = data["action"] # if "id" in data: # print(f" id = {data["id"]}") # print(f" action = {action}") if action == "getUploadedFile": if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return component = c_exhibit.get_exhibit_component(data["id"]) if len(component.dataToUpload) > 0: upload = component.dataToUpload.pop(0) # json_string = json.dumps(upload) # self.wfile.write(bytes(json_string, encoding="UTF-8")) self.wfile.write(upload) elif action == "beginSynchronization": if "synchronizeWith" in data: c_exhibit.update_synchronization_list(data["id"], data["synchronizeWith"]) else: # it's a ping try: id = data["id"] # type = data["type"] if id == "UNKNOWN": print(f"Warning: exhibitComponent ping with id=UNKNOWN coming from {self.address_string()}") self.wfile.write(bytes(json.dumps({}), encoding='UTF-8')) # print("END POST") # print("===============") return except KeyError: print("Error: exhibitComponent ping received without id or type field") # print("END POST") # print("===============") return # No id or type, so bail out # print(f" id = {id}") # print(" action = ping") c_exhibit.update_exhibit_component_status(data, self.address_string()) self.send_current_configuration(id) elif ping_class == "tracker": if "action" not in data: response = {"success": False, "reason": "Request missing 'action' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return action = data["action"] if action == "getLayoutDefinition": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") layout_definition, success, reason = c_track.get_layout_definition(data["name"] + ".ini", kind=kind) response = {"success": success, "reason": reason, "layout": layout_definition} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitData": if "data" not in data or "name" not in data: response = {"success": False, "reason": "Request missing 'data' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") file_path = os.path.join(config.APP_PATH, kind, "data", data["name"] + ".txt") success, reason = c_track.write_JSON(data["data"], file_path) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitRawText": if "text" not in data or "name" not in data: response = {"success": False, "reason": "Request missing 'text' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") success, reason = c_track.write_raw_text(data["text"], data["name"] + ".txt", kind) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "retrieveRawText": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") result, success, reason = c_track.get_raw_text(data["name"] + ".txt", kind) response = {"success": success, "reason": reason, "text": result} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitAnalytics": if "data" not in data or 'name' not in data: response = {"success": False, "reason": "Request missing 'data' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "analytics", data["name"] + ".txt") success, reason = c_track.write_JSON(data["data"], file_path) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "getAvailableDefinitions": kind = data.get("kind", "flexible-tracker") definition_list = [] template_path = os.path.join(config.APP_PATH, kind, "templates") for file in os.listdir(template_path): if file.lower().endswith(".ini"): definition_list.append(file) self.wfile.write(bytes(json.dumps(definition_list), encoding="UTF-8")) elif action == "downloadTrackerData": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".txt"): name += ".txt" data_path = os.path.join(config.APP_PATH, kind, "data", name) result = c_track.create_CSV(data_path) response = {"success": True, "csv": result} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "clearTrackerData": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".txt"): name += ".txt" data_path = os.path.join(config.APP_PATH, kind, "data", name) success = True reason = "" with config.trackingDataWriteLock: try: os.remove(data_path) except PermissionError: success = False reason = f"You do not have write permission for the file {data_path}" except FileNotFoundError: success = True # This error results in the user's desired action! reason = f"File does not exist: {data_path}" if reason != "": print(reason) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "createTemplate": if "name" not in data or "template" not in data: response = {"success": False, "reason": "Request missing 'name' or 'template' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".ini"): name += ".ini" file_path = os.path.join(config.APP_PATH, kind, "templates", name) success = c_track.create_template(file_path, data["template"]) response = {"success": success} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "deleteTemplate": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") file_path = os.path.join(config.APP_PATH, kind, "templates", data["name"] + ".ini") with config.trackerTemplateWriteLock: response = delete_file(file_path) self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "checkConnection": self.wfile.write(bytes(json.dumps({"success": True}), encoding="UTF-8")) else: print(f"Error: ping with unknown class '{ping_class}' received") response = {"success": False, "reason": f"Unknown class {ping_class}"} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) # print("END POST") # print("===============") return # print("END POST") # print("===============") def delete_file(file_path) -> dict: """Delete the specified file and return a dictionary with the result""" response = {"success": False} try: os.remove(file_path) response["success"] = True except FileNotFoundError: response["reason"] = f"File {file_path} does not exist" except PermissionError: response["reason"] = f"You do not have permission for the file f{file_path}" return response def parse_byte_range(byte_range): """Returns the two numbers in 'bytes=123-456' or throws ValueError. The last number or both numbers may be None. """ BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$') if byte_range.strip() == '': return None, None m = BYTE_RANGE_RE.match(byte_range) if not m: raise ValueError(f'Invalid byte range {byte_range}') first, last = [x and int(x) for x in m.groups()] if last and last < first: raise ValueError(f'Invalid byte range {byte_range}') return first, last def clear_terminal(): """Clear the terminal""" os.system('cls' if os.name == 'nt' else 'clear') def command_line_setup(): """Prompt the user for several pieces of information on first-time setup""" settings_dict = {} clear_terminal() print("##########################################################") print("Welcome to Constellation Control Server!") print("") print("This appears to be your first time running Control Server.") print("In order to set up your configuration, you will be asked") print("a few questions. If you don't know the answer, or wish to") print("accept the default, just press the enter key.") print("") gallery_name = input("Enter a name for the gallery (default: Constellation): ").strip() if gallery_name == "": gallery_name = "Constellation" settings_dict["gallery_name"] = gallery_name default_ip = socket.gethostbyname(socket.gethostname()) ip_address = input(f"Enter this computer's static IP address (default: {default_ip}): ").strip() if ip_address == "": ip_address = default_ip settings_dict["ip_address"] = ip_address default_port = 8082 while True: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: if s.connect_ex((ip_address, default_port)) != 0: # Port is free break else: default_port += 1 port = input(f"Enter the desired port (default: {default_port}): ").strip() if port == "": port = default_port else: port = int(port) settings_dict["server_port"] = port settings_dict["current_exhibit"] = "default.exhibit" return {"CURRENT": settings_dict} def load_default_configuration(): """Read the current exhibit configuration from file and initialize it""" global server_port global ip_address global gallery_name # First, retrieve the config filename that defines the desired gallery config_reader = configparser.ConfigParser(delimiters="=") config_reader.optionxform = str # Override default, which is case in-sensitive gal_path = os.path.join(config.APP_PATH, "galleryConfiguration.ini") with config.galleryConfigurationLock: config_reader.read(gal_path) try: current = config_reader["CURRENT"] except KeyError: # We don't have a config file, so let's get info from the user to create one settings_dict = command_line_setup() config_reader.read_dict(settings_dict) with open(os.path.join(config.APP_PATH, "galleryConfiguration.ini"), "w", encoding="UTF-8") as f: config_reader.write(f) current = config_reader["CURRENT"] server_port = current.getint("server_port", 8080) ip_address = current.get("server_ip_address", socket.gethostbyname(socket.gethostname())) gallery_name = current.get("gallery_name", "Constellation") staff_list = current.get("assignable_staff", []) if len(staff_list) > 0: config.assignable_staff = [x.strip() for x in staff_list.split(",")] c_sched.retrieve_schedule() config.projectorList = [] # Load the component descriptions. Do this first, so they are available when # creating the various components try: print("Reading component descriptions...", end="", flush=True) config.componentDescriptions = dict(config_reader["COMPONENT_DESCRIPTIONS"]) print(" done") except KeyError: print("None found") config.componentDescriptions = {} # Parse list of PJLink projectors try: pjlink_projectors = config_reader["PJLINK_PROJECTORS"] print("Connecting to PJLink projectors...", end="\r", flush=True) except KeyError: print("No PJLink projectors specified") pjlink_projectors = [] n_proj = len(pjlink_projectors) cur_proj = 0 for key in pjlink_projectors: cur_proj += 1 print(f"Connecting to PJLink projectors... {cur_proj}/{n_proj}", end="\r", flush=True) if c_proj.get_projector(key) is None: # Try to split on a comma. If we get two elements back, that means # we have the form "ip, password" split = pjlink_projectors[key].split(",") if len(split) == 2: # We have an IP address and a password ip = split[0].strip() password = split[1].strip() if password == "": password = None new_proj = c_proj.Projector(key, ip, "pjlink", password=password) elif len(split) == 1: # We have an IP address only new_proj = c_proj.Projector(key, pjlink_projectors[key], "pjlink") else: print("Invalid PJLink projector entry:", pjlink_projectors[key]) break config.projectorList.append(new_proj) print("Connecting to PJLink projectors... done ") # Parse list of serial projectors try: serial_projectors = config_reader["SERIAL_PROJECTORS"] print("Connecting to serial projectors...", end="\r", flush=True) except KeyError: print("No serial projectors specified") serial_projectors = [] n_proj = len(serial_projectors) cur_proj = 0 for key in serial_projectors: cur_proj += 1 print(f"Connecting to serial projectors... {cur_proj}/{n_proj}", end="\r", flush=True) if c_proj.get_projector(key) is None: # Try to split on a comma. If we get two elements back, that means # we have the form "ip, password" split = serial_projectors[key].split(",") if len(split) == 2: # We have an IP address and a make ip = split[0].strip() make = split[1].strip() if make == "": make = None new_proj = c_proj.Projector(key, ip, "serial", make=make) elif len(split) == 1: # We have an IP address only new_proj = c_proj.Projector(key, serial_projectors[key], "serial") else: print("Invalid serial projector entry:", serial_projectors[key]) break config.projectorList.append(new_proj) print("Connecting to serial projectors... done ") # Parse list of Wake on LAN devices try: wol = config_reader["WAKE_ON_LAN"] print("Collecting Wake on LAN devices...", end="", flush=True) for key in wol: if c_exhibit.get_exhibit_component(key) is None: # If 'get_exhibit_component' is not None, this key corresponds # to a WoL device with a matching exhibit component ID and # we have already loaded that component from the pickle file value_split = wol[key].split(",") if len(value_split) == 2: # We have been given a MAC address and IP address device = c_exhibit.WakeOnLANDevice(key, value_split[0].strip(), ip_address=value_split[1].strip()) elif len(value_split) == 1: # We have been given only a MAC address device = c_exhibit.WakeOnLANDevice(key, value_split[0].strip()) else: print(f"Wake on LAN device specified with unknown format: {wol[key]}") continue config.wakeOnLANList.append(device) print(" done") except KeyError: print("No wake on LAN devices specified") config.wakeOnLANList = [] # Build any existing issues try: issue_file = os.path.join(config.APP_PATH, "issues", "issues.json") with open(issue_file, "r", encoding="UTF-8") as file_object: issues = json.load(file_object) print("Reading stored issues...", end="", flush=True) for issue in issues: new_issue = c_issues.Issue(issue) config.issueList.append(new_issue) print(" done") except FileNotFoundError: print("No stored issues to read") # Parse list of static components try: static_components = config_reader["STATIC_COMPONENTS"] print("Adding static components... ", end="\r", flush=True) for this_type in static_components: split = static_components[this_type].split(",") for this_id in split: c_exhibit.add_exhibit_component(this_id.strip(), this_type, category="static") print("done") except KeyError: print("none specified") # Parse the reboot_time if necessary if "reboot_time" in current: reboot_time = dateutil.parser.parse(current["reboot_time"]) if reboot_time < datetime.datetime.now(): reboot_time += datetime.timedelta(days=1) config.serverRebootTime = reboot_time print("Server will reboot at:", config.serverRebootTime.isoformat()) # Then, load the configuration for that exhibit c_exhibit.read_exhibit_configuration(current["current_exhibit"]) # Update the components that the configuration has changed for component in config.componentList: component.update_configuration() def check_file_structure(): """Check to make sure we have the appropriate file structure set up""" schedules_dir = os.path.join(config.APP_PATH, "schedules") exhibits_dir = os.path.join(config.APP_PATH, "exhibits") misc_dirs = {"analytics": os.path.join(config.APP_PATH, "analytics"), "flexible-tracker": os.path.join(config.APP_PATH, "flexible-tracker"), "flexible-tracker/data": os.path.join(config.APP_PATH, "flexible-tracker", "data"), "flexible-tracker/templates": os.path.join(config.APP_PATH, "flexible-tracker", "templates"), "flexible-voter": os.path.join(config.APP_PATH, "flexible-voter"), "flexible-voter/data": os.path.join(config.APP_PATH, "flexible-voter", "data"), "flexible-voter/templates": os.path.join(config.APP_PATH, "flexible-voter", "templates"), "issues": os.path.join(config.APP_PATH, "issues"), "issues/media": os.path.join(config.APP_PATH, "issues", "media"), "maintenance-logs": os.path.join(config.APP_PATH, "maintenance-logs")} try: os.listdir(schedules_dir) except FileNotFoundError: print("Missing schedules directory. Creating now...") try: os.mkdir(schedules_dir) default_schedule_list = ["monday.ini", "tuesday.ini", "wednesday.ini", "thursday.ini", "friday.ini", "saturday.ini", "sunday.ini"] for file in default_schedule_list: with open(os.path.join(schedules_dir, file), 'w', encoding="UTF-8") as f: f.write("[SCHEDULE]\n") except PermissionError: print("Error: unable to create 'schedules' directory. Do you have write permission?") try: os.listdir(exhibits_dir) except FileNotFoundError: print("Missing exhibits directory. Creating now...") try: os.mkdir(exhibits_dir) with open(os.path.join(exhibits_dir, "default.exhibit"), 'w', encoding="UTF-8") as f: f.write("") except PermissionError: print("Error: unable to create 'exhibits' directory. Do you have write permission?") for key in misc_dirs: try: os.listdir(misc_dirs[key]) except FileNotFoundError: print(f"Missing {key} directory. Creating now...") try: os.mkdir(misc_dirs[key]) except PermissionError: print(f"Error: unable to create '{key}' directory. Do you have write permission?") def quit_handler(*args): """Handle cleanly shutting down the server""" try: if config.rebooting is True: exit_code = 1 print("\nRebooting server...") else: exit_code = 0 print('\nKeyboard interrupt detected. Cleaning up and shutting down...') except RuntimeError: exit_code = 0 # Save the current component lists to a pickle file so that # we can resume from the current state path_to_write = os.path.join(config.APP_PATH, "current_state.dat") with open(path_to_write, 'wb') as f: pickle.dump(config.componentList, f) for key in config.polling_thread_dict: config.polling_thread_dict[key].cancel() with config.logLock: logging.info("Server shutdown") with config.galleryConfigurationLock: with config.scheduleLock: with config.trackingDataWriteLock: sys.exit(exit_code) def error_handler(*exc_info): """Catch errors and log them to file""" text = "".join(traceback.format_exception(*exc_info)).replace('"', "'").replace("\n", "<newline>") with config.logLock: logging.error(f'"{text}"') print(f"Error: see control_server.log for more details ({datetime.datetime.now()})") def check_for_software_update(): """Download the version.txt file from GitHub and check if there is an update""" global software_update_available print("Checking for update... ", end="") try: for line in urllib.request.urlopen( "https://raw.githubusercontent.com/Cosmic-Chatter/Constellation/main/control_server/version.txt"): if float(line.decode('utf-8')) > SOFTWARE_VERSION: software_update_available = True break except urllib.error.HTTPError: print("cannot connect to update server") return if software_update_available: print("update available!") else: print("the server is up to date.") # Check whether we have packaged with Pyinstaller and set the appropriate root path. config.EXEC_PATH = os.path.dirname(os.path.abspath(__file__)) if getattr(sys, 'frozen', False): # If the application is run as a --onefile bundle, the PyInstaller bootloader # extends the sys module by a flag frozen=True and sets the app # path into variable sys.executable. config.APP_PATH = os.path.dirname(sys.executable) else: config.APP_PATH = config.EXEC_PATH server_port: int = 8080 # Default; should be set in currentExhibitConfiguration.ini ip_address: str = socket.gethostbyname(socket.gethostname()) # Default; should be set in galleryConfiguration.ini ADDR: str = "" # Accept connections from all interfaces gallery_name: str = "" SOFTWARE_VERSION = 1.0 software_update_available: bool = False # Set up log file log_path: str = os.path.join(config.APP_PATH, "control_server.log") logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', filename=log_path, format='%(levelname)s, %(asctime)s, %(message)s', level=logging.DEBUG) signal.signal(signal.SIGINT, quit_handler) sys.excepthook = error_handler with config.logLock: logging.info("Server started") # Try to reload the previous state from the pickle file current_state.dat try: state_path = os.path.join(config.APP_PATH, "current_state.dat") with open(state_path, "rb") as previous_state: config.componentList = pickle.load(previous_state) print("Previous server state loaded") except (FileNotFoundError, EOFError): print("Could not load previous server state") check_file_structure() c_exhibit.check_available_exhibits() load_default_configuration() c_sched.poll_event_schedule() c_proj.poll_projectors() c_exhibit.poll_wake_on_LAN_devices() check_for_software_update() httpd = ThreadedHTTPServer((ADDR, server_port), RequestHandler) httpd.serve_forever()
# Constellation Control Server # A centralized server for controlling museum exhibit components # Written by Morgan Rehnberg, Fort Worth Museum of Science and History # Released under the MIT license # Standard modules from http.server import HTTPServer, SimpleHTTPRequestHandler from socketserver import ThreadingMixIn import logging import datetime import configparser import json import os import mimetypes import cgi import signal import socket import sys import shutil import traceback import threading import pickle import urllib.request import time import re # Non-standard modules import dateutil.parser # Constellation modules import config import constellation_exhibit as c_exhibit import constellation_issues as c_issues import constellation_maintenance as c_maint import constellation_projector as c_proj import constellation_schedule as c_sched import constellation_tracker as c_track class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): """Stub which triggers dispatch of requests into individual threads.""" daemon_threads = True class RequestHandler(SimpleHTTPRequestHandler): """Handle incoming requests to the control server""" def send_current_configuration(self, id_): """Function to respond to a POST with a dictionary defining the current exhibit configuration""" json_string = json.dumps(c_exhibit.get_exhibit_component(id_).config) if len(c_exhibit.get_exhibit_component(id_).config["commands"]) > 0: # Clear the command list now that we have sent c_exhibit.get_exhibit_component(id_).config["commands"] = [] self.wfile.write(bytes(json_string, encoding="UTF-8")) def send_webpage_update(self): """Function to collect the current exhibit status, format it, and send it back to the web client to update the page""" component_dict_list = [] for item in config.componentList: temp = {"id": item.id, "type": item.type} if "content" in item.config: temp["content"] = item.config["content"] if "error" in item.config: temp["error"] = item.config["error"] if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] if "AnyDeskID" in item.config: temp["AnyDeskID"] = item.config["AnyDeskID"] temp["class"] = "exhibitComponent" temp["status"] = item.current_status() temp["ip_address"] = item.ip temp["helperPort"] = item.helperPort temp["helperAddress"] = item.helperAddress component_dict_list.append(temp) for item in config.projectorList: temp = {"id": item.id, "type": 'PROJECTOR', "ip_address": item.ip} if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] temp["class"] = "exhibitComponent" temp["status"] = item.state["status"] component_dict_list.append(temp) for item in config.wakeOnLANList: temp = {"id": item.id, "type": 'WAKE_ON_LAN', "ip_address": item.ip} if "allowed_actions" in item.config: temp["allowed_actions"] = item.config["allowed_actions"] if "description" in item.config: temp["description"] = item.config["description"] temp["class"] = "exhibitComponent" temp["status"] = item.state["status"] component_dict_list.append(temp) # Also include an object with the status of the overall gallery temp = {"class": "gallery", "currentExhibit": config.currentExhibit, "availableExhibits": config.exhibit_list, "galleryName": gallery_name, "updateAvailable": str(software_update_available).lower()} component_dict_list.append(temp) # Also include an object containing the current issues temp = {"class": "issues", "issueList": [x.details for x in config.issueList], "lastUpdateDate": config.issueList_last_update_date, "assignable_staff": config.assignable_staff} component_dict_list.append(temp) # Also include an object containing the current schedule with config.scheduleLock: temp = {"class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} component_dict_list.append(temp) json_string = json.dumps(component_dict_list, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) def log_request(self, code='-', size='-'): # Override to suppress the automatic logging pass def copy_byte_range(self, infile, start=None, stop=None, bufsize=16 * 1024): """Like shutil.copyfileobj, but only copy a range of the streams. Both start and stop are inclusive. """ if start is not None: infile.seek(start) while 1: to_read = min(bufsize, stop + 1 - infile.tell() if stop else bufsize) buf = infile.read(to_read) if not buf: break self.wfile.write(buf) def handle_range_request(self, f): """Handle a GET request using a byte range. Inspired by https://github.com/danvk/RangeHTTPServer """ try: self.range = parse_byte_range(self.headers['Range']) except ValueError: self.send_error(400, 'Invalid byte range') return first, last = self.range fs = os.fstat(f.fileno()) file_len = fs[6] if first >= file_len: self.send_error(416, 'Requested Range Not Satisfiable') return None ctype = self.guess_type(self.translate_path(self.path)) if last is None or last >= file_len: last = file_len - 1 response_length = last - first + 1 try: self.send_response(206) self.send_header('Content-type', ctype) self.send_header('Accept-Ranges', 'bytes') self.send_header('Content-Range', 'bytes %s-%s/%s' % (first, last, file_len)) self.send_header('Content-Length', str(response_length)) self.send_header('Last-Modified', self.date_time_string(fs.st_mtime)) self.end_headers() self.copy_byte_range(f) except IOError as e: print(e) def do_GET(self): # Receive a GET request and respond with a console webpage # print("+++++++++++++++") # print("BEGIN GET") print(f" Active threads: {threading.active_count()} ", end="\r", flush=True) # print(f" path = {self.path}") # Strip out any options from the query string self.path = self.path.split("?")[0] if self.path.lower().endswith("html") or self.path == "/": if self.path == "/": file_path = os.path.join(config.APP_PATH, "webpage.html") if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, "webpage.html") f = open(file_path, "r", encoding='UTF-8') else: if self.path.startswith("/"): self.path = self.path[1:] file_path = os.path.join(config.APP_PATH, self.path) if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, self.path) f = open(file_path, "r", encoding='UTF-8') page = str(f.read()) # Build the address that the webpage should contact to reach this server address_to_insert = "'http://" + str(ip_address) + ":" + str(server_port) + "'" # Then, insert that into the document page = page.replace("INSERT_SERVERIP_HERE", address_to_insert) self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() self.wfile.write(bytes(page, encoding="UTF-8")) f.close() # print("END GET") # print("+++++++++++++++") return else: # Open the file requested and send it mimetype = mimetypes.guess_type(self.path, strict=False)[0] if self.path[0] == '/': # Strip out leading /, as it screws up os.path.join self.path = self.path[1:] try: file_path = os.path.join(config.APP_PATH, self.path) if not os.path.isfile(file_path): # Handle the case of a Pyinstaller --onefile binary file_path = os.path.join(config.EXEC_PATH, self.path) with open(file_path, 'rb') as f: if "Range" in self.headers: self.handle_range_request(f) else: try: self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() # print(f" Writing data to client") self.wfile.write(f.read()) except BrokenPipeError: print("Connection closed prematurely") # print("END GET") # print("+++++++++++++++") return except IOError: self.send_error(404, f"File Not Found: {self.path}") with config.logLock: logging.error("GET for unexpected file %s", self.path) # print("END GET") # print("+++++++++++++++") def do_OPTIONS(self): """Respond to an OPTIONS request""" # print("---------------") # print("BEGIN OPTIONS") self.send_response(200, "OK") self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization') self.send_header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') self.send_header('Access-Control-Allow-Credentials', 'true') self.end_headers() # print("END OPTIONS") # print("---------------") def do_POST(self): """Receives pings from client devices and respond with any updated information""" # print("===============") # print("BEGIN POST") print(f" Active threads: {threading.active_count()} ", end="\r", flush=True) self.send_response(200, "OK") self.send_header("Access-Control-Allow-Origin", "*") self.send_header('Access-Control-Allow-Headers', 'Content-Type,Authorization') self.send_header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS') self.send_header('Access-Control-Allow-Credentials', 'true') self.end_headers() # Get the data from the request try: ctype, pdict = cgi.parse_header(self.headers.get('content-type')) except: print("DO_POST: Error: Are we missing the Content-Type header?") with config.logLock: logging.warning("POST received without content-type header") print(self.headers) return if ctype == "multipart/form-data": # File upload try: pdict['boundary'] = bytes(pdict['boundary'], "utf-8") content_len = int(self.headers.get('Content-length')) pdict['CONTENT-LENGTH'] = content_len fields = cgi.parse_multipart(self.rfile, pdict) file = fields.get('file')[0] action = fields.get("action")[0] if action == "uploadIssueMedia": content_path = os.path.join(config.APP_PATH, "issues", "media") _, extension = os.path.splitext(fields.get("filename")[0]) # Create a new filename so we never have collisions new_filename = str(time.time()).replace(".", "") + extension filepath = os.path.join(content_path, new_filename) print(f"Saving uploaded file to {filepath}") with config.issueMediaLock: with open(filepath, "wb") as f: f.write(file) else: print("Unknown file upload action:", action) return json_string = json.dumps({"success": True, "filename": new_filename}) except: json_string = json.dumps({"success": False}) try: self.wfile.write(bytes(json_string, encoding="UTF-8")) except BrokenPipeError: pass elif ctype == "application/json": # print(" application/json") # Unpack the data length = int(self.headers['Content-length']) data_str = self.rfile.read(length).decode("utf-8") try: # JSON data = json.loads(data_str) except json.decoder.JSONDecodeError: # not JSON data = {} split = data_str.split("&") for seg in split: split2 = seg.split("=") data[split2[0]] = split2[1] try: ping_class = data["class"] except KeyError: print("Error: ping received without class field") response = {"success": False, "reason": "Request missing 'class' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return # print(f" class = {ping_class}") if ping_class == "webpage": try: action = data["action"] except KeyError: print("Error: webpage ping received without action field") # print("END POST") # print("===============") response = {"success": True, "reason": "Missing required field 'action'."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return # print(f" action = {action}") if action == "fetchUpdate": self.send_webpage_update() elif action == "fetchProjectorUpdate": if "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id'.", "status": None} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return proj = c_proj.get_projector(data["id"]) if proj is not None: response_dict = {"success": True, "state": proj.state} else: response_dict = {"success": False, "reason": f"Projector {data['id']} does not exist", "status": "DELETE"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "reloadConfiguration": load_default_configuration() json_string = json.dumps({"success": True}) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "queueCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_exhibit.get_exhibit_component(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "queueProjectorCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_proj.get_projector(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "queueWOLCommand": if "command" not in data or "id" not in data: response_dict = {"success": False, "reason": "Missing required field 'id' or 'command'."} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) return c_exhibit.get_wake_on_LAN_component(data["id"]).queue_command(data["command"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "updateSchedule": # This command handles both adding a new scheduled action # and editing an existing action if "name" not in data or "timeToSet" not in data or "actionToSet" not in data or "targetToSet" not in data or "isAddition" not in data: response_dict = {"success": False, "reason": "Missing one or more required keys"} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) return try: time_to_set = dateutil.parser.parse(data['timeToSet']).time() except dateutil.parser._parser.ParserError: response_dict = {"success": False, "reason": "Unknown date format"} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) return error = False error_message = "" line_to_set = f"{data['timeToSet']} = {data['actionToSet']}" if data["targetToSet"] is None: line_to_set += "\n" else: line_to_set += f", {data['targetToSet']}\n" sched_dir = os.path.join(config.APP_PATH, "schedules") path = os.path.join(sched_dir, data["name"] + ".ini") if data["isAddition"]: # Check if this time already exists error = c_sched.check_if_schedule_time_exists(path, time_to_set) if not error: with config.scheduleLock: with open(path, 'a', encoding="UTF-8") as f: f.write(line_to_set) else: error_message = "An action with this time already exists" elif "timeToReplace" in data: output_text = "" time_to_replace = dateutil.parser.parse(data['timeToReplace']).time() print("replacing schedule", time_to_replace, time_to_set, c_sched.check_if_schedule_time_exists(path, time_to_set)) # We need to make sure we are not editing this entry to have # the same time as another entry if time_to_set == time_to_replace: okay_to_edit = True else: okay_to_edit = not c_sched.check_if_schedule_time_exists(path, time_to_set) if okay_to_edit: with config.scheduleLock: # Iterate the file to replace the line we are changing with open(path, 'r', encoding='UTF-8') as f: for line in f.readlines(): split = line.split("=") if len(split) == 2: # We have a valid ini line if dateutil.parser.parse(split[0]).time() != time_to_replace: # This line doesn't match, so keep it as is output_text += line else: output_text += line_to_set else: output_text += line with open(path, 'w', encoding='UTF-8') as f: f.write(output_text) else: error = True error_message = "An action with this time already exists" response_dict = {} if not error: # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict["class"] = "schedule" response_dict["updateTime"] = config.scheduleUpdateTime response_dict["schedule"] = config.scheduleList response_dict["nextEvent"] = config.nextEvent response_dict["success"] = True else: response_dict["success"] = False response_dict["reason"] = error_message json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == 'refreshSchedule': # This command reloads the schedule from disk. Normal schedule # changes are passed during fetchUpdate c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "convertSchedule": if "date" not in data or "from" not in data: response = {"success": False, "reason": "Request missing 'date' or 'from' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return sched_dir = os.path.join(config.APP_PATH, "schedules") with config.scheduleLock: shutil.copy(os.path.join(sched_dir, data["from"].lower() + ".ini"), os.path.join(sched_dir, data["date"] + ".ini")) # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "deleteSchedule": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return with config.scheduleLock: sched_dir = os.path.join(config.APP_PATH, "schedules") os.remove(os.path.join(sched_dir, data["name"] + ".ini")) # Reload the schedule from disk c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "deleteScheduleAction": if "from" not in data or "time" not in data: response = {"success": False, "reason": "Request missing 'from' or 'time' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return c_sched.delete_schedule_action(data["from"], data["time"]) c_sched.retrieve_schedule() # Send the updated schedule back with config.scheduleLock: response_dict = {"success": True, "class": "schedule", "updateTime": config.scheduleUpdateTime, "schedule": config.scheduleList, "nextEvent": config.nextEvent} json_string = json.dumps(response_dict, default=str) self.wfile.write(bytes(json_string, encoding="UTF-8")) elif action == "setExhibit": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return print("Changing exhibit to:", data["name"]) c_exhibit.read_exhibit_configuration(data["name"], update_default=True) # Update the components that the configuration has changed for component in config.componentList: component.update_configuration() response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "createExhibit": if "name" not in data or data["name"] == "": response = {"success": False, "reason": "Request missing 'name' field or name is blank."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return clone = None if "cloneFrom" in data and data["cloneFrom"] != "": clone = data["cloneFrom"] c_exhibit.create_new_exhibit(data["name"], clone) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "deleteExhibit": if "name" not in data or data["name"] == "": response = {"success": False, "reason": "Request missing 'name' field or name is empty."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return c_exhibit.delete_exhibit(data["name"]) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "setComponentContent": if "id" not in data or "content" not in data: response = {"success": False, "reason": "Request missing 'id' or 'content' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return content_to_set = data["content"] print(f"Changing content for {data['id']}:", content_to_set) if not isinstance(content_to_set, list): content_to_set = [data["content"]] c_exhibit.set_component_content(data['id'], content_to_set) response = {"success": True, "reason": ""} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "getHelpText": try: readme_path = os.path.join(config.APP_PATH, "README.md") with open(readme_path, 'r', encoding='UTF-8') as f: text = f.read() self.wfile.write(bytes(text, encoding="UTF-8")) except FileNotFoundError: with config.logLock: logging.error("Unable to read README.md") elif action == "createIssue": if "details" in data: with config.issueLock: new_issue = c_issues.Issue(data["details"]) config.issueList.append(new_issue) c_issues.save_issueList() response_dict = {"success": True} else: response_dict = {"success": False, "reason": "Must include field 'details'"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "editIssue": if "details" in data and "id" in data["details"]: c_issues.edit_issue(data["details"]) c_issues.save_issueList() response_dict = {"success": True} else: response_dict = { "success": False, "reason": "Must include field 'details' with property 'id'" } self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "deleteIssue": if "id" in data: c_issues.remove_issue(data["id"]) c_issues.save_issueList() response_dict = {"success": True, "reason": ""} else: response_dict = {"success": False, "reason": "Must include field 'id'"} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "getIssueList": response = { "success": True, "issueList": [x.details for x in config.issueList] } self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "issueMediaDelete": if "filename" not in data: response = {"success": False, "reason": "Request missing 'filename' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return this_id = None if "id" in data: this_id = data["id"] c_issues.delete_issue_media_file(data["filename"], owner=this_id) response = {"success": True} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == 'updateMaintenanceStatus': if "id" not in data or "status" not in data or "notes" not in data: response = {"success": False, "reason": "Request missing 'id', 'status', or 'notes' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") record = {"id": data["id"], "date": datetime.datetime.now().isoformat(), "status": data['status'], "notes": data["notes"]} with config.maintenanceLock: try: with open(file_path, 'a', encoding='UTF-8') as f: f.write(json.dumps(record) + "\n") success = True reason = "" except FileNotFoundError: success = False reason = f"File path {file_path} does not exist" except PermissionError: success = False reason = f"You do not have write permission for the file {file_path}" response_dict = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == 'deleteMaintenanceRecord': if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return else: file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") with config.maintenanceLock: response = delete_file(file_path) self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == 'getMaintenanceStatus': if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "maintenance-logs", data["id"] + ".txt") with config.maintenanceLock: response_dict = c_maint.get_maintenance_report(file_path) self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) elif action == "getAllMaintenanceStatuses": record_list = [] maintenance_path = os.path.join(config.APP_PATH, "maintenance-logs") for file in os.listdir(maintenance_path): if file.lower().endswith(".txt"): with config.maintenanceLock: file_path = os.path.join(maintenance_path, file) record_list.append(c_maint.get_maintenance_report(file_path)) response_dict = {"success": True, "records": record_list} self.wfile.write(bytes(json.dumps(response_dict), encoding="UTF-8")) else: print(f"Error: Unknown webpage command received: {action}") with config.logLock: logging.error(f"Unknown webpage command received: {action}") elif ping_class == "exhibitComponent": if "action" in data: # not a ping action = data["action"] # if "id" in data: # print(f" id = {data['id']}") # print(f" action = {action}") if action == "getUploadedFile": if "id" not in data: response = {"success": False, "reason": "Request missing 'id' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return component = c_exhibit.get_exhibit_component(data["id"]) if len(component.dataToUpload) > 0: upload = component.dataToUpload.pop(0) # json_string = json.dumps(upload) # self.wfile.write(bytes(json_string, encoding="UTF-8")) self.wfile.write(upload) elif action == "beginSynchronization": if "synchronizeWith" in data: c_exhibit.update_synchronization_list(data["id"], data["synchronizeWith"]) else: # it's a ping try: id = data["id"] # type = data["type"] if id == "UNKNOWN": print(f"Warning: exhibitComponent ping with id=UNKNOWN coming from {self.address_string()}") self.wfile.write(bytes(json.dumps({}), encoding='UTF-8')) # print("END POST") # print("===============") return except KeyError: print("Error: exhibitComponent ping received without id or type field") # print("END POST") # print("===============") return # No id or type, so bail out # print(f" id = {id}") # print(" action = ping") c_exhibit.update_exhibit_component_status(data, self.address_string()) self.send_current_configuration(id) elif ping_class == "tracker": if "action" not in data: response = {"success": False, "reason": "Request missing 'action' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return action = data["action"] if action == "getLayoutDefinition": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") layout_definition, success, reason = c_track.get_layout_definition(data["name"] + ".ini", kind=kind) response = {"success": success, "reason": reason, "layout": layout_definition} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitData": if "data" not in data or "name" not in data: response = {"success": False, "reason": "Request missing 'data' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") file_path = os.path.join(config.APP_PATH, kind, "data", data["name"] + ".txt") success, reason = c_track.write_JSON(data["data"], file_path) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitRawText": if "text" not in data or "name" not in data: response = {"success": False, "reason": "Request missing 'text' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") success, reason = c_track.write_raw_text(data["text"], data["name"] + ".txt", kind) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "retrieveRawText": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") result, success, reason = c_track.get_raw_text(data["name"] + ".txt", kind) response = {"success": success, "reason": reason, "text": result} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "submitAnalytics": if "data" not in data or 'name' not in data: response = {"success": False, "reason": "Request missing 'data' or 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return file_path = os.path.join(config.APP_PATH, "analytics", data["name"] + ".txt") success, reason = c_track.write_JSON(data["data"], file_path) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "getAvailableDefinitions": kind = data.get("kind", "flexible-tracker") definition_list = [] template_path = os.path.join(config.APP_PATH, kind, "templates") for file in os.listdir(template_path): if file.lower().endswith(".ini"): definition_list.append(file) self.wfile.write(bytes(json.dumps(definition_list), encoding="UTF-8")) elif action == "downloadTrackerData": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".txt"): name += ".txt" data_path = os.path.join(config.APP_PATH, kind, "data", name) result = c_track.create_CSV(data_path) response = {"success": True, "csv": result} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "clearTrackerData": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".txt"): name += ".txt" data_path = os.path.join(config.APP_PATH, kind, "data", name) success = True reason = "" with config.trackingDataWriteLock: try: os.remove(data_path) except PermissionError: success = False reason = f"You do not have write permission for the file {data_path}" except FileNotFoundError: success = True # This error results in the user's desired action! reason = f"File does not exist: {data_path}" if reason != "": print(reason) response = {"success": success, "reason": reason} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "createTemplate": if "name" not in data or "template" not in data: response = {"success": False, "reason": "Request missing 'name' or 'template' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") name = data["name"] if not name.lower().endswith(".ini"): name += ".ini" file_path = os.path.join(config.APP_PATH, kind, "templates", name) success = c_track.create_template(file_path, data["template"]) response = {"success": success} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "deleteTemplate": if "name" not in data: response = {"success": False, "reason": "Request missing 'name' field."} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) return kind = data.get("kind", "flexible-tracker") file_path = os.path.join(config.APP_PATH, kind, "templates", data["name"] + ".ini") with config.trackerTemplateWriteLock: response = delete_file(file_path) self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) elif action == "checkConnection": self.wfile.write(bytes(json.dumps({"success": True}), encoding="UTF-8")) else: print(f"Error: ping with unknown class '{ping_class}' received") response = {"success": False, "reason": f"Unknown class {ping_class}"} self.wfile.write(bytes(json.dumps(response), encoding="UTF-8")) # print("END POST") # print("===============") return # print("END POST") # print("===============") def delete_file(file_path) -> dict: """Delete the specified file and return a dictionary with the result""" response = {"success": False} try: os.remove(file_path) response["success"] = True except FileNotFoundError: response["reason"] = f"File {file_path} does not exist" except PermissionError: response["reason"] = f"You do not have permission for the file f{file_path}" return response def parse_byte_range(byte_range): """Returns the two numbers in 'bytes=123-456' or throws ValueError. The last number or both numbers may be None. """ BYTE_RANGE_RE = re.compile(r'bytes=(\d+)-(\d+)?$') if byte_range.strip() == '': return None, None m = BYTE_RANGE_RE.match(byte_range) if not m: raise ValueError(f'Invalid byte range {byte_range}') first, last = [x and int(x) for x in m.groups()] if last and last < first: raise ValueError(f'Invalid byte range {byte_range}') return first, last def clear_terminal(): """Clear the terminal""" os.system('cls' if os.name == 'nt' else 'clear') def command_line_setup(): """Prompt the user for several pieces of information on first-time setup""" settings_dict = {} clear_terminal() print("##########################################################") print("Welcome to Constellation Control Server!") print("") print("This appears to be your first time running Control Server.") print("In order to set up your configuration, you will be asked") print("a few questions. If you don't know the answer, or wish to") print("accept the default, just press the enter key.") print("") gallery_name = input("Enter a name for the gallery (default: Constellation): ").strip() if gallery_name == "": gallery_name = "Constellation" settings_dict["gallery_name"] = gallery_name default_ip = socket.gethostbyname(socket.gethostname()) ip_address = input(f"Enter this computer's static IP address (default: {default_ip}): ").strip() if ip_address == "": ip_address = default_ip settings_dict["ip_address"] = ip_address default_port = 8082 while True: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: if s.connect_ex((ip_address, default_port)) != 0: # Port is free break else: default_port += 1 port = input(f"Enter the desired port (default: {default_port}): ").strip() if port == "": port = default_port else: port = int(port) settings_dict["server_port"] = port settings_dict["current_exhibit"] = "default.exhibit" return {"CURRENT": settings_dict} def load_default_configuration(): """Read the current exhibit configuration from file and initialize it""" global server_port global ip_address global gallery_name # First, retrieve the config filename that defines the desired gallery config_reader = configparser.ConfigParser(delimiters="=") config_reader.optionxform = str # Override default, which is case in-sensitive gal_path = os.path.join(config.APP_PATH, "galleryConfiguration.ini") with config.galleryConfigurationLock: config_reader.read(gal_path) try: current = config_reader["CURRENT"] except KeyError: # We don't have a config file, so let's get info from the user to create one settings_dict = command_line_setup() config_reader.read_dict(settings_dict) with open(os.path.join(config.APP_PATH, "galleryConfiguration.ini"), "w", encoding="UTF-8") as f: config_reader.write(f) current = config_reader["CURRENT"] server_port = current.getint("server_port", 8080) ip_address = current.get("server_ip_address", socket.gethostbyname(socket.gethostname())) gallery_name = current.get("gallery_name", "Constellation") staff_list = current.get("assignable_staff", []) if len(staff_list) > 0: config.assignable_staff = [x.strip() for x in staff_list.split(",")] c_sched.retrieve_schedule() config.projectorList = [] # Load the component descriptions. Do this first, so they are available when # creating the various components try: print("Reading component descriptions...", end="", flush=True) config.componentDescriptions = dict(config_reader["COMPONENT_DESCRIPTIONS"]) print(" done") except KeyError: print("None found") config.componentDescriptions = {} # Parse list of PJLink projectors try: pjlink_projectors = config_reader["PJLINK_PROJECTORS"] print("Connecting to PJLink projectors...", end="\r", flush=True) except KeyError: print("No PJLink projectors specified") pjlink_projectors = [] n_proj = len(pjlink_projectors) cur_proj = 0 for key in pjlink_projectors: cur_proj += 1 print(f"Connecting to PJLink projectors... {cur_proj}/{n_proj}", end="\r", flush=True) if c_proj.get_projector(key) is None: # Try to split on a comma. If we get two elements back, that means # we have the form "ip, password" split = pjlink_projectors[key].split(",") if len(split) == 2: # We have an IP address and a password ip = split[0].strip() password = split[1].strip() if password == "": password = None new_proj = c_proj.Projector(key, ip, "pjlink", password=password) elif len(split) == 1: # We have an IP address only new_proj = c_proj.Projector(key, pjlink_projectors[key], "pjlink") else: print("Invalid PJLink projector entry:", pjlink_projectors[key]) break config.projectorList.append(new_proj) print("Connecting to PJLink projectors... done ") # Parse list of serial projectors try: serial_projectors = config_reader["SERIAL_PROJECTORS"] print("Connecting to serial projectors...", end="\r", flush=True) except KeyError: print("No serial projectors specified") serial_projectors = [] n_proj = len(serial_projectors) cur_proj = 0 for key in serial_projectors: cur_proj += 1 print(f"Connecting to serial projectors... {cur_proj}/{n_proj}", end="\r", flush=True) if c_proj.get_projector(key) is None: # Try to split on a comma. If we get two elements back, that means # we have the form "ip, password" split = serial_projectors[key].split(",") if len(split) == 2: # We have an IP address and a make ip = split[0].strip() make = split[1].strip() if make == "": make = None new_proj = c_proj.Projector(key, ip, "serial", make=make) elif len(split) == 1: # We have an IP address only new_proj = c_proj.Projector(key, serial_projectors[key], "serial") else: print("Invalid serial projector entry:", serial_projectors[key]) break config.projectorList.append(new_proj) print("Connecting to serial projectors... done ") # Parse list of Wake on LAN devices try: wol = config_reader["WAKE_ON_LAN"] print("Collecting Wake on LAN devices...", end="", flush=True) for key in wol: if c_exhibit.get_exhibit_component(key) is None: # If 'get_exhibit_component' is not None, this key corresponds # to a WoL device with a matching exhibit component ID and # we have already loaded that component from the pickle file value_split = wol[key].split(",") if len(value_split) == 2: # We have been given a MAC address and IP address device = c_exhibit.WakeOnLANDevice(key, value_split[0].strip(), ip_address=value_split[1].strip()) elif len(value_split) == 1: # We have been given only a MAC address device = c_exhibit.WakeOnLANDevice(key, value_split[0].strip()) else: print(f"Wake on LAN device specified with unknown format: {wol[key]}") continue config.wakeOnLANList.append(device) print(" done") except KeyError: print("No wake on LAN devices specified") config.wakeOnLANList = [] # Build any existing issues try: issue_file = os.path.join(config.APP_PATH, "issues", "issues.json") with open(issue_file, "r", encoding="UTF-8") as file_object: issues = json.load(file_object) print("Reading stored issues...", end="", flush=True) for issue in issues: new_issue = c_issues.Issue(issue) config.issueList.append(new_issue) print(" done") except FileNotFoundError: print("No stored issues to read") # Parse list of static components try: static_components = config_reader["STATIC_COMPONENTS"] print("Adding static components... ", end="\r", flush=True) for this_type in static_components: split = static_components[this_type].split(",") for this_id in split: c_exhibit.add_exhibit_component(this_id.strip(), this_type, category="static") print("done") except KeyError: print("none specified") # Parse the reboot_time if necessary if "reboot_time" in current: reboot_time = dateutil.parser.parse(current["reboot_time"]) if reboot_time < datetime.datetime.now(): reboot_time += datetime.timedelta(days=1) config.serverRebootTime = reboot_time print("Server will reboot at:", config.serverRebootTime.isoformat()) # Then, load the configuration for that exhibit c_exhibit.read_exhibit_configuration(current["current_exhibit"]) # Update the components that the configuration has changed for component in config.componentList: component.update_configuration() def check_file_structure(): """Check to make sure we have the appropriate file structure set up""" schedules_dir = os.path.join(config.APP_PATH, "schedules") exhibits_dir = os.path.join(config.APP_PATH, "exhibits") misc_dirs = {"analytics": os.path.join(config.APP_PATH, "analytics"), "flexible-tracker": os.path.join(config.APP_PATH, "flexible-tracker"), "flexible-tracker/data": os.path.join(config.APP_PATH, "flexible-tracker", "data"), "flexible-tracker/templates": os.path.join(config.APP_PATH, "flexible-tracker", "templates"), "flexible-voter": os.path.join(config.APP_PATH, "flexible-voter"), "flexible-voter/data": os.path.join(config.APP_PATH, "flexible-voter", "data"), "flexible-voter/templates": os.path.join(config.APP_PATH, "flexible-voter", "templates"), "issues": os.path.join(config.APP_PATH, "issues"), "issues/media": os.path.join(config.APP_PATH, "issues", "media"), "maintenance-logs": os.path.join(config.APP_PATH, "maintenance-logs")} try: os.listdir(schedules_dir) except FileNotFoundError: print("Missing schedules directory. Creating now...") try: os.mkdir(schedules_dir) default_schedule_list = ["monday.ini", "tuesday.ini", "wednesday.ini", "thursday.ini", "friday.ini", "saturday.ini", "sunday.ini"] for file in default_schedule_list: with open(os.path.join(schedules_dir, file), 'w', encoding="UTF-8") as f: f.write("[SCHEDULE]\n") except PermissionError: print("Error: unable to create 'schedules' directory. Do you have write permission?") try: os.listdir(exhibits_dir) except FileNotFoundError: print("Missing exhibits directory. Creating now...") try: os.mkdir(exhibits_dir) with open(os.path.join(exhibits_dir, "default.exhibit"), 'w', encoding="UTF-8") as f: f.write("") except PermissionError: print("Error: unable to create 'exhibits' directory. Do you have write permission?") for key in misc_dirs: try: os.listdir(misc_dirs[key]) except FileNotFoundError: print(f"Missing {key} directory. Creating now...") try: os.mkdir(misc_dirs[key]) except PermissionError: print(f"Error: unable to create '{key}' directory. Do you have write permission?") def quit_handler(*args): """Handle cleanly shutting down the server""" try: if config.rebooting is True: exit_code = 1 print("\nRebooting server...") else: exit_code = 0 print('\nKeyboard interrupt detected. Cleaning up and shutting down...') except RuntimeError: exit_code = 0 # Save the current component lists to a pickle file so that # we can resume from the current state path_to_write = os.path.join(config.APP_PATH, "current_state.dat") with open(path_to_write, 'wb') as f: pickle.dump(config.componentList, f) for key in config.polling_thread_dict: config.polling_thread_dict[key].cancel() with config.logLock: logging.info("Server shutdown") with config.galleryConfigurationLock: with config.scheduleLock: with config.trackingDataWriteLock: sys.exit(exit_code) def error_handler(*exc_info): """Catch errors and log them to file""" text = "".join(traceback.format_exception(*exc_info)).replace('"', "'").replace("\n", "<newline>") with config.logLock: logging.error(f'"{text}"') print(f"Error: see control_server.log for more details ({datetime.datetime.now()})") def check_for_software_update(): """Download the version.txt file from GitHub and check if there is an update""" global software_update_available print("Checking for update... ", end="") try: for line in urllib.request.urlopen( "https://raw.githubusercontent.com/Cosmic-Chatter/Constellation/main/control_server/version.txt"): if float(line.decode('utf-8')) > SOFTWARE_VERSION: software_update_available = True break except urllib.error.HTTPError: print("cannot connect to update server") return if software_update_available: print("update available!") else: print("the server is up to date.") # Check whether we have packaged with Pyinstaller and set the appropriate root path. config.EXEC_PATH = os.path.dirname(os.path.abspath(__file__)) if getattr(sys, 'frozen', False): # If the application is run as a --onefile bundle, the PyInstaller bootloader # extends the sys module by a flag frozen=True and sets the app # path into variable sys.executable. config.APP_PATH = os.path.dirname(sys.executable) else: config.APP_PATH = config.EXEC_PATH server_port: int = 8080 # Default; should be set in currentExhibitConfiguration.ini ip_address: str = socket.gethostbyname(socket.gethostname()) # Default; should be set in galleryConfiguration.ini ADDR: str = "" # Accept connections from all interfaces gallery_name: str = "" SOFTWARE_VERSION = 1.0 software_update_available: bool = False # Set up log file log_path: str = os.path.join(config.APP_PATH, "control_server.log") logging.basicConfig(datefmt='%Y-%m-%d %H:%M:%S', filename=log_path, format='%(levelname)s, %(asctime)s, %(message)s', level=logging.DEBUG) signal.signal(signal.SIGINT, quit_handler) sys.excepthook = error_handler with config.logLock: logging.info("Server started") # Try to reload the previous state from the pickle file current_state.dat try: state_path = os.path.join(config.APP_PATH, "current_state.dat") with open(state_path, "rb") as previous_state: config.componentList = pickle.load(previous_state) print("Previous server state loaded") except (FileNotFoundError, EOFError): print("Could not load previous server state") check_file_structure() c_exhibit.check_available_exhibits() load_default_configuration() c_sched.poll_event_schedule() c_proj.poll_projectors() c_exhibit.poll_wake_on_LAN_devices() check_for_software_update() httpd = ThreadedHTTPServer((ADDR, server_port), RequestHandler) httpd.serve_forever()
import json from flask import Flask, render_template , request from flask.wrappers import Response from get_ocr import get_ocr import os import datetime from werkzeug.utils import secure_filename import csv app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("/upload",methods=['POST','GET']) def upload(): if request.method == 'POST': img = request.files.get('imagefile', '') img.save(os.path.join(os.getcwd() , "static" , secure_filename('img_test' + '.jpg'))) img_path = 'static/img_test.jpg' data , text , textnew , newpath= get_ocr(img_path) return render_template('edit_details.html' , data= data , text=text , img = newpath , textnew=textnew ) current_uid = {} current_uid['id'] = "None" @app.route("/submit",methods=['POST','GET']) def sub(): if request.method == 'POST': global updated_data updated_data = {} updated_data['DOC_type'] = request.form.get('doctype') updated_data['Name'] = request.form.get('name') updated_data['Gender'] = request.form.get('gender') updated_data['Birth year'] = request.form.get('byear') updated_data['Uid'] = request.form.get('uid') current_uid['id'] = updated_data['Uid'] return render_template('jsonify.html' , data = updated_data) @app.route("/insert",methods=['POST','GET']) def insert(): date = str(datetime.datetime.now()) f = open("records.csv", "a") f.write(f"{updated_data["DOC_type"]},{updated_data["Uid"]},{updated_data["Name"]},{updated_data["Birth year"]},{updated_data["Gender"]}, {date[0:10]},{date[11:19]}\n") f.close() return render_template('jsonify.html' , data = updated_data , msg=1) @app.route("/downlaod",methods=['POST','GET']) def download(): uid = current_uid['id'] json_file_path = f"static/document/{uid}.json" with open(json_file_path, 'r') as fp: json_data = json.load(fp) return Response( json_data, mimetype="text/json", headers={"Content-disposition": f"attachment; filename={uid}.json"}) @app.route("/record", methods=['POST','GET']) # page to view record of all users def rec(): val = [] with open("records.csv", "r") as f: reader = csv.reader(f) for i in reader: val.append(i) return render_template('/records.html' , val = val) if __name__ == '__main__': app.run(debug=True) # app.run(host='0.0.0.0')
import json from flask import Flask, render_template , request from flask.wrappers import Response from get_ocr import get_ocr import os import datetime from werkzeug.utils import secure_filename import csv app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("/upload",methods=['POST','GET']) def upload(): if request.method == 'POST': img = request.files.get('imagefile', '') img.save(os.path.join(os.getcwd() , "static" , secure_filename('img_test' + '.jpg'))) img_path = 'static/img_test.jpg' data , text , textnew , newpath= get_ocr(img_path) return render_template('edit_details.html' , data= data , text=text , img = newpath , textnew=textnew ) current_uid = {} current_uid['id'] = "None" @app.route("/submit",methods=['POST','GET']) def sub(): if request.method == 'POST': global updated_data updated_data = {} updated_data['DOC_type'] = request.form.get('doctype') updated_data['Name'] = request.form.get('name') updated_data['Gender'] = request.form.get('gender') updated_data['Birth year'] = request.form.get('byear') updated_data['Uid'] = request.form.get('uid') current_uid['id'] = updated_data['Uid'] return render_template('jsonify.html' , data = updated_data) @app.route("/insert",methods=['POST','GET']) def insert(): date = str(datetime.datetime.now()) f = open("records.csv", "a") f.write(f"{updated_data['DOC_type']},{updated_data['Uid']},{updated_data['Name']},{updated_data['Birth year']},{updated_data['Gender']}, {date[0:10]},{date[11:19]}\n") f.close() return render_template('jsonify.html' , data = updated_data , msg=1) @app.route("/downlaod",methods=['POST','GET']) def download(): uid = current_uid['id'] json_file_path = f"static/document/{uid}.json" with open(json_file_path, 'r') as fp: json_data = json.load(fp) return Response( json_data, mimetype="text/json", headers={"Content-disposition": f"attachment; filename={uid}.json"}) @app.route("/record", methods=['POST','GET']) # page to view record of all users def rec(): val = [] with open("records.csv", "r") as f: reader = csv.reader(f) for i in reader: val.append(i) return render_template('/records.html' , val = val) if __name__ == '__main__': app.run(debug=True) # app.run(host='0.0.0.0')
import pytest from r2d7.meta import Metawing import json list_printer_tests = ( ('{"position": 5, "id": 2085, "name": "DBS Swarm", "faction": "Separatist Alliance", "ships": [{"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 62, "name": "Hyena-class Droid Bomber", "xws": "hyenaclassdroidbomber", "link": "https://meta.listfortress.com/ships/62.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 81.25, "weight": 0.803933897124467}', '''DBS Swarm :vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::hyenaclassdroidbomber: Average: 81%, Weighted: 80%'''), ('{"position": 1, "id": 2336, "name": null, "faction": "Resistance", "link": "https://meta.listfortress.com/ship_combos/2336.json", "ships": [{"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 49, "name": "RZ-2 A-wing", "xws": "rz2awing", "link": "https://meta.listfortress.com/ships/49.json"}, {"id": 61, "name": "Resistance Transport Pod", "xws": "resistancetransportpod", "link": "https://meta.listfortress.com/ships/61.json"}], "squadron_count": 2, "tournaments_count": 2, "average_percentile": 98.68, "weight": 1.16857595629635}', '''<https://meta.listfortress.com/ship_combos/2336|(unnamed)> :t70xwing::t70xwing::t70xwing::rz2awing::resistancetransportpod: Average: 99%, Weighted: 117%'''), ('{"position": 2, "id": 191, "name": "Double Firespray", "faction": "Scum and Villainy", "link": "https://meta.listfortress.com/ship_combos/191.json", "ships": [{"id": 22, "name": "Firespray-class Patrol Craft", "xws": "firesprayclasspatrolcraft", "link": "https://meta.listfortress.com/ships/22.json"}, {"id": 22, "name": "Firespray-class Patrol Craft", "xws": "firesprayclasspatrolcraft", "link": "https://meta.listfortress.com/ships/22.json"}], "squadron_count": 13, "tournaments_count": 8, "average_percentile": 38.81, "weight": 1.01919215760887}', '''<https://meta.listfortress.com/ship_combos/191|Double Firespray> :firesprayclasspatrolcraft::firesprayclasspatrolcraft: Average: 39%, Weighted: 102%'''), ('{"position": 3, "id": 2801, "name": "The Baron and the Bros", "faction": "First Order", "link": "https://meta.listfortress.com/ship_combos/2801.json", "ships": [{"id": 51, "name": "TIE/fo Fighter", "xws": "tiefofighter", "link": "https://meta.listfortress.com/ships/51.json"}, {"id": 67, "name": "TIE/ba Interceptor", "xws": "tiebainterceptor", "link": "https://meta.listfortress.com/ships/67.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 95.45, "weight": 0.944481781237137}', '''<https://meta.listfortress.com/ship_combos/2801|The Baron and the Bros> :tiefofighter::tiebainterceptor::tiesffighter::tiesffighter::tiesffighter: Average: 95%, Weighted: 94%'''), ('{"position": 4, "id": 2324, "name": null, "faction": "First Order", "link": "https://meta.listfortress.com/ship_combos/2324.json", "ships": [{"id": 51, "name": "TIE/fo Fighter", "xws": "tiefofighter", "link": "https://meta.listfortress.com/ships/51.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 53, "name": "TIE/vn Silencer", "xws": "tievnsilencer", "link": "https://meta.listfortress.com/ships/53.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 91.47, "weight": 0.905128373685589}', '''<https://meta.listfortress.com/ship_combos/2324|(unnamed)> :tiefofighter::tiesffighter::tiesffighter::tiesffighter::tievnsilencer: Average: 91%, Weighted: 91%'''), ) @pytest.mark.parametrize('message, expected', list_printer_tests) def test_list_printer(testbot, message, expected): j = json.loads(message) assert testbot.list_printer(j) == expected ship_printer_tests = ( ('{"position": 1, "id": 21, "xws": "fangfighter", "name": "Fang Fighter", "link": "https://meta.listfortress.com/ships/21.json", "pilots": [{"id": 99, "name": "Old Teroch", "link": "https://meta.listfortress.com/pilots/99.json", "image": "https://meta.listfortress.com/pilots/99/image.png"}, {"id": 96, "name": "Fenn Rau", "link": "https://meta.listfortress.com/pilots/96.json", "image": "https://meta.listfortress.com/pilots/96/image.png"}, {"id": 97, "name": "Joy Rekkoff", "link": "https://meta.listfortress.com/pilots/97.json", "image": "https://meta.listfortress.com/pilots/97/image.png"}, {"id": 98, "name": "Kad Solus", "link": "https://meta.listfortress.com/pilots/98.json", "image": "https://meta.listfortress.com/pilots/98/image.png"}, {"id": 100, "name": "Skull Squadron Pilot", "link": "https://meta.listfortress.com/pilots/100.json", "image": "https://meta.listfortress.com/pilots/100/image.png"}, {"id": 101, "name": "Zealous Recruit", "link": "https://meta.listfortress.com/pilots/101.json", "image": "https://meta.listfortress.com/pilots/101/image.png"}], "squadron_count": 18, "tournaments_count": 7, "average_percentile": 34.75, "weight": 1.24538930744309, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/ships/21|Fang Fighter>:fangfighter: Average: 35%, Weighted: 125%'''), ('{"position": 2, "id": 28, "xws": "m3ainterceptor", "name": "M3-A Interceptor", "link": "https://meta.listfortress.com/ships/28.json", "pilots": [{"id": 132, "name": "Cartel Spacer", "link": "https://meta.listfortress.com/pilots/132.json", "image": "https://meta.listfortress.com/pilots/132/image.png"}, {"id": 134, "name": "Inaldra", "link": "https://meta.listfortress.com/pilots/134.json", "image": "https://meta.listfortress.com/pilots/134/image.png"}, {"id": 135, "name": "Laetin A\'shera", "link": "https://meta.listfortress.com/pilots/135.json", "image": "https://meta.listfortress.com/pilots/135/image.png"}, {"id": 136, "name": "Quinn Jast", "link": "https://meta.listfortress.com/pilots/136.json", "image": "https://meta.listfortress.com/pilots/136/image.png"}, {"id": 137, "name": "Serissu", "link": "https://meta.listfortress.com/pilots/137.json", "image": "https://meta.listfortress.com/pilots/137/image.png"}, {"id": 138, "name": "Sunny Bounder", "link": "https://meta.listfortress.com/pilots/138.json", "image": "https://meta.listfortress.com/pilots/138/image.png"}, {"id": 139, "name": "Tansarii Point Veteran", "link": "https://meta.listfortress.com/pilots/139.json", "image": "https://meta.listfortress.com/pilots/139/image.png"}, {"id": 133, "name": "Genesis Red", "link": "https://meta.listfortress.com/pilots/133.json", "image": "https://meta.listfortress.com/pilots/133/image.png"}, {"id": 369, "name": "G4R-G0R V/M", "link": "https://meta.listfortress.com/pilots/369.json", "image": "https://meta.listfortress.com/pilots/369/image.png"}], "squadron_count": 17, "tournaments_count": 8, "average_percentile": 36.67, "weight": 1.23087941090141, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/ships/28|M3-A Interceptor>:m3ainterceptor: Average: 37%, Weighted: 123%'''), ('{"position": 4, "id": 61, "xws": "resistancetransportpod", "name": "Resistance Transport Pod", "link": "https://meta.listfortress.com/ships/61.json", "pilots": [{"id": 341, "name": "BB-8", "link": "https://meta.listfortress.com/pilots/341.json", "image": "https://meta.listfortress.com/pilots/341/image.png"}, {"id": 342, "name": "Rose Tico", "link": "https://meta.listfortress.com/pilots/342.json", "image": "https://meta.listfortress.com/pilots/342/image.png"}, {"id": 343, "name": "Vi Moradi", "link": "https://meta.listfortress.com/pilots/343.json", "image": "https://meta.listfortress.com/pilots/343/image.png"}, {"id": 344, "name": "Finn", "link": "https://meta.listfortress.com/pilots/344.json", "image": "https://meta.listfortress.com/pilots/344/image.png"}], "squadron_count": 8, "tournaments_count": 7, "average_percentile": 48.6, "weight": 0, "faction": "Resistance"}', '''<https://meta.listfortress.com/ships/61|Resistance Transport Pod>:resistancetransportpod: Average: 49%, Weighted: 0%'''), ) @pytest.mark.parametrize('message, expected', ship_printer_tests) def test_ship_printer(testbot, message, expected): j = json.loads(message) assert testbot.ship_printer(j) == expected pilot_printer_tests = ( ('{"position": 1, "id": 271, "xws": "tn3465", "name": "TN-3465", "link": "https://meta.listfortress.com/pilots/271.json", "image": "https://meta.listfortress.com/pilots/271/image.png", "ship": {"id": 51, "name": "TIE/fo Fighter", "link": "https://meta.listfortress.com/ships/51.json"}, "squadron_count": 2, "tournaments_count": 1, "average_percentile": 93.46, "weight": 1.46578136825278, "faction": "First Order"}', '''<https://meta.listfortress.com/pilots/271|TN-3465> :tiefofighter: Average: 93%, Weighted: 147%'''), ('{"position": 3, "id": 102, "xws": "bobafett", "name": "Boba Fett", "link": "https://meta.listfortress.com/pilots/102.json", "image": "https://meta.listfortress.com/pilots/102/image.png", "ship": {"id": 22, "name": "Firespray-class Patrol Craft", "link": "https://meta.listfortress.com/ships/22.json"}, "squadron_count": 21, "tournaments_count": 9, "average_percentile": 36.35, "weight": 1.16356864601878, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/pilots/102|Boba Fett> :firesprayclasspatrolcraft: Average: 36%, Weighted: 116%'''), ('{"position": 5, "id": 321, "xws": "plokoon", "name": "Plo Koon", "link": "https://meta.listfortress.com/pilots/321.json", "image": "https://meta.listfortress.com/pilots/321/image.png", "ship": {"id": 58, "name": "Delta-7 Aethersprite", "link": "https://meta.listfortress.com/ships/58.json"}, "squadron_count": 6, "tournaments_count": 4, "average_percentile": 48.14, "weight": 1.12182792544073, "faction": "Galactic Republic"}', '''<https://meta.listfortress.com/pilots/321|Plo Koon> :delta7aethersprite: Average: 48%, Weighted: 112%'''), ) @pytest.mark.parametrize('message, expected', pilot_printer_tests) def test_pilot_printer(testbot, message, expected): j = json.loads(message) assert testbot.pilot_printer(j) == expected upgrade_printer_tests = ( ('{"position": 1, "id": 160, "xws": "heroic", "name": "Heroic", "link": "https://meta.listfortress.com/upgrades/160.json", "image": "https://meta.listfortress.com/upgrades/160/image.png", "squadron_count": 18, "tournaments_count": 11, "average_percentile": 43.71, "weight": 1.37863771336788}', '''<https://meta.listfortress.com/upgrades/160|Heroic> Average: 44%, Weighted: 138%'''), ('{"position": 4, "id": 92, "xws": "protonbombs", "name": "Proton Bombs", "link": "https://meta.listfortress.com/upgrades/92.json", "image": "https://meta.listfortress.com/upgrades/92/image.png", "squadron_count": 28, "tournaments_count": 12, "average_percentile": 34.47, "weight": 1.22427215793812}', '''<https://meta.listfortress.com/upgrades/92|Proton Bombs> Average: 34%, Weighted: 122%'''), ('{"position": 5, "id": 227, "xws": "autoblasters", "name": "Autoblasters", "link": "https://meta.listfortress.com/upgrades/227.json", "image": "https://meta.listfortress.com/upgrades/227/image.png", "squadron_count": 27, "tournaments_count": 12, "average_percentile": 6, "weight": 0.055}', '''<https://meta.listfortress.com/upgrades/227|Autoblasters> Average: 6%, Weighted: 6%'''), ) @pytest.mark.parametrize('message, expected', upgrade_printer_tests) def test_upgrade_printer(testbot, message, expected): j = json.loads(message) assert testbot.upgrade_printer(j) == expected
import pytest from r2d7.meta import Metawing import json list_printer_tests = ( ('{"position": 5, "id": 2085, "name": "DBS Swarm", "faction": "Separatist Alliance", "ships": [{"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 55, "name": "Vulture-class Droid Fighter", "xws": "vultureclassdroidfighter", "link": "https://meta.listfortress.com/ships/55.json"}, {"id": 62, "name": "Hyena-class Droid Bomber", "xws": "hyenaclassdroidbomber", "link": "https://meta.listfortress.com/ships/62.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 81.25, "weight": 0.803933897124467}', '''DBS Swarm :vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::vultureclassdroidfighter::hyenaclassdroidbomber: Average: 81%, Weighted: 80%'''), ('{"position": 1, "id": 2336, "name": null, "faction": "Resistance", "link": "https://meta.listfortress.com/ship_combos/2336.json", "ships": [{"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 50, "name": "T-70 X-wing", "xws": "t70xwing", "link": "https://meta.listfortress.com/ships/50.json"}, {"id": 49, "name": "RZ-2 A-wing", "xws": "rz2awing", "link": "https://meta.listfortress.com/ships/49.json"}, {"id": 61, "name": "Resistance Transport Pod", "xws": "resistancetransportpod", "link": "https://meta.listfortress.com/ships/61.json"}], "squadron_count": 2, "tournaments_count": 2, "average_percentile": 98.68, "weight": 1.16857595629635}', '''<https://meta.listfortress.com/ship_combos/2336|(unnamed)> :t70xwing::t70xwing::t70xwing::rz2awing::resistancetransportpod: Average: 99%, Weighted: 117%'''), ('{"position": 2, "id": 191, "name": "Double Firespray", "faction": "Scum and Villainy", "link": "https://meta.listfortress.com/ship_combos/191.json", "ships": [{"id": 22, "name": "Firespray-class Patrol Craft", "xws": "firesprayclasspatrolcraft", "link": "https://meta.listfortress.com/ships/22.json"}, {"id": 22, "name": "Firespray-class Patrol Craft", "xws": "firesprayclasspatrolcraft", "link": "https://meta.listfortress.com/ships/22.json"}], "squadron_count": 13, "tournaments_count": 8, "average_percentile": 38.81, "weight": 1.01919215760887}', '''<https://meta.listfortress.com/ship_combos/191|Double Firespray> :firesprayclasspatrolcraft::firesprayclasspatrolcraft: Average: 39%, Weighted: 102%'''), ('{"position": 3, "id": 2801, "name": "The Baron and the Bros", "faction": "First Order", "link": "https://meta.listfortress.com/ship_combos/2801.json", "ships": [{"id": 51, "name": "TIE/fo Fighter", "xws": "tiefofighter", "link": "https://meta.listfortress.com/ships/51.json"}, {"id": 67, "name": "TIE/ba Interceptor", "xws": "tiebainterceptor", "link": "https://meta.listfortress.com/ships/67.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 95.45, "weight": 0.944481781237137}', '''<https://meta.listfortress.com/ship_combos/2801|The Baron and the Bros> :tiefofighter::tiebainterceptor::tiesffighter::tiesffighter::tiesffighter: Average: 95%, Weighted: 94%'''), ('{"position": 4, "id": 2324, "name": null, "faction": "First Order", "link": "https://meta.listfortress.com/ship_combos/2324.json", "ships": [{"id": 51, "name": "TIE/fo Fighter", "xws": "tiefofighter", "link": "https://meta.listfortress.com/ships/51.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 52, "name": "TIE/sf Fighter", "xws": "tiesffighter", "link": "https://meta.listfortress.com/ships/52.json"}, {"id": 53, "name": "TIE/vn Silencer", "xws": "tievnsilencer", "link": "https://meta.listfortress.com/ships/53.json"}], "squadron_count": 1, "tournaments_count": 1, "average_percentile": 91.47, "weight": 0.905128373685589}', '''<https://meta.listfortress.com/ship_combos/2324|(unnamed)> :tiefofighter::tiesffighter::tiesffighter::tiesffighter::tievnsilencer: Average: 91%, Weighted: 91%'''), ) @pytest.mark.parametrize('message, expected', list_printer_tests) def test_list_printer(testbot, message, expected): j = json.loads(message) assert testbot.list_printer(j) == expected ship_printer_tests = ( ('{"position": 1, "id": 21, "xws": "fangfighter", "name": "Fang Fighter", "link": "https://meta.listfortress.com/ships/21.json", "pilots": [{"id": 99, "name": "Old Teroch", "link": "https://meta.listfortress.com/pilots/99.json", "image": "https://meta.listfortress.com/pilots/99/image.png"}, {"id": 96, "name": "Fenn Rau", "link": "https://meta.listfortress.com/pilots/96.json", "image": "https://meta.listfortress.com/pilots/96/image.png"}, {"id": 97, "name": "Joy Rekkoff", "link": "https://meta.listfortress.com/pilots/97.json", "image": "https://meta.listfortress.com/pilots/97/image.png"}, {"id": 98, "name": "Kad Solus", "link": "https://meta.listfortress.com/pilots/98.json", "image": "https://meta.listfortress.com/pilots/98/image.png"}, {"id": 100, "name": "Skull Squadron Pilot", "link": "https://meta.listfortress.com/pilots/100.json", "image": "https://meta.listfortress.com/pilots/100/image.png"}, {"id": 101, "name": "Zealous Recruit", "link": "https://meta.listfortress.com/pilots/101.json", "image": "https://meta.listfortress.com/pilots/101/image.png"}], "squadron_count": 18, "tournaments_count": 7, "average_percentile": 34.75, "weight": 1.24538930744309, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/ships/21|Fang Fighter>:fangfighter: Average: 35%, Weighted: 125%'''), ('{"position": 2, "id": 28, "xws": "m3ainterceptor", "name": "M3-A Interceptor", "link": "https://meta.listfortress.com/ships/28.json", "pilots": [{"id": 132, "name": "Cartel Spacer", "link": "https://meta.listfortress.com/pilots/132.json", "image": "https://meta.listfortress.com/pilots/132/image.png"}, {"id": 134, "name": "Inaldra", "link": "https://meta.listfortress.com/pilots/134.json", "image": "https://meta.listfortress.com/pilots/134/image.png"}, {"id": 135, "name": "Laetin A\'shera", "link": "https://meta.listfortress.com/pilots/135.json", "image": "https://meta.listfortress.com/pilots/135/image.png"}, {"id": 136, "name": "Quinn Jast", "link": "https://meta.listfortress.com/pilots/136.json", "image": "https://meta.listfortress.com/pilots/136/image.png"}, {"id": 137, "name": "Serissu", "link": "https://meta.listfortress.com/pilots/137.json", "image": "https://meta.listfortress.com/pilots/137/image.png"}, {"id": 138, "name": "Sunny Bounder", "link": "https://meta.listfortress.com/pilots/138.json", "image": "https://meta.listfortress.com/pilots/138/image.png"}, {"id": 139, "name": "Tansarii Point Veteran", "link": "https://meta.listfortress.com/pilots/139.json", "image": "https://meta.listfortress.com/pilots/139/image.png"}, {"id": 133, "name": "Genesis Red", "link": "https://meta.listfortress.com/pilots/133.json", "image": "https://meta.listfortress.com/pilots/133/image.png"}, {"id": 369, "name": "G4R-G0R V/M", "link": "https://meta.listfortress.com/pilots/369.json", "image": "https://meta.listfortress.com/pilots/369/image.png"}], "squadron_count": 17, "tournaments_count": 8, "average_percentile": 36.67, "weight": 1.23087941090141, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/ships/28|M3-A Interceptor>:m3ainterceptor: Average: 37%, Weighted: 123%'''), ('{"position": 4, "id": 61, "xws": "resistancetransportpod", "name": "Resistance Transport Pod", "link": "https://meta.listfortress.com/ships/61.json", "pilots": [{"id": 341, "name": "BB-8", "link": "https://meta.listfortress.com/pilots/341.json", "image": "https://meta.listfortress.com/pilots/341/image.png"}, {"id": 342, "name": "Rose Tico", "link": "https://meta.listfortress.com/pilots/342.json", "image": "https://meta.listfortress.com/pilots/342/image.png"}, {"id": 343, "name": "Vi Moradi", "link": "https://meta.listfortress.com/pilots/343.json", "image": "https://meta.listfortress.com/pilots/343/image.png"}, {"id": 344, "name": "Finn", "link": "https://meta.listfortress.com/pilots/344.json", "image": "https://meta.listfortress.com/pilots/344/image.png"}], "squadron_count": 8, "tournaments_count": 7, "average_percentile": 48.6, "weight": 0, "faction": "Resistance"}', '''<https://meta.listfortress.com/ships/61|Resistance Transport Pod>:resistancetransportpod: Average: 49%, Weighted: 0%'''), ) @pytest.mark.parametrize('message, expected', ship_printer_tests) def test_ship_printer(testbot, message, expected): j = json.loads(message) assert testbot.ship_printer(j) == expected pilot_printer_tests = ( ('{"position": 1, "id": 271, "xws": "tn3465", "name": "TN-3465", "link": "https://meta.listfortress.com/pilots/271.json", "image": "https://meta.listfortress.com/pilots/271/image.png", "ship": {"id": 51, "name": "TIE/fo Fighter", "link": "https://meta.listfortress.com/ships/51.json"}, "squadron_count": 2, "tournaments_count": 1, "average_percentile": 93.46, "weight": 1.46578136825278, "faction": "First Order"}', '''<https://meta.listfortress.com/pilots/271|TN-3465> :tiefofighter: Average: 93%, Weighted: 147%'''), ('{"position": 3, "id": 102, "xws": "bobafett", "name": "Boba Fett", "link": "https://meta.listfortress.com/pilots/102.json", "image": "https://meta.listfortress.com/pilots/102/image.png", "ship": {"id": 22, "name": "Firespray-class Patrol Craft", "link": "https://meta.listfortress.com/ships/22.json"}, "squadron_count": 21, "tournaments_count": 9, "average_percentile": 36.35, "weight": 1.16356864601878, "faction": "Scum and Villainy"}', '''<https://meta.listfortress.com/pilots/102|Boba Fett> :firesprayclasspatrolcraft: Average: 36%, Weighted: 116%'''), ('{"position": 5, "id": 321, "xws": "plokoon", "name": "Plo Koon", "link": "https://meta.listfortress.com/pilots/321.json", "image": "https://meta.listfortress.com/pilots/321/image.png", "ship": {"id": 58, "name": "Delta-7 Aethersprite", "link": "https://meta.listfortress.com/ships/58.json"}, "squadron_count": 6, "tournaments_count": 4, "average_percentile": 48.14, "weight": 1.12182792544073, "faction": "Galactic Republic"}', '''<https://meta.listfortress.com/pilots/321|Plo Koon> :delta7aethersprite: Average: 48%, Weighted: 112%'''), ) @pytest.mark.parametrize('message, expected', pilot_printer_tests) def test_pilot_printer(testbot, message, expected): j = json.loads(message) assert testbot.pilot_printer(j) == expected upgrade_printer_tests = ( ('{"position": 1, "id": 160, "xws": "heroic", "name": "Heroic", "link": "https://meta.listfortress.com/upgrades/160.json", "image": "https://meta.listfortress.com/upgrades/160/image.png", "squadron_count": 18, "tournaments_count": 11, "average_percentile": 43.71, "weight": 1.37863771336788}', '''<https://meta.listfortress.com/upgrades/160|Heroic> Average: 44%, Weighted: 138%'''), ('{"position": 4, "id": 92, "xws": "protonbombs", "name": "Proton Bombs", "link": "https://meta.listfortress.com/upgrades/92.json", "image": "https://meta.listfortress.com/upgrades/92/image.png", "squadron_count": 28, "tournaments_count": 12, "average_percentile": 34.47, "weight": 1.22427215793812}', '''<https://meta.listfortress.com/upgrades/92|Proton Bombs> Average: 34%, Weighted: 122%'''), ('{"position": 5, "id": 227, "xws": "autoblasters", "name": "Autoblasters", "link": "https://meta.listfortress.com/upgrades/227.json", "image": "https://meta.listfortress.com/upgrades/227/image.png", "squadron_count": 27, "tournaments_count": 12, "average_percentile": 6, "weight": 0.055}', '''<https://meta.listfortress.com/upgrades/227|Autoblasters> Average: 6%, Weighted: 6%'''), ) @pytest.mark.parametrize('message, expected', upgrade_printer_tests) def test_upgrade_printer(testbot, message, expected): j = json.loads(message) assert testbot.upgrade_printer(j) == expected
import json from landsatxplore.api import API from pprint import pprint # Initialize a new API instance and get an access key username = "batuhang" password = "SLCH6i5k9L.." api = API(username, password) # Search for Landsat TM scenes scenes = api.search( dataset='landsat_8_c1', latitude=28.85, longitude=41.35, start_date='2019-01-01', end_date='2021-10-01', max_cloud_cover=50, min_cloud_cover=20 ) print(f"{len(scenes)} scenes found.") # Process the result for scene in scenes: # print(scene['acquisition_date'].strftime('%Y-%m-%d')) # # Write scene footprints to disk # fname = f"{scene["landsat_product_id"]}.geojson" # with open(fname, "w") as f: # json.dump(scene['spatial_coverage'].__geo_interface__, f) pprint(scene['entity_id']) api.logout() from landsatxplore.earthexplorer import EarthExplorer ee = EarthExplorer(username, password) ee.download(scenes[0]['entity_id'], output_dir='./data')
import json from landsatxplore.api import API from pprint import pprint # Initialize a new API instance and get an access key username = "batuhang" password = "SLCH6i5k9L.." api = API(username, password) # Search for Landsat TM scenes scenes = api.search( dataset='landsat_8_c1', latitude=28.85, longitude=41.35, start_date='2019-01-01', end_date='2021-10-01', max_cloud_cover=50, min_cloud_cover=20 ) print(f"{len(scenes)} scenes found.") # Process the result for scene in scenes: # print(scene['acquisition_date'].strftime('%Y-%m-%d')) # # Write scene footprints to disk # fname = f"{scene['landsat_product_id']}.geojson" # with open(fname, "w") as f: # json.dump(scene['spatial_coverage'].__geo_interface__, f) pprint(scene['entity_id']) api.logout() from landsatxplore.earthexplorer import EarthExplorer ee = EarthExplorer(username, password) ee.download(scenes[0]['entity_id'], output_dir='./data')
_E='replace' _D=False _C='\n' _B='\r\n' _A=None import contextlib,io,os,shlex,shutil,sys,tempfile from . import formatting,termui,utils from ._compat import _find_binary_reader class EchoingStdin: def __init__(A,input,output):A._input=input;A._output=output def __getattr__(A,x):return getattr(A._input,x) def _echo(A,rv):A._output.write(rv);return rv def read(A,n=-1):return A._echo(A._input.read(n)) def readline(A,n=-1):return A._echo(A._input.readline(n)) def readlines(A):return[A._echo(B)for B in A._input.readlines()] def __iter__(A):return iter((A._echo(B)for B in A._input)) def __repr__(A):return repr(A._input) def make_input_stream(input,charset): if hasattr(input,'read'): A=_find_binary_reader(input) if A is not _A:return A raise TypeError('Could not find binary reader for input stream.') if input is _A:input=b'' elif not isinstance(input,bytes):input=input.encode(charset) return io.BytesIO(input) class Result: def __init__(A,runner,stdout_bytes,stderr_bytes,exit_code,exception,exc_info=_A):A.runner=runner;A.stdout_bytes=stdout_bytes;A.stderr_bytes=stderr_bytes;A.exit_code=exit_code;A.exception=exception;A.exc_info=exc_info @property def output(self):return self.stdout @property def stdout(self):return self.stdout_bytes.decode(self.runner.charset,_E).replace(_B,_C) @property def stderr(self): A=self if A.stderr_bytes is _A:raise ValueError('stderr not separately captured') return A.stderr_bytes.decode(A.runner.charset,_E).replace(_B,_C) def __repr__(A):B=repr(A.exception)if A.exception else'okay';return f"<{type(A).__name__} {B}>" class CliRunner: def __init__(A,charset='utf-8',env=_A,echo_stdin=_D,mix_stderr=True):A.charset=charset;A.env=env or{};A.echo_stdin=echo_stdin;A.mix_stderr=mix_stderr def get_default_prog_name(A,cli):return cli.name or'root' def make_env(C,overrides=_A): A=overrides;B=dict(C.env) if A:B.update(A) return B @contextlib.contextmanager def isolation(self,input=_A,env=_A,color=_D): D=env;A=self;input=make_input_stream(input,A.charset);H=sys.stdin;I=sys.stdout;J=sys.stderr;K=formatting.FORCED_WIDTH;formatting.FORCED_WIDTH=80;D=A.make_env(D);E=io.BytesIO() if A.echo_stdin:input=EchoingStdin(input,E) input=io.TextIOWrapper(input,encoding=A.charset);sys.stdout=io.TextIOWrapper(E,encoding=A.charset) if not A.mix_stderr:F=io.BytesIO();sys.stderr=io.TextIOWrapper(F,encoding=A.charset) if A.mix_stderr:sys.stderr=sys.stdout sys.stdin=input def L(prompt=_A):sys.stdout.write(prompt or'');A=input.readline().rstrip(_B);sys.stdout.write(f"{A}\n");sys.stdout.flush();return A def M(prompt=_A):sys.stdout.write(f"{prompt or""}\n");sys.stdout.flush();return input.readline().rstrip(_B) def N(echo): A=sys.stdin.read(1) if echo:sys.stdout.write(A);sys.stdout.flush() return A O=color def P(stream=_A,color=_A): A=color if A is _A:return not O return not A Q=termui.visible_prompt_func;R=termui.hidden_prompt_func;S=termui._getchar;T=utils.should_strip_ansi;termui.visible_prompt_func=L;termui.hidden_prompt_func=M;termui._getchar=N;utils.should_strip_ansi=P;G={} try: for (B,C) in D.items(): G[B]=os.environ.get(B) if C is _A: try:del os.environ[B] except Exception:pass else:os.environ[B]=C yield(E,not A.mix_stderr and F) finally: for (B,C) in G.items(): if C is _A: try:del os.environ[B] except Exception:pass else:os.environ[B]=C sys.stdout=I;sys.stderr=J;sys.stdin=H;termui.visible_prompt_func=Q;termui.hidden_prompt_func=R;termui._getchar=S;utils.should_strip_ansi=T;formatting.FORCED_WIDTH=K def invoke(B,cli,args=_A,input=_A,env=_A,catch_exceptions=True,color=_D,**G): C=args;E=_A with B.isolation(input=input,env=env,color=color)as H: F=_A;A=0 if isinstance(C,str):C=shlex.split(C) try:I=G.pop('prog_name') except KeyError:I=B.get_default_prog_name(cli) try:cli.main(args=C or(),prog_name=I,**G) except SystemExit as D: E=sys.exc_info();A=D.code if A is _A:A=0 if A!=0:F=D if not isinstance(A,int):sys.stdout.write(str(A));sys.stdout.write(_C);A=1 except Exception as D: if not catch_exceptions:raise F=D;A=1;E=sys.exc_info() finally: sys.stdout.flush();K=H[0].getvalue() if B.mix_stderr:J=_A else:J=H[1].getvalue() return Result(runner=B,stdout_bytes=K,stderr_bytes=J,exit_code=A,exception=F,exc_info=E) @contextlib.contextmanager def isolated_filesystem(self): B=os.getcwd();A=tempfile.mkdtemp();os.chdir(A) try:yield A finally: os.chdir(B) try:shutil.rmtree(A) except OSError:pass
_E='replace' _D=False _C='\n' _B='\r\n' _A=None import contextlib,io,os,shlex,shutil,sys,tempfile from . import formatting,termui,utils from ._compat import _find_binary_reader class EchoingStdin: def __init__(A,input,output):A._input=input;A._output=output def __getattr__(A,x):return getattr(A._input,x) def _echo(A,rv):A._output.write(rv);return rv def read(A,n=-1):return A._echo(A._input.read(n)) def readline(A,n=-1):return A._echo(A._input.readline(n)) def readlines(A):return[A._echo(B)for B in A._input.readlines()] def __iter__(A):return iter((A._echo(B)for B in A._input)) def __repr__(A):return repr(A._input) def make_input_stream(input,charset): if hasattr(input,'read'): A=_find_binary_reader(input) if A is not _A:return A raise TypeError('Could not find binary reader for input stream.') if input is _A:input=b'' elif not isinstance(input,bytes):input=input.encode(charset) return io.BytesIO(input) class Result: def __init__(A,runner,stdout_bytes,stderr_bytes,exit_code,exception,exc_info=_A):A.runner=runner;A.stdout_bytes=stdout_bytes;A.stderr_bytes=stderr_bytes;A.exit_code=exit_code;A.exception=exception;A.exc_info=exc_info @property def output(self):return self.stdout @property def stdout(self):return self.stdout_bytes.decode(self.runner.charset,_E).replace(_B,_C) @property def stderr(self): A=self if A.stderr_bytes is _A:raise ValueError('stderr not separately captured') return A.stderr_bytes.decode(A.runner.charset,_E).replace(_B,_C) def __repr__(A):B=repr(A.exception)if A.exception else'okay';return f"<{type(A).__name__} {B}>" class CliRunner: def __init__(A,charset='utf-8',env=_A,echo_stdin=_D,mix_stderr=True):A.charset=charset;A.env=env or{};A.echo_stdin=echo_stdin;A.mix_stderr=mix_stderr def get_default_prog_name(A,cli):return cli.name or'root' def make_env(C,overrides=_A): A=overrides;B=dict(C.env) if A:B.update(A) return B @contextlib.contextmanager def isolation(self,input=_A,env=_A,color=_D): D=env;A=self;input=make_input_stream(input,A.charset);H=sys.stdin;I=sys.stdout;J=sys.stderr;K=formatting.FORCED_WIDTH;formatting.FORCED_WIDTH=80;D=A.make_env(D);E=io.BytesIO() if A.echo_stdin:input=EchoingStdin(input,E) input=io.TextIOWrapper(input,encoding=A.charset);sys.stdout=io.TextIOWrapper(E,encoding=A.charset) if not A.mix_stderr:F=io.BytesIO();sys.stderr=io.TextIOWrapper(F,encoding=A.charset) if A.mix_stderr:sys.stderr=sys.stdout sys.stdin=input def L(prompt=_A):sys.stdout.write(prompt or'');A=input.readline().rstrip(_B);sys.stdout.write(f"{A}\n");sys.stdout.flush();return A def M(prompt=_A):sys.stdout.write(f"{prompt or''}\n");sys.stdout.flush();return input.readline().rstrip(_B) def N(echo): A=sys.stdin.read(1) if echo:sys.stdout.write(A);sys.stdout.flush() return A O=color def P(stream=_A,color=_A): A=color if A is _A:return not O return not A Q=termui.visible_prompt_func;R=termui.hidden_prompt_func;S=termui._getchar;T=utils.should_strip_ansi;termui.visible_prompt_func=L;termui.hidden_prompt_func=M;termui._getchar=N;utils.should_strip_ansi=P;G={} try: for (B,C) in D.items(): G[B]=os.environ.get(B) if C is _A: try:del os.environ[B] except Exception:pass else:os.environ[B]=C yield(E,not A.mix_stderr and F) finally: for (B,C) in G.items(): if C is _A: try:del os.environ[B] except Exception:pass else:os.environ[B]=C sys.stdout=I;sys.stderr=J;sys.stdin=H;termui.visible_prompt_func=Q;termui.hidden_prompt_func=R;termui._getchar=S;utils.should_strip_ansi=T;formatting.FORCED_WIDTH=K def invoke(B,cli,args=_A,input=_A,env=_A,catch_exceptions=True,color=_D,**G): C=args;E=_A with B.isolation(input=input,env=env,color=color)as H: F=_A;A=0 if isinstance(C,str):C=shlex.split(C) try:I=G.pop('prog_name') except KeyError:I=B.get_default_prog_name(cli) try:cli.main(args=C or(),prog_name=I,**G) except SystemExit as D: E=sys.exc_info();A=D.code if A is _A:A=0 if A!=0:F=D if not isinstance(A,int):sys.stdout.write(str(A));sys.stdout.write(_C);A=1 except Exception as D: if not catch_exceptions:raise F=D;A=1;E=sys.exc_info() finally: sys.stdout.flush();K=H[0].getvalue() if B.mix_stderr:J=_A else:J=H[1].getvalue() return Result(runner=B,stdout_bytes=K,stderr_bytes=J,exit_code=A,exception=F,exc_info=E) @contextlib.contextmanager def isolated_filesystem(self): B=os.getcwd();A=tempfile.mkdtemp();os.chdir(A) try:yield A finally: os.chdir(B) try:shutil.rmtree(A) except OSError:pass
# Copyright 2019, The Emissions API Developers # https://emissions-api.org # This software is available under the terms of an MIT license. # See LICENSE fore more information. class RESTParamError(ValueError): """User-specific exception, used in :func:`~emissionsapi.utils.polygon_to_wkt`. """ pass def bounding_box_to_wkt(lon1, lat1, lon2, lat2): """Convert a bounding box specified by its top-left and bottom-right coordinates to a wkt string defining a polygon. """ return f'POLYGON(({lon1} {lat1},{lon1} {lat2},{lon2} {lat2},'\ f'{lon2} {lat1},{lon1} {lat1}))' def polygon_to_wkt(polygon): """Converts a list of points to a WKT string defining a polygon. :param polygon: List of values with every pair of values representing a consecutive vertex of the polygon. :type polygon: list :return: WKT defining the polygon. :rtype: str """ # check if element number is even if len(polygon) % 2 != 0: raise RESTParamError('Number of elements has to be even') # check if polygon is closed if polygon[-2:] != polygon[:2]: # close polygon by adding the first lon/lat pair at the end of the list polygon.extend(polygon[0:2]) # check if we have at least 3 (+1 to close the polygon) coordinate points if len(polygon) < 8: raise RESTParamError('At least 4 points are needed to define a ' 'polygon') # create list with x-y points as strings points = [] for index in range(0, len(polygon), 2): points.append(f'{polygon[index]} {polygon[index+1]}') # return string with points, joined by ',' return f'POLYGON(({','.join(points)}))'
# Copyright 2019, The Emissions API Developers # https://emissions-api.org # This software is available under the terms of an MIT license. # See LICENSE fore more information. class RESTParamError(ValueError): """User-specific exception, used in :func:`~emissionsapi.utils.polygon_to_wkt`. """ pass def bounding_box_to_wkt(lon1, lat1, lon2, lat2): """Convert a bounding box specified by its top-left and bottom-right coordinates to a wkt string defining a polygon. """ return f'POLYGON(({lon1} {lat1},{lon1} {lat2},{lon2} {lat2},'\ f'{lon2} {lat1},{lon1} {lat1}))' def polygon_to_wkt(polygon): """Converts a list of points to a WKT string defining a polygon. :param polygon: List of values with every pair of values representing a consecutive vertex of the polygon. :type polygon: list :return: WKT defining the polygon. :rtype: str """ # check if element number is even if len(polygon) % 2 != 0: raise RESTParamError('Number of elements has to be even') # check if polygon is closed if polygon[-2:] != polygon[:2]: # close polygon by adding the first lon/lat pair at the end of the list polygon.extend(polygon[0:2]) # check if we have at least 3 (+1 to close the polygon) coordinate points if len(polygon) < 8: raise RESTParamError('At least 4 points are needed to define a ' 'polygon') # create list with x-y points as strings points = [] for index in range(0, len(polygon), 2): points.append(f'{polygon[index]} {polygon[index+1]}') # return string with points, joined by ',' return f'POLYGON(({",".join(points)}))'
from falcon.testing import Result, TestClient from sustainerds.api.entities.user.model import UserDbModel ############################################################################### # model tests ############################################################################### def test_something(): d = UserDbModel() d.email = "tim@elbart.com" d.password = "secret123" ############################################################################### # endpoint tests ############################################################################### def test_register_user(test_client: TestClient): doc = {"email": "tim@elbart.com", "password": "bla123"} result: Result = test_client.simulate_post("/user", json=doc) assert result.status_code == 200 data = result.json result2: Result = test_client.simulate_get(f"/user/{data["id"]}") assert result2.status_code == 200 assert data == result2.json
from falcon.testing import Result, TestClient from sustainerds.api.entities.user.model import UserDbModel ############################################################################### # model tests ############################################################################### def test_something(): d = UserDbModel() d.email = "tim@elbart.com" d.password = "secret123" ############################################################################### # endpoint tests ############################################################################### def test_register_user(test_client: TestClient): doc = {"email": "tim@elbart.com", "password": "bla123"} result: Result = test_client.simulate_post("/user", json=doc) assert result.status_code == 200 data = result.json result2: Result = test_client.simulate_get(f"/user/{data['id']}") assert result2.status_code == 200 assert data == result2.json
from inspect import trace from fastapi import APIRouter, Depends, status, Response from typing import Optional from pydantic import BaseModel from core.config import ( ALLOWED_HOSTS, PROJECT_NAME, PROJECT_VERSION, API_PORT, DATABASE_NAME, NER_LABEL_COLLECTION, Feedback_Template_Collection, Feedback_Suggestion_Collection, LABEL_COLLECTION, LABEL_TRAIN_JOB_COLLECTION, ) from db.mongodb import AsyncIOMotorClient, get_database from bson.objectid import ObjectId import asyncio from typing import Any, Dict, AnyStr, List, Union from datetime import datetime from db.utils import convert_mongo_id from utils.trainer_communicate import asyncio_update_db_last_modify_time, set_trainer_restart_required import re JSONObject = Dict[AnyStr, Any] JSONArray = List[Any] JSONStructure = Union[JSONArray, JSONObject] router = APIRouter() LABEL_API_TAGS = ["Label"] example_text = "Dan Will be deemed to have completed its delivery obligations before 2021-7-5 if in Niall's opinion, the Jeep Car satisfies the Acceptance Criteria, and Niall notifies Dan in writing that it is accepting the Jeep Car." class create_new_label_body(BaseModel): user: str = "example@gmail.com" label_name: str = "Party" inherit: list = ["B-per", "I-per", "B-org", "I-org"] alias_as: list = ["String"] comment: str = """This is the example cased.""" tags: list = [] @router.post("/labels", tags = LABEL_API_TAGS, status_code=status.HTTP_200_OK) async def define_new_label(response: Response, data: create_new_label_body): result = re.findall(r'[;|(|)]',data.label_name) if len(result) != 0: response.status_code = status.HTTP_406_NOT_ACCEPTABLE return { "message": "Label Name must not contain \"" + '\", \"'.join(result) + '"' } mongo_client = await get_database() col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] result = col.find({"label_name": data.label_name}) result = await result.to_list(None) if len(result) != 0: result[0]["id"] = str(result[0]["_id"]) del result[0]["_id"] return { "message": f"Failed, Already have {data.label_name}", "label": result[0] } else: dataToStore = { "user": data.user, "label_name": data.label_name, "inherit": data.inherit, "alias_as": data.alias_as, "comment": data.comment, "tags": data.tags, "adapter": { "current_filename": "", "training_status": "", "history": [], "update_time": datetime.now(), }, "create_time": datetime.now(), } try: result = await col.insert_one(dataToStore) response.status_code = status.HTTP_201_CREATED return { "message": f"Success, new label {data.label_name} added." } except Exception as e: return { "message": f"Fail, please check the Error Message", "error_msg": str(e) } @router.get("/labels", tags = LABEL_API_TAGS) async def get_all_label(): mongo_client = await get_database() label_define_col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] labels = await label_define_col.find({}, {"_id": False}).to_list(None) return labels @router.get("/labels/{label_name}", tags = LABEL_API_TAGS) async def get_label_by_name(label_name, response: Response): mongo_client = await get_database() label_define_col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] label_data_col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] label = await label_define_col.find_one({"label_name": label_name}) if label == None: response.status_code = status.HTTP_404_NOT_FOUND return { "message": "Failed, Can't find this label name" } label = convert_mongo_id(label) texts = label_data_col.find( {"text_and_labels.labels": {"$in": [label_name] + label["inherit"]}}, {"text_and_labels": False} ) texts = await texts.to_list(None) texts_count = len(texts) label["data_count"] = texts_count label["description(auto_generated)"] = f"""Label "{label["label_name"]}" is to label out {label["label_name"]} in concerto contract. {label["label_name"]} also all the {label["inherit"]} labels in current and future dataset, and when training {label["alias_as"]}, text which labeled as Party will also be labeled positively. Currently, we have {label["data_count"]} datas contain this label in training dataset.""" return label class update_data_body(BaseModel): user: str = "example@gmail.com" tags: Optional[list] = [""] texts: JSONArray = [ { "text": "Eason", "labels": ["Party", "String"] }, { "text": "will", "labels": ["O"] }, { "text": "meet", "labels": ["O"] }, { "text": "Dan", "labels": ["Party", "String"] }, { "text": "at", "labels": ["O"] }, { "text": "2021-08-04 18:00", "labels": ["TemporalUnit"] }, { "text": ".", "labels": ["O"] }, ] from utils.tokenizer import tokenizer as roberta_tokenizer @router.post("/data/labeledText", tags = LABEL_API_TAGS, status_code=status.HTTP_200_OK) async def update_labeled_data(response: Response, data: update_data_body, refreash_trainer: bool = False): sentences = [] current_sentence = [] # Split the texts by dot. # So avoid CUDA Out of Memory at training by too long texts. # This won't affect NER model's performance. for text in data.texts: current_sentence.append(text) if text == {'text': '.', 'labels': ['O']}: # New Sentence, New data. sentences.append(current_sentence) current_sentence = [] sentences.append(current_sentence) mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] insert_ids = [] for sentence in sentences: token_and_labels = [] last_word_index = len(sentence)-1 for i, text in enumerate(sentence): if i != 0 and i != last_word_index: text_to_do = " " + text["text"] else: text_to_do = text["text"] tokens = roberta_tokenizer.tokenize(text_to_do) for j, token in enumerate(tokens): token_and_labels.append({ "token": token, "labels": text["labels"] }) dataToStore = { "user": data.user, "tags": data.tags, "text_and_labels": sentence, "token_and_labels": token_and_labels, "TimeStamp": datetime.now(), } # todo: Check the label in text all included. result = await col.insert_one(dataToStore) insert_ids.append(str(result.inserted_id)) await asyncio_update_db_last_modify_time(NER_LABEL_COLLECTION) if refreash_trainer: await set_trainer_restart_required(True) return { "message": "Add Success", "insert_ids": insert_ids } @router.get("/data/labeledText", tags = LABEL_API_TAGS) async def get_labeled_data(response: Response, label_name: str = None, detail: bool = False, start: int = 0, end: int = 10): if end == -1 and start == -1: end = None mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = col.find({"text_and_labels.labels": {"$in": [label_name]}}, {"text_and_labels": detail, "token_and_labels": detail}) result = await result.to_list(end) result = result[start:end] result = list(map(convert_mongo_id,result)) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } class custom_filter(BaseModel): mongo_filter: dict = {"user": "example@gmail.com"} @router.post("/data/labeledText/find:by:mongo:filter", tags = LABEL_API_TAGS) async def get_labeled_data_by_custom_filter(response: Response, data: custom_filter, detail: bool = False, start: int = 0, end: int = 10): if end == -1 and start == -1: end = None mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = col.find(data.mongo_filter, {"text_and_labels": detail, "token_and_labels": detail}) result = await result.to_list(end) result = result[start:end] result = list(map(convert_mongo_id,result)) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } @router.get("/data/labeledText/{_id}", tags = LABEL_API_TAGS) async def get_labeled_data_by_id(response: Response, _id, detail: bool = True): mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = await col.find_one({"_id": ObjectId(_id)}, {"text_and_labels": detail, "token_and_labels": detail}) if result: result["_id"] = str(result["_id"]) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } else: response.status_code = status.HTTP_404_NOT_FOUND return { "message": f"_id {_id} Not Found." } @router.delete("/data/labeledText/{_id}", tags = LABEL_API_TAGS) async def delete_labeled_data_by_id(response: Response, _id): mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = await col.delete_one({"_id": ObjectId(_id)}) if result.deleted_count: response.status_code = status.HTTP_204_NO_CONTENT return response else: response.status_code = status.HTTP_404_NOT_FOUND response.status_code = status.HTTP_200_OK return { "message": f"Failed, {_id} Not Found." }
from inspect import trace from fastapi import APIRouter, Depends, status, Response from typing import Optional from pydantic import BaseModel from core.config import ( ALLOWED_HOSTS, PROJECT_NAME, PROJECT_VERSION, API_PORT, DATABASE_NAME, NER_LABEL_COLLECTION, Feedback_Template_Collection, Feedback_Suggestion_Collection, LABEL_COLLECTION, LABEL_TRAIN_JOB_COLLECTION, ) from db.mongodb import AsyncIOMotorClient, get_database from bson.objectid import ObjectId import asyncio from typing import Any, Dict, AnyStr, List, Union from datetime import datetime from db.utils import convert_mongo_id from utils.trainer_communicate import asyncio_update_db_last_modify_time, set_trainer_restart_required import re JSONObject = Dict[AnyStr, Any] JSONArray = List[Any] JSONStructure = Union[JSONArray, JSONObject] router = APIRouter() LABEL_API_TAGS = ["Label"] example_text = "Dan Will be deemed to have completed its delivery obligations before 2021-7-5 if in Niall's opinion, the Jeep Car satisfies the Acceptance Criteria, and Niall notifies Dan in writing that it is accepting the Jeep Car." class create_new_label_body(BaseModel): user: str = "example@gmail.com" label_name: str = "Party" inherit: list = ["B-per", "I-per", "B-org", "I-org"] alias_as: list = ["String"] comment: str = """This is the example cased.""" tags: list = [] @router.post("/labels", tags = LABEL_API_TAGS, status_code=status.HTTP_200_OK) async def define_new_label(response: Response, data: create_new_label_body): result = re.findall(r'[;|(|)]',data.label_name) if len(result) != 0: response.status_code = status.HTTP_406_NOT_ACCEPTABLE return { "message": "Label Name must not contain \"" + '\", \"'.join(result) + '"' } mongo_client = await get_database() col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] result = col.find({"label_name": data.label_name}) result = await result.to_list(None) if len(result) != 0: result[0]["id"] = str(result[0]["_id"]) del result[0]["_id"] return { "message": f"Failed, Already have {data.label_name}", "label": result[0] } else: dataToStore = { "user": data.user, "label_name": data.label_name, "inherit": data.inherit, "alias_as": data.alias_as, "comment": data.comment, "tags": data.tags, "adapter": { "current_filename": "", "training_status": "", "history": [], "update_time": datetime.now(), }, "create_time": datetime.now(), } try: result = await col.insert_one(dataToStore) response.status_code = status.HTTP_201_CREATED return { "message": f"Success, new label {data.label_name} added." } except Exception as e: return { "message": f"Fail, please check the Error Message", "error_msg": str(e) } @router.get("/labels", tags = LABEL_API_TAGS) async def get_all_label(): mongo_client = await get_database() label_define_col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] labels = await label_define_col.find({}, {"_id": False}).to_list(None) return labels @router.get("/labels/{label_name}", tags = LABEL_API_TAGS) async def get_label_by_name(label_name, response: Response): mongo_client = await get_database() label_define_col = mongo_client[DATABASE_NAME][LABEL_COLLECTION] label_data_col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] label = await label_define_col.find_one({"label_name": label_name}) if label == None: response.status_code = status.HTTP_404_NOT_FOUND return { "message": "Failed, Can't find this label name" } label = convert_mongo_id(label) texts = label_data_col.find( {"text_and_labels.labels": {"$in": [label_name] + label["inherit"]}}, {"text_and_labels": False} ) texts = await texts.to_list(None) texts_count = len(texts) label["data_count"] = texts_count label["description(auto_generated)"] = f"""Label "{label["label_name"]}" is to label out {label["label_name"]} in concerto contract. {label["label_name"]} also all the {label["inherit"]} labels in current and future dataset, and when training {label["alias_as"]}, text which labeled as Party will also be labeled positively. Currently, we have {label["data_count"]} datas contain this label in training dataset.""" return label class update_data_body(BaseModel): user: str = "example@gmail.com" tags: Optional[list] = [""] texts: JSONArray = [ { "text": "Eason", "labels": ["Party", "String"] }, { "text": "will", "labels": ["O"] }, { "text": "meet", "labels": ["O"] }, { "text": "Dan", "labels": ["Party", "String"] }, { "text": "at", "labels": ["O"] }, { "text": "2021-08-04 18:00", "labels": ["TemporalUnit"] }, { "text": ".", "labels": ["O"] }, ] from utils.tokenizer import tokenizer as roberta_tokenizer @router.post("/data/labeledText", tags = LABEL_API_TAGS, status_code=status.HTTP_200_OK) async def update_labeled_data(response: Response, data: update_data_body, refreash_trainer: bool = False): sentences = [] current_sentence = [] # Split the texts by dot. # So avoid CUDA Out of Memory at training by too long texts. # This won't affect NER model's performance. for text in data.texts: current_sentence.append(text) if text == {'text': '.', 'labels': ['O']}: # New Sentence, New data. sentences.append(current_sentence) current_sentence = [] sentences.append(current_sentence) mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] insert_ids = [] for sentence in sentences: token_and_labels = [] last_word_index = len(sentence)-1 for i, text in enumerate(sentence): if i != 0 and i != last_word_index: text_to_do = " " + text["text"] else: text_to_do = text["text"] tokens = roberta_tokenizer.tokenize(text_to_do) for j, token in enumerate(tokens): token_and_labels.append({ "token": token, "labels": text["labels"] }) dataToStore = { "user": data.user, "tags": data.tags, "text_and_labels": sentence, "token_and_labels": token_and_labels, "TimeStamp": datetime.now(), } # todo: Check the label in text all included. result = await col.insert_one(dataToStore) insert_ids.append(str(result.inserted_id)) await asyncio_update_db_last_modify_time(NER_LABEL_COLLECTION) if refreash_trainer: await set_trainer_restart_required(True) return { "message": "Add Success", "insert_ids": insert_ids } @router.get("/data/labeledText", tags = LABEL_API_TAGS) async def get_labeled_data(response: Response, label_name: str = None, detail: bool = False, start: int = 0, end: int = 10): if end == -1 and start == -1: end = None mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = col.find({"text_and_labels.labels": {"$in": [label_name]}}, {"text_and_labels": detail, "token_and_labels": detail}) result = await result.to_list(end) result = result[start:end] result = list(map(convert_mongo_id,result)) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } class custom_filter(BaseModel): mongo_filter: dict = {"user": "example@gmail.com"} @router.post("/data/labeledText/find:by:mongo:filter", tags = LABEL_API_TAGS) async def get_labeled_data_by_custom_filter(response: Response, data: custom_filter, detail: bool = False, start: int = 0, end: int = 10): if end == -1 and start == -1: end = None mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = col.find(data.mongo_filter, {"text_and_labels": detail, "token_and_labels": detail}) result = await result.to_list(end) result = result[start:end] result = list(map(convert_mongo_id,result)) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } @router.get("/data/labeledText/{_id}", tags = LABEL_API_TAGS) async def get_labeled_data_by_id(response: Response, _id, detail: bool = True): mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = await col.find_one({"_id": ObjectId(_id)}, {"text_and_labels": detail, "token_and_labels": detail}) if result: result["_id"] = str(result["_id"]) response.status_code = status.HTTP_200_OK return { "message": "Success", "data": result } else: response.status_code = status.HTTP_404_NOT_FOUND return { "message": f"_id {_id} Not Found." } @router.delete("/data/labeledText/{_id}", tags = LABEL_API_TAGS) async def delete_labeled_data_by_id(response: Response, _id): mongo_client = await get_database() col = mongo_client[DATABASE_NAME][NER_LABEL_COLLECTION] result = await col.delete_one({"_id": ObjectId(_id)}) if result.deleted_count: response.status_code = status.HTTP_204_NO_CONTENT return response else: response.status_code = status.HTTP_404_NOT_FOUND response.status_code = status.HTTP_200_OK return { "message": f"Failed, {_id} Not Found." }
#!/usr/bin/env python3 import argparse import copy from datetime import datetime from distutils.util import strtobool from distutils.version import LooseVersion import functools import os import pathlib import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_extension from torch.testing._internal.common_utils import ( FILE_SCHEMA, IS_IN_CI, TEST_WITH_ROCM, shell, set_cwd, parser as common_parser, ) import torch.distributed as dist from typing import Dict, Optional, List REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # using tools/ to optimize test run. sys.path.append(str(REPO_ROOT)) from tools.testing.test_selections import ( export_S3_test_times, get_shard_based_on_S3, # NS: Disable target determination # get_slow_tests_based_on_S3, get_specified_test_cases, get_reordered_tests, get_test_case_configs, ) # NS: Disable target determination # from tools.testing.modulefinder_determinator import ( # should_run_test, # TARGET_DET_LIST, # ) HAVE_TEST_SELECTION_TOOLS = True except ImportError: HAVE_TEST_SELECTION_TOOLS = False print( "Unable to import test_selections from tools/testing. Running without test selection stats..." ) def discover_tests( base_dir: Optional[pathlib.Path] = None, blocklisted_patterns: Optional[List[str]] = None, blocklisted_tests: Optional[List[str]] = None, extra_tests: Optional[List[str]] = None) -> List[str]: """ Searches for all python files starting with test_ excluding one specified by patterns """ def skip_test_p(name: str) -> bool: rc = False if blocklisted_patterns is not None: rc |= any(name.startswith(pattern) for pattern in blocklisted_patterns) if blocklisted_tests is not None: rc |= name in blocklisted_tests return rc cwd = pathlib.Path(__file__).resolve().parent if base_dir is None else base_dir all_py_files = list(cwd.glob('**/test_*.py')) rc = [str(fname.relative_to(cwd))[:-3] for fname in all_py_files] # Invert slashes on Windows if sys.platform == "win32": rc = [name.replace('\\', '/') for name in rc] rc = [test for test in rc if not skip_test_p(test)] if extra_tests is not None: rc += extra_tests return sorted(rc) TESTS = discover_tests( blocklisted_patterns=[ 'ao', 'bottleneck_test', 'custom_backend', 'custom_operator', 'fx', # executed by test_fx.py 'jit', # executed by test_jit.py 'mobile', 'onnx', 'package', # executed by test_package.py 'quantization', # executed by test_quantization.py 'autograd', # executed by test_autograd.py ], blocklisted_tests=[ 'test_bundled_images', 'test_cpp_extensions_aot', 'test_determination', 'test_jit_fuser', 'test_jit_simple', 'test_jit_string', 'test_kernel_launch_checks', 'test_metal', 'test_nnapi', 'test_segment_reductions', 'test_static_runtime', 'test_throughput_benchmark', 'test_typing', "distributed/algorithms/ddp_comm_hooks/test_ddp_hooks", "distributed/algorithms/quantization/test_quantization", "distributed/bin/test_script", "distributed/elastic/multiprocessing/bin/test_script", "distributed/launcher/bin/test_script", "distributed/launcher/bin/test_script_init_method", "distributed/launcher/bin/test_script_is_torchelastic_launched", "distributed/launcher/bin/test_script_local_rank", "distributed/test_c10d_spawn", 'distributions/test_transforms', 'distributions/test_utils', ], extra_tests=[ "test_cpp_extensions_aot_ninja", "test_cpp_extensions_aot_no_ninja", "distributed/elastic/timer/api_test", "distributed/elastic/timer/local_timer_example", "distributed/elastic/timer/local_timer_test", "distributed/elastic/events/lib_test", "distributed/elastic/metrics/api_test", "distributed/elastic/utils/logging_test", "distributed/elastic/utils/util_test", "distributed/elastic/utils/distributed_test", "distributed/elastic/multiprocessing/api_test", "test_deploy", ] ) FSDP_TEST = [test for test in TESTS if test.startswith("distributed/fsdp")] # Tests need to be run with pytest. USE_PYTEST_LIST = [ "distributed/pipeline/sync/skip/test_api", "distributed/pipeline/sync/skip/test_gpipe", "distributed/pipeline/sync/skip/test_inspect_skip_layout", "distributed/pipeline/sync/skip/test_leak", "distributed/pipeline/sync/skip/test_portal", "distributed/pipeline/sync/skip/test_stash_pop", "distributed/pipeline/sync/skip/test_tracker", "distributed/pipeline/sync/skip/test_verify_skippables", "distributed/pipeline/sync/test_balance", "distributed/pipeline/sync/test_bugs", "distributed/pipeline/sync/test_checkpoint", "distributed/pipeline/sync/test_copy", "distributed/pipeline/sync/test_deferred_batch_norm", "distributed/pipeline/sync/test_dependency", "distributed/pipeline/sync/test_inplace", "distributed/pipeline/sync/test_microbatch", "distributed/pipeline/sync/test_phony", "distributed/pipeline/sync/test_pipe", "distributed/pipeline/sync/test_pipeline", "distributed/pipeline/sync/test_stream", "distributed/pipeline/sync/test_transparency", "distributed/pipeline/sync/test_worker", "distributions/test_constraints", "distributions/test_transforms", "distributions/test_utils", "test_typing", "distributed/elastic/events/lib_test", "distributed/elastic/agent/server/test/api_test", "test_deploy", ] WINDOWS_BLOCKLIST = [ "distributed/nn/jit/test_instantiator", "distributed/rpc/test_faulty_agent", "distributed/rpc/test_tensorpipe_agent", "distributed/rpc/test_share_memory", "distributed/rpc/cuda/test_tensorpipe_agent", "distributed/pipeline/sync/skip/test_api", "distributed/pipeline/sync/skip/test_gpipe", "distributed/pipeline/sync/skip/test_inspect_skip_layout", "distributed/pipeline/sync/skip/test_leak", "distributed/pipeline/sync/skip/test_portal", "distributed/pipeline/sync/skip/test_stash_pop", "distributed/pipeline/sync/skip/test_tracker", "distributed/pipeline/sync/skip/test_verify_skippables", "distributed/pipeline/sync/test_balance", "distributed/pipeline/sync/test_bugs", "distributed/pipeline/sync/test_checkpoint", "distributed/pipeline/sync/test_copy", "distributed/pipeline/sync/test_deferred_batch_norm", "distributed/pipeline/sync/test_dependency", "distributed/pipeline/sync/test_inplace", "distributed/pipeline/sync/test_microbatch", "distributed/pipeline/sync/test_phony", "distributed/pipeline/sync/test_pipe", "distributed/pipeline/sync/test_pipeline", "distributed/pipeline/sync/test_stream", "distributed/pipeline/sync/test_transparency", "distributed/pipeline/sync/test_worker", "distributed/elastic/agent/server/test/api_test", "distributed/elastic/multiprocessing/api_test", "distributed/_shard/checkpoint/test_checkpoint" "distributed/_shard/checkpoint/test_file_system_checkpoint" "distributed/_shard/sharding_spec/test_sharding_spec", "distributed/_shard/sharding_plan/test_sharding_plan", "distributed/_shard/sharded_tensor/test_megatron_prototype", "distributed/_shard/sharded_tensor/test_sharded_tensor", "distributed/_shard/sharded_tensor/test_sharded_tensor_reshard", "distributed/_shard/sharded_tensor/ops/test_chunk", "distributed/_shard/sharded_tensor/ops/test_elementwise_ops", "distributed/_shard/sharded_tensor/ops/test_embedding", "distributed/_shard/sharded_tensor/ops/test_embedding_bag", "distributed/_shard/sharded_tensor/ops/test_binary_cmp", "distributed/_shard/sharded_tensor/ops/test_init", "distributed/_shard/sharded_tensor/ops/test_linear", "distributed/_shard/sharded_tensor/ops/test_math_ops", "distributed/_shard/sharded_tensor/ops/test_matrix_ops", "distributed/_shard/sharded_tensor/ops/test_softmax", "distributed/_shard/sharded_optim/test_sharded_optim", "distributed/_shard/test_partial_tensor", "distributed/_shard/test_replicated_tensor", ] + FSDP_TEST ROCM_BLOCKLIST = [ "distributed/nn/jit/test_instantiator", "distributed/rpc/test_faulty_agent", "distributed/rpc/test_tensorpipe_agent", "distributed/rpc/test_share_memory", "distributed/rpc/cuda/test_tensorpipe_agent", "distributed/_shard/checkpoint/test_checkpoint" "distributed/_shard/checkpoint/test_file_system_checkpoint" "distributed/_shard/sharding_spec/test_sharding_spec", "distributed/_shard/sharding_plan/test_sharding_plan", "distributed/_shard/sharded_tensor/test_megatron_prototype", "distributed/_shard/sharded_tensor/test_sharded_tensor", "distributed/_shard/sharded_tensor/test_sharded_tensor_reshard", "distributed/_shard/sharded_tensor/ops/test_chunk", "distributed/_shard/sharded_tensor/ops/test_elementwise_ops", "distributed/_shard/sharded_tensor/ops/test_embedding", "distributed/_shard/sharded_tensor/ops/test_embedding_bag", "distributed/_shard/sharded_tensor/ops/test_binary_cmp", "distributed/_shard/sharded_tensor/ops/test_init", "distributed/_shard/sharded_tensor/ops/test_linear", "distributed/_shard/sharded_tensor/ops/test_math_ops", "distributed/_shard/sharded_tensor/ops/test_matrix_ops", "distributed/_shard/sharded_tensor/ops/test_softmax", "distributed/_shard/sharded_optim/test_sharded_optim", "distributed/_shard/test_partial_tensor", "distributed/_shard/test_replicated_tensor", "test_determination", "test_jit_legacy", "test_type_hints", "test_openmp", ] RUN_PARALLEL_BLOCKLIST = [ "test_cpp_extensions_jit", "test_jit_disabled", "test_mobile_optimizer", "test_multiprocessing", "test_multiprocessing_spawn", "test_namedtuple_return_api", "test_overrides", "test_show_pickle", "test_tensorexpr", "test_cuda_primary_ctx", ] + FSDP_TEST WINDOWS_COVERAGE_BLOCKLIST = [] # A subset of our TEST list that validates PyTorch's ops, modules, and autograd function as expected CORE_TEST_LIST = [ "test_autograd", "test_modules", "test_nn", "test_ops", "test_ops_gradients", "test_ops_jit", "test_torch" ] # the JSON file to store the S3 test stats TEST_TIMES_FILE = ".pytorch-test-times.json" # if a test file takes longer than 5 min, we add it to TARGET_DET_LIST SLOW_TEST_THRESHOLD = 300 DISTRIBUTED_TESTS_CONFIG = {} if dist.is_available(): DISTRIBUTED_TESTS_CONFIG["test"] = {"WORLD_SIZE": "1"} if not TEST_WITH_ROCM and dist.is_mpi_available(): DISTRIBUTED_TESTS_CONFIG["mpi"] = { "WORLD_SIZE": "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-mpi", } if dist.is_nccl_available(): DISTRIBUTED_TESTS_CONFIG["nccl"] = { "WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-nccl", } if dist.is_gloo_available(): DISTRIBUTED_TESTS_CONFIG["gloo"] = { "WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-gloo", } # https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python SIGNALS_TO_NAMES_DICT = { getattr(signal, n): n for n in dir(signal) if n.startswith("SIG") and "_" not in n } CPP_EXTENSIONS_ERROR = """ Ninja (https://ninja-build.org) is required for some of the C++ extensions tests, but it could not be found. Install ninja with `pip install ninja` or `conda install ninja`. Alternatively, disable said tests with `run_test.py --exclude test_cpp_extensions_aot_ninja test_cpp_extensions_jit`. """ PYTORCH_COLLECT_COVERAGE = bool(os.environ.get("PYTORCH_COLLECT_COVERAGE")) ENABLE_PR_HISTORY_REORDERING = bool( os.environ.get("ENABLE_PR_HISTORY_REORDERING", "0") == "1" ) JIT_EXECUTOR_TESTS = [ "test_jit_profiling", "test_jit_legacy", "test_jit_fuser_legacy", ] DISTRIBUTED_TESTS = [test for test in TESTS if test.startswith("distributed")] TESTS_REQUIRING_LAPACK = [ "distributions/test_constraints", "distributions/test_distributions", ] # Dictionary matching test modules (in TESTS) to lists of test cases (within that test_module) that would be run when # options.run_specified_test_cases is enabled. # For example: # { # "test_nn": ["test_doubletensor_avg_pool3d", "test_share_memory", "test_hook_requires_grad"], # ... # } # then for test_nn.py, we would ONLY run test_doubletensor_avg_pool3d, test_share_memory, and test_hook_requires_grad. SPECIFIED_TEST_CASES_DICT: Dict[str, List[str]] = {} # The file from which the SPECIFIED_TEST_CASES_DICT will be filled, a CSV of test cases that would be run when # options.run_specified_test_cases is enabled. SPECIFIED_TEST_CASES_FILE: str = ".pytorch_specified_test_cases.csv" def print_to_stderr(message): print(message, file=sys.stderr) def get_test_case_args(test_module, using_pytest) -> List[str]: args = [] # if test_module not specified or specified with '__all__' then run all tests if ( test_module not in SPECIFIED_TEST_CASES_DICT or "__all__" in SPECIFIED_TEST_CASES_DICT[test_module] ): return args if using_pytest: args.append("-k") args.append(" or ".join(SPECIFIED_TEST_CASES_DICT[test_module])) else: for test in SPECIFIED_TEST_CASES_DICT[test_module]: args.append("-k") args.append(test) return args def get_executable_command(options, allow_pytest, disable_coverage=False): if options.coverage and not disable_coverage: executable = ["coverage", "run", "--parallel-mode", "--source=torch"] else: executable = [sys.executable] if options.pytest: if allow_pytest: executable += ["-m", "pytest"] else: print_to_stderr( "Pytest cannot be used for this test. Falling back to unittest." ) return executable def run_test( test_module, test_directory, options, launcher_cmd=None, extra_unittest_args=None ): unittest_args = options.additional_unittest_args.copy() if options.verbose: unittest_args.append(f'-{'v'*options.verbose}') # in case of pytest if test_module in RUN_PARALLEL_BLOCKLIST: unittest_args = [ arg for arg in unittest_args if not arg.startswith("--run-parallel") ] if extra_unittest_args: assert isinstance(extra_unittest_args, list) unittest_args.extend(extra_unittest_args) # If using pytest, replace -f with equivalent -x if options.pytest: unittest_args = [arg if arg != "-f" else "-x" for arg in unittest_args] elif IS_IN_CI: # use the downloaded test cases configuration, not supported in pytest unittest_args.extend(["--import-slow-tests", "--import-disabled-tests"]) # Multiprocessing related tests cannot run with coverage. # Tracking issue: https://github.com/pytorch/pytorch/issues/50661 disable_coverage = ( sys.platform == "win32" and test_module in WINDOWS_COVERAGE_BLOCKLIST ) # Extra arguments are not supported with pytest executable = get_executable_command( options, allow_pytest=not extra_unittest_args, disable_coverage=disable_coverage ) # TODO: move this logic into common_utils.py instead of passing in "-k" individually # The following logic for running specified tests will only run for non-distributed tests, as those are dispatched # to test_distributed and not run_test (this function) if options.run_specified_test_cases: unittest_args.extend(get_test_case_args(test_module, "pytest" in executable)) # Can't call `python -m unittest test_*` here because it doesn't run code # in `if __name__ == '__main__': `. So call `python test_*.py` instead. argv = [test_module + ".py"] + unittest_args command = (launcher_cmd or []) + executable + argv print_to_stderr("Executing {} ... [{}]".format(command, datetime.now())) return shell(command, test_directory) def test_cuda_primary_ctx(test_module, test_directory, options): return run_test( test_module, test_directory, options, extra_unittest_args=["--subprocess"] ) run_test_with_subprocess = functools.partial(run_test, extra_unittest_args=["--subprocess"]) def get_run_test_with_subprocess_fn(): return lambda test_module, test_directory, options: run_test_with_subprocess(test_module, test_directory, options) def _test_cpp_extensions_aot(test_directory, options, use_ninja): if use_ninja: try: cpp_extension.verify_ninja_availability() except RuntimeError: print(CPP_EXTENSIONS_ERROR) return 1 # Wipe the build folder, if it exists already cpp_extensions_test_dir = os.path.join(test_directory, "cpp_extensions") cpp_extensions_test_build_dir = os.path.join(cpp_extensions_test_dir, "build") if os.path.exists(cpp_extensions_test_build_dir): shutil.rmtree(cpp_extensions_test_build_dir) # Build the test cpp extensions modules shell_env = os.environ.copy() shell_env["USE_NINJA"] = str(1 if use_ninja else 0) cmd = [sys.executable, "setup.py", "install", "--root", "./install"] return_code = shell(cmd, cwd=cpp_extensions_test_dir, env=shell_env) if return_code != 0: return return_code if sys.platform != "win32": return_code = shell( cmd, cwd=os.path.join(cpp_extensions_test_dir, "no_python_abi_suffix_test"), env=shell_env, ) if return_code != 0: return return_code # "install" the test modules and run tests python_path = os.environ.get("PYTHONPATH", "") from shutil import copyfile test_module = "test_cpp_extensions_aot" + ("_ninja" if use_ninja else "_no_ninja") copyfile( test_directory + "/test_cpp_extensions_aot.py", test_directory + "/" + test_module + ".py", ) try: cpp_extensions = os.path.join(test_directory, "cpp_extensions") install_directory = "" # install directory is the one that is named site-packages for root, directories, _ in os.walk(os.path.join(cpp_extensions, "install")): for directory in directories: if "-packages" in directory: install_directory = os.path.join(root, directory) assert install_directory, "install_directory must not be empty" os.environ["PYTHONPATH"] = os.pathsep.join([install_directory, python_path]) return run_test(test_module, test_directory, options) finally: os.environ["PYTHONPATH"] = python_path if os.path.exists(test_directory + "/" + test_module + ".py"): os.remove(test_directory + "/" + test_module + ".py") def test_cpp_extensions_aot_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot(test_directory, options, use_ninja=True) def test_cpp_extensions_aot_no_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot(test_directory, options, use_ninja=False) def test_distributed(test_module, test_directory, options): # MPI tests are broken with Python-3.9 mpi_available = subprocess.call( "command -v mpiexec", shell=True ) == 0 and sys.version_info < (3, 9) if options.verbose and not mpi_available: print_to_stderr("MPI not available -- MPI backend tests will be skipped") config = DISTRIBUTED_TESTS_CONFIG for backend, env_vars in config.items(): if sys.platform == "win32" and backend != "gloo": continue if backend == "mpi" and not mpi_available: continue for with_init_file in {True, False}: if sys.platform == "win32" and not with_init_file: continue tmp_dir = tempfile.mkdtemp() if options.verbose: init_str = "with {} init_method" with_init = init_str.format("file" if with_init_file else "env") print_to_stderr( "Running distributed tests for the {} backend {}".format( backend, with_init ) ) old_environ = dict(os.environ) os.environ["TEMP_DIR"] = tmp_dir os.environ["BACKEND"] = backend os.environ["INIT_METHOD"] = "env://" os.environ.update(env_vars) if with_init_file: if test_module == "test_distributed_spawn": init_method = f"{FILE_SCHEMA}{tmp_dir}/" else: init_method = f"{FILE_SCHEMA}{tmp_dir}/shared_init_file" os.environ["INIT_METHOD"] = init_method try: os.mkdir(os.path.join(tmp_dir, "barrier")) os.mkdir(os.path.join(tmp_dir, "test_dir")) if backend == "mpi": # test mpiexec for --noprefix option with open(os.devnull, "w") as devnull: allowrunasroot_opt = ( "--allow-run-as-root" if subprocess.call( 'mpiexec --allow-run-as-root -n 1 bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT, ) == 0 else "" ) noprefix_opt = ( "--noprefix" if subprocess.call( f'mpiexec {allowrunasroot_opt} -n 1 --noprefix bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT, ) == 0 else "" ) mpiexec = ["mpiexec", "-n", "3", noprefix_opt, allowrunasroot_opt] return_code = run_test( test_module, test_directory, options, launcher_cmd=mpiexec ) else: return_code = run_test(test_module, test_directory, options, extra_unittest_args=["--subprocess"]) if return_code != 0: return return_code finally: shutil.rmtree(tmp_dir) os.environ.clear() os.environ.update(old_environ) return 0 CUSTOM_HANDLERS = { "test_cuda_primary_ctx": test_cuda_primary_ctx, "test_cpp_extensions_aot_no_ninja": test_cpp_extensions_aot_no_ninja, "test_cpp_extensions_aot_ninja": test_cpp_extensions_aot_ninja, "distributed/test_distributed_spawn": test_distributed, "distributed/test_c10d_nccl": get_run_test_with_subprocess_fn(), "distributed/test_c10d_gloo": get_run_test_with_subprocess_fn(), "distributed/test_c10d_common": get_run_test_with_subprocess_fn(), "distributed/test_c10d_spawn_gloo": get_run_test_with_subprocess_fn(), "distributed/test_c10d_spawn_nccl": get_run_test_with_subprocess_fn(), "distributed/test_store": get_run_test_with_subprocess_fn(), "distributed/test_pg_wrapper": get_run_test_with_subprocess_fn(), "distributed/rpc/test_faulty_agent": get_run_test_with_subprocess_fn(), "distributed/rpc/test_tensorpipe_agent": get_run_test_with_subprocess_fn(), "distributed/rpc/test_share_memory": get_run_test_with_subprocess_fn(), "distributed/rpc/cuda/test_tensorpipe_agent": get_run_test_with_subprocess_fn(), } def parse_test_module(test): return test.split(".")[0] class TestChoices(list): def __init__(self, *args, **kwargs): super(TestChoices, self).__init__(args[0]) def __contains__(self, item): return list.__contains__(self, parse_test_module(item)) def parse_args(): parser = argparse.ArgumentParser( description="Run the PyTorch unit test suite", epilog="where TESTS is any of: {}".format(", ".join(TESTS)), formatter_class=argparse.RawTextHelpFormatter, parents=[common_parser] ) parser.add_argument( "-v", "--verbose", action="count", default=0, help="print verbose information and test-by-test results", ) parser.add_argument("--jit", "--jit", action="store_true", help="run all jit tests") parser.add_argument( "--distributed-tests", "--distributed-tests", action="store_true", help="run all distributed tests", ) parser.add_argument( "-core", "--core", action="store_true", help="Only run core tests, or tests that validate PyTorch's ops, modules," "and autograd. They are defined by CORE_TEST_LIST." ) parser.add_argument( "-pt", "--pytest", action="store_true", help="If true, use `pytest` to execute the tests. E.g., this runs " "TestTorch with pytest in verbose and coverage mode: " "python run_test.py -vci torch -pt", ) parser.add_argument( "-c", "--coverage", action="store_true", help="enable coverage", default=PYTORCH_COLLECT_COVERAGE, ) parser.add_argument( "-i", "--include", nargs="+", choices=TestChoices(TESTS), default=TESTS, metavar="TESTS", help="select a set of tests to include (defaults to ALL tests)." " tests must be a part of the TESTS list defined in run_test.py", ) parser.add_argument( "-x", "--exclude", nargs="+", choices=TESTS, metavar="TESTS", default=[], help="select a set of tests to exclude", ) parser.add_argument( "-f", "--first", choices=TESTS, metavar="TESTS", help="select the test to start from (excludes previous tests)", ) parser.add_argument( "-l", "--last", choices=TESTS, metavar="TESTS", help="select the last test to run (excludes following tests)", ) parser.add_argument( "--bring-to-front", nargs="+", choices=TestChoices(TESTS), default=[], metavar="TESTS", help="select a set of tests to run first. This can be used in situations" " where you want to run all tests, but care more about some set, " "e.g. after making a change to a specific component", ) parser.add_argument( "--ignore-win-blocklist", action="store_true", help="always run blocklisted windows tests", ) # NS: Disable target determination until it can be made more reliable # parser.add_argument( # "--determine-from", # help="File of affected source filenames to determine which tests to run.", # ) parser.add_argument( "--continue-through-error", action="store_true", help="Runs the full test suite despite one of the tests failing", default=strtobool(os.environ.get("CONTINUE_THROUGH_ERROR", "False")), ) parser.add_argument( "additional_unittest_args", nargs="*", help="additional arguments passed through to unittest, e.g., " "python run_test.py -i sparse -- TestSparse.test_factory_size_check", ) parser.add_argument( "--export-past-test-times", nargs="?", type=str, const=TEST_TIMES_FILE, help="dumps test times from previous S3 stats into a file, format JSON", ) parser.add_argument( "--shard", nargs=2, type=int, help="runs a shard of the tests (taking into account other selections), e.g., " "--shard 2 3 will break up the selected tests into 3 shards and run the tests " "in the 2nd shard (the first number should not exceed the second)", ) parser.add_argument( "--exclude-jit-executor", action="store_true", help="exclude tests that are run for a specific jit config", ) parser.add_argument( "--exclude-distributed-tests", action="store_true", help="exclude distributed tests", ) parser.add_argument( "--run-specified-test-cases", nargs="?", type=str, const=SPECIFIED_TEST_CASES_FILE, help="load specified test cases file dumped from previous OSS CI stats, format CSV. " " If all test cases should run for a <test_module> please add a single row: \n" " test_filename,test_case_name\n" " ...\n" " <test_module>,__all__\n" " ...\n" 'how we use the stats will be based on option "--use-specified-test-cases-by".', ) parser.add_argument( "--use-specified-test-cases-by", type=str, choices=["include", "bring-to-front"], default="include", help='used together with option "--run-specified-test-cases". When specified test case ' "file is set, this option allows the user to control whether to only run the specified test " "modules or to simply bring the specified modules to front and also run the remaining " "modules. Note: regardless of this option, we will only run the specified test cases " " within a specified test module. For unspecified test modules with the bring-to-front " "option, all test cases will be run, as one may expect.", ) parser.add_argument( "--dry-run", action="store_true", help="Only list the test that will run.", ) return parser.parse_args() def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index`=False) and/or ``options.last``(:attr:`find_last_index`=True) are used. :attr:`selected_tests` can be a list that contains multiple consequent occurrences of tests as part of the same test module, e.g.: ``` selected_tests = ['autograd', 'cuda', **'torch.TestTorch.test_acos', 'torch.TestTorch.test_tan', 'torch.TestTorch.test_add'**, 'utils'] ``` If :attr:`test`='torch' and :attr:`find_last_index`=False, result should be **2**. If :attr:`test`='torch' and :attr:`find_last_index`=True, result should be **4**. Args: test (str): Name of test to lookup selected_tests (list): List of tests find_last_index (bool, optional): should we lookup the index of first or last occurrence (first is default) Returns: index of the first or last occurrence of the given test """ idx = 0 found_idx = -1 for t in selected_tests: if t.startswith(test): found_idx = idx if not find_last_index: break idx += 1 return found_idx def exclude_tests(exclude_list, selected_tests, exclude_message=None): for exclude_test in exclude_list: tests_copy = selected_tests[:] for test in tests_copy: if test.startswith(exclude_test): if exclude_message is not None: print_to_stderr("Excluding {} {}".format(test, exclude_message)) selected_tests.remove(test) return selected_tests def get_selected_tests(options): # First make sure run specific test cases options are processed. if options.run_specified_test_cases: if options.use_specified_test_cases_by == "include": options.include = list(SPECIFIED_TEST_CASES_DICT.keys()) elif options.use_specified_test_cases_by == "bring-to-front": options.bring_to_front = list(SPECIFIED_TEST_CASES_DICT.keys()) selected_tests = options.include # filter if there's JIT only and distributed only test options if options.jit: selected_tests = list( filter(lambda test_name: "jit" in test_name, selected_tests) ) if options.distributed_tests: selected_tests = list( filter(lambda test_name: test_name in DISTRIBUTED_TESTS, selected_tests) ) # Filter to only run core tests when --core option is specified if options.core: selected_tests = list( filter(lambda test_name: test_name in CORE_TEST_LIST, selected_tests) ) # process reordering if options.bring_to_front: to_front = set(options.bring_to_front) selected_tests = options.bring_to_front + list( filter(lambda name: name not in to_front, selected_tests) ) if options.first: first_index = find_test_index(options.first, selected_tests) selected_tests = selected_tests[first_index:] if options.last: last_index = find_test_index(options.last, selected_tests, find_last_index=True) selected_tests = selected_tests[: last_index + 1] # process exclusion if options.exclude_jit_executor: options.exclude.extend(JIT_EXECUTOR_TESTS) if options.exclude_distributed_tests: options.exclude.extend(DISTRIBUTED_TESTS) # these tests failing in CUDA 11.6 temporary disabling. issue https://github.com/pytorch/pytorch/issues/75375 if torch.version.cuda is not None and LooseVersion(torch.version.cuda) == "11.6": options.exclude.extend(["distributions/test_constraints"]) selected_tests = exclude_tests(options.exclude, selected_tests) if sys.platform == "win32" and not options.ignore_win_blocklist: target_arch = os.environ.get("VSCMD_ARG_TGT_ARCH") if target_arch != "x64": WINDOWS_BLOCKLIST.append("cpp_extensions_aot_no_ninja") WINDOWS_BLOCKLIST.append("cpp_extensions_aot_ninja") WINDOWS_BLOCKLIST.append("cpp_extensions_jit") WINDOWS_BLOCKLIST.append("jit") WINDOWS_BLOCKLIST.append("jit_fuser") # This is exception that's caused by this issue https://github.com/pytorch/pytorch/issues/69460 # This below code should be removed once this issue is solved if torch.version.cuda is not None and LooseVersion(torch.version.cuda) >= "11.5": WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot") WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot_ninja") WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot_no_ninja") selected_tests = exclude_tests(WINDOWS_BLOCKLIST, selected_tests, "on Windows") elif TEST_WITH_ROCM: selected_tests = exclude_tests(ROCM_BLOCKLIST, selected_tests, "on ROCm") # sharding if options.shard: assert len(options.shard) == 2, "Unexpected shard format" assert min(options.shard) > 0, "Shards must be positive numbers" which_shard, num_shards = options.shard assert ( which_shard <= num_shards ), "Selected shard must be less than or equal to total number of shards" assert num_shards <= len( selected_tests ), f"Number of shards must be less than {len(selected_tests)}" # TODO: fix this to use test_times_filename, but currently this is not working # because setting the export arg immeidately halts the test execution. selected_tests = get_shard_based_on_S3( which_shard, num_shards, selected_tests, TEST_TIMES_FILE ) # skip all distributed tests if distributed package is not available. if not dist.is_available(): selected_tests = exclude_tests(DISTRIBUTED_TESTS, selected_tests, "PyTorch is built without distributed support.") # skip tests that require LAPACK when it's not available if not torch._C.has_lapack: selected_tests = exclude_tests(TESTS_REQUIRING_LAPACK, selected_tests, "PyTorch is built without LAPACK support.") return selected_tests def run_test_module(test: str, test_directory: str, options) -> Optional[str]: test_module = parse_test_module(test) # Printing the date here can help diagnose which tests are slow print_to_stderr("Running {} ... [{}]".format(test, datetime.now())) handler = CUSTOM_HANDLERS.get(test_module, run_test) return_code = handler(test_module, test_directory, options) assert isinstance(return_code, int) and not isinstance( return_code, bool ), "Return code should be an integer" if return_code == 0: return None message = f"{test} failed!" if return_code < 0: # subprocess.Popen returns the child process' exit signal as # return code -N, where N is the signal number. signal_name = SIGNALS_TO_NAMES_DICT[-return_code] message += f" Received signal: {signal_name}" return message def main(): options = parse_args() # TODO: move this export & download function in tools/ folder test_times_filename = options.export_past_test_times if test_times_filename: print( f"Exporting past test times from S3 to {test_times_filename}, no tests will be run." ) export_S3_test_times(test_times_filename) return specified_test_cases_filename = options.run_specified_test_cases if specified_test_cases_filename: print( f"Loading specified test cases to run from {specified_test_cases_filename}." ) global SPECIFIED_TEST_CASES_DICT SPECIFIED_TEST_CASES_DICT = get_specified_test_cases( specified_test_cases_filename, TESTS ) test_directory = str(REPO_ROOT / "test") selected_tests = get_selected_tests(options) if options.verbose: print_to_stderr("Selected tests:\n {}".format("\n ".join(selected_tests))) if options.dry_run: return if options.coverage and not PYTORCH_COLLECT_COVERAGE: shell(["coverage", "erase"]) # NS: Disable target determination until it can be made more reliable # if options.determine_from is not None and os.path.exists(options.determine_from): # slow_tests = get_slow_tests_based_on_S3( # TESTS, TARGET_DET_LIST, SLOW_TEST_THRESHOLD # ) # print_to_stderr( # "Added the following tests to target_det tests as calculated based on S3:" # ) # print_to_stderr(slow_tests) # with open(options.determine_from, "r") as fh: # touched_files = [ # os.path.normpath(name.strip()) # for name in fh.read().split("\n") # if len(name.strip()) > 0 # ] # # HACK: Ensure the 'test' paths can be traversed by Modulefinder # sys.path.append(test_directory) # selected_tests = [ # test # for test in selected_tests # if should_run_test( # TARGET_DET_LIST + slow_tests, test, touched_files, options # ) # ] # sys.path.remove(test_directory) if IS_IN_CI: selected_tests = get_reordered_tests( selected_tests, ENABLE_PR_HISTORY_REORDERING ) # downloading test cases configuration to local environment get_test_case_configs(dirpath=test_directory) has_failed = False failure_messages = [] try: for test in selected_tests: options_clone = copy.deepcopy(options) if test in USE_PYTEST_LIST: options_clone.pytest = True err_message = run_test_module(test, test_directory, options_clone) if err_message is None: continue has_failed = True failure_messages.append(err_message) if not options_clone.continue_through_error: raise RuntimeError(err_message) print_to_stderr(err_message) finally: if options.coverage: from coverage import Coverage with set_cwd(test_directory): cov = Coverage() if PYTORCH_COLLECT_COVERAGE: cov.load() cov.combine(strict=False) cov.save() if not PYTORCH_COLLECT_COVERAGE: cov.html_report() if options.continue_through_error and has_failed: for err in failure_messages: print_to_stderr(err) sys.exit(1) if __name__ == "__main__": main()
#!/usr/bin/env python3 import argparse import copy from datetime import datetime from distutils.util import strtobool from distutils.version import LooseVersion import functools import os import pathlib import shutil import signal import subprocess import sys import tempfile import torch from torch.utils import cpp_extension from torch.testing._internal.common_utils import ( FILE_SCHEMA, IS_IN_CI, TEST_WITH_ROCM, shell, set_cwd, parser as common_parser, ) import torch.distributed as dist from typing import Dict, Optional, List REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent try: # using tools/ to optimize test run. sys.path.append(str(REPO_ROOT)) from tools.testing.test_selections import ( export_S3_test_times, get_shard_based_on_S3, # NS: Disable target determination # get_slow_tests_based_on_S3, get_specified_test_cases, get_reordered_tests, get_test_case_configs, ) # NS: Disable target determination # from tools.testing.modulefinder_determinator import ( # should_run_test, # TARGET_DET_LIST, # ) HAVE_TEST_SELECTION_TOOLS = True except ImportError: HAVE_TEST_SELECTION_TOOLS = False print( "Unable to import test_selections from tools/testing. Running without test selection stats..." ) def discover_tests( base_dir: Optional[pathlib.Path] = None, blocklisted_patterns: Optional[List[str]] = None, blocklisted_tests: Optional[List[str]] = None, extra_tests: Optional[List[str]] = None) -> List[str]: """ Searches for all python files starting with test_ excluding one specified by patterns """ def skip_test_p(name: str) -> bool: rc = False if blocklisted_patterns is not None: rc |= any(name.startswith(pattern) for pattern in blocklisted_patterns) if blocklisted_tests is not None: rc |= name in blocklisted_tests return rc cwd = pathlib.Path(__file__).resolve().parent if base_dir is None else base_dir all_py_files = list(cwd.glob('**/test_*.py')) rc = [str(fname.relative_to(cwd))[:-3] for fname in all_py_files] # Invert slashes on Windows if sys.platform == "win32": rc = [name.replace('\\', '/') for name in rc] rc = [test for test in rc if not skip_test_p(test)] if extra_tests is not None: rc += extra_tests return sorted(rc) TESTS = discover_tests( blocklisted_patterns=[ 'ao', 'bottleneck_test', 'custom_backend', 'custom_operator', 'fx', # executed by test_fx.py 'jit', # executed by test_jit.py 'mobile', 'onnx', 'package', # executed by test_package.py 'quantization', # executed by test_quantization.py 'autograd', # executed by test_autograd.py ], blocklisted_tests=[ 'test_bundled_images', 'test_cpp_extensions_aot', 'test_determination', 'test_jit_fuser', 'test_jit_simple', 'test_jit_string', 'test_kernel_launch_checks', 'test_metal', 'test_nnapi', 'test_segment_reductions', 'test_static_runtime', 'test_throughput_benchmark', 'test_typing', "distributed/algorithms/ddp_comm_hooks/test_ddp_hooks", "distributed/algorithms/quantization/test_quantization", "distributed/bin/test_script", "distributed/elastic/multiprocessing/bin/test_script", "distributed/launcher/bin/test_script", "distributed/launcher/bin/test_script_init_method", "distributed/launcher/bin/test_script_is_torchelastic_launched", "distributed/launcher/bin/test_script_local_rank", "distributed/test_c10d_spawn", 'distributions/test_transforms', 'distributions/test_utils', ], extra_tests=[ "test_cpp_extensions_aot_ninja", "test_cpp_extensions_aot_no_ninja", "distributed/elastic/timer/api_test", "distributed/elastic/timer/local_timer_example", "distributed/elastic/timer/local_timer_test", "distributed/elastic/events/lib_test", "distributed/elastic/metrics/api_test", "distributed/elastic/utils/logging_test", "distributed/elastic/utils/util_test", "distributed/elastic/utils/distributed_test", "distributed/elastic/multiprocessing/api_test", "test_deploy", ] ) FSDP_TEST = [test for test in TESTS if test.startswith("distributed/fsdp")] # Tests need to be run with pytest. USE_PYTEST_LIST = [ "distributed/pipeline/sync/skip/test_api", "distributed/pipeline/sync/skip/test_gpipe", "distributed/pipeline/sync/skip/test_inspect_skip_layout", "distributed/pipeline/sync/skip/test_leak", "distributed/pipeline/sync/skip/test_portal", "distributed/pipeline/sync/skip/test_stash_pop", "distributed/pipeline/sync/skip/test_tracker", "distributed/pipeline/sync/skip/test_verify_skippables", "distributed/pipeline/sync/test_balance", "distributed/pipeline/sync/test_bugs", "distributed/pipeline/sync/test_checkpoint", "distributed/pipeline/sync/test_copy", "distributed/pipeline/sync/test_deferred_batch_norm", "distributed/pipeline/sync/test_dependency", "distributed/pipeline/sync/test_inplace", "distributed/pipeline/sync/test_microbatch", "distributed/pipeline/sync/test_phony", "distributed/pipeline/sync/test_pipe", "distributed/pipeline/sync/test_pipeline", "distributed/pipeline/sync/test_stream", "distributed/pipeline/sync/test_transparency", "distributed/pipeline/sync/test_worker", "distributions/test_constraints", "distributions/test_transforms", "distributions/test_utils", "test_typing", "distributed/elastic/events/lib_test", "distributed/elastic/agent/server/test/api_test", "test_deploy", ] WINDOWS_BLOCKLIST = [ "distributed/nn/jit/test_instantiator", "distributed/rpc/test_faulty_agent", "distributed/rpc/test_tensorpipe_agent", "distributed/rpc/test_share_memory", "distributed/rpc/cuda/test_tensorpipe_agent", "distributed/pipeline/sync/skip/test_api", "distributed/pipeline/sync/skip/test_gpipe", "distributed/pipeline/sync/skip/test_inspect_skip_layout", "distributed/pipeline/sync/skip/test_leak", "distributed/pipeline/sync/skip/test_portal", "distributed/pipeline/sync/skip/test_stash_pop", "distributed/pipeline/sync/skip/test_tracker", "distributed/pipeline/sync/skip/test_verify_skippables", "distributed/pipeline/sync/test_balance", "distributed/pipeline/sync/test_bugs", "distributed/pipeline/sync/test_checkpoint", "distributed/pipeline/sync/test_copy", "distributed/pipeline/sync/test_deferred_batch_norm", "distributed/pipeline/sync/test_dependency", "distributed/pipeline/sync/test_inplace", "distributed/pipeline/sync/test_microbatch", "distributed/pipeline/sync/test_phony", "distributed/pipeline/sync/test_pipe", "distributed/pipeline/sync/test_pipeline", "distributed/pipeline/sync/test_stream", "distributed/pipeline/sync/test_transparency", "distributed/pipeline/sync/test_worker", "distributed/elastic/agent/server/test/api_test", "distributed/elastic/multiprocessing/api_test", "distributed/_shard/checkpoint/test_checkpoint" "distributed/_shard/checkpoint/test_file_system_checkpoint" "distributed/_shard/sharding_spec/test_sharding_spec", "distributed/_shard/sharding_plan/test_sharding_plan", "distributed/_shard/sharded_tensor/test_megatron_prototype", "distributed/_shard/sharded_tensor/test_sharded_tensor", "distributed/_shard/sharded_tensor/test_sharded_tensor_reshard", "distributed/_shard/sharded_tensor/ops/test_chunk", "distributed/_shard/sharded_tensor/ops/test_elementwise_ops", "distributed/_shard/sharded_tensor/ops/test_embedding", "distributed/_shard/sharded_tensor/ops/test_embedding_bag", "distributed/_shard/sharded_tensor/ops/test_binary_cmp", "distributed/_shard/sharded_tensor/ops/test_init", "distributed/_shard/sharded_tensor/ops/test_linear", "distributed/_shard/sharded_tensor/ops/test_math_ops", "distributed/_shard/sharded_tensor/ops/test_matrix_ops", "distributed/_shard/sharded_tensor/ops/test_softmax", "distributed/_shard/sharded_optim/test_sharded_optim", "distributed/_shard/test_partial_tensor", "distributed/_shard/test_replicated_tensor", ] + FSDP_TEST ROCM_BLOCKLIST = [ "distributed/nn/jit/test_instantiator", "distributed/rpc/test_faulty_agent", "distributed/rpc/test_tensorpipe_agent", "distributed/rpc/test_share_memory", "distributed/rpc/cuda/test_tensorpipe_agent", "distributed/_shard/checkpoint/test_checkpoint" "distributed/_shard/checkpoint/test_file_system_checkpoint" "distributed/_shard/sharding_spec/test_sharding_spec", "distributed/_shard/sharding_plan/test_sharding_plan", "distributed/_shard/sharded_tensor/test_megatron_prototype", "distributed/_shard/sharded_tensor/test_sharded_tensor", "distributed/_shard/sharded_tensor/test_sharded_tensor_reshard", "distributed/_shard/sharded_tensor/ops/test_chunk", "distributed/_shard/sharded_tensor/ops/test_elementwise_ops", "distributed/_shard/sharded_tensor/ops/test_embedding", "distributed/_shard/sharded_tensor/ops/test_embedding_bag", "distributed/_shard/sharded_tensor/ops/test_binary_cmp", "distributed/_shard/sharded_tensor/ops/test_init", "distributed/_shard/sharded_tensor/ops/test_linear", "distributed/_shard/sharded_tensor/ops/test_math_ops", "distributed/_shard/sharded_tensor/ops/test_matrix_ops", "distributed/_shard/sharded_tensor/ops/test_softmax", "distributed/_shard/sharded_optim/test_sharded_optim", "distributed/_shard/test_partial_tensor", "distributed/_shard/test_replicated_tensor", "test_determination", "test_jit_legacy", "test_type_hints", "test_openmp", ] RUN_PARALLEL_BLOCKLIST = [ "test_cpp_extensions_jit", "test_jit_disabled", "test_mobile_optimizer", "test_multiprocessing", "test_multiprocessing_spawn", "test_namedtuple_return_api", "test_overrides", "test_show_pickle", "test_tensorexpr", "test_cuda_primary_ctx", ] + FSDP_TEST WINDOWS_COVERAGE_BLOCKLIST = [] # A subset of our TEST list that validates PyTorch's ops, modules, and autograd function as expected CORE_TEST_LIST = [ "test_autograd", "test_modules", "test_nn", "test_ops", "test_ops_gradients", "test_ops_jit", "test_torch" ] # the JSON file to store the S3 test stats TEST_TIMES_FILE = ".pytorch-test-times.json" # if a test file takes longer than 5 min, we add it to TARGET_DET_LIST SLOW_TEST_THRESHOLD = 300 DISTRIBUTED_TESTS_CONFIG = {} if dist.is_available(): DISTRIBUTED_TESTS_CONFIG["test"] = {"WORLD_SIZE": "1"} if not TEST_WITH_ROCM and dist.is_mpi_available(): DISTRIBUTED_TESTS_CONFIG["mpi"] = { "WORLD_SIZE": "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-mpi", } if dist.is_nccl_available(): DISTRIBUTED_TESTS_CONFIG["nccl"] = { "WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-nccl", } if dist.is_gloo_available(): DISTRIBUTED_TESTS_CONFIG["gloo"] = { "WORLD_SIZE": "2" if torch.cuda.device_count() == 2 else "3", "TEST_REPORT_SOURCE_OVERRIDE": "dist-gloo", } # https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python SIGNALS_TO_NAMES_DICT = { getattr(signal, n): n for n in dir(signal) if n.startswith("SIG") and "_" not in n } CPP_EXTENSIONS_ERROR = """ Ninja (https://ninja-build.org) is required for some of the C++ extensions tests, but it could not be found. Install ninja with `pip install ninja` or `conda install ninja`. Alternatively, disable said tests with `run_test.py --exclude test_cpp_extensions_aot_ninja test_cpp_extensions_jit`. """ PYTORCH_COLLECT_COVERAGE = bool(os.environ.get("PYTORCH_COLLECT_COVERAGE")) ENABLE_PR_HISTORY_REORDERING = bool( os.environ.get("ENABLE_PR_HISTORY_REORDERING", "0") == "1" ) JIT_EXECUTOR_TESTS = [ "test_jit_profiling", "test_jit_legacy", "test_jit_fuser_legacy", ] DISTRIBUTED_TESTS = [test for test in TESTS if test.startswith("distributed")] TESTS_REQUIRING_LAPACK = [ "distributions/test_constraints", "distributions/test_distributions", ] # Dictionary matching test modules (in TESTS) to lists of test cases (within that test_module) that would be run when # options.run_specified_test_cases is enabled. # For example: # { # "test_nn": ["test_doubletensor_avg_pool3d", "test_share_memory", "test_hook_requires_grad"], # ... # } # then for test_nn.py, we would ONLY run test_doubletensor_avg_pool3d, test_share_memory, and test_hook_requires_grad. SPECIFIED_TEST_CASES_DICT: Dict[str, List[str]] = {} # The file from which the SPECIFIED_TEST_CASES_DICT will be filled, a CSV of test cases that would be run when # options.run_specified_test_cases is enabled. SPECIFIED_TEST_CASES_FILE: str = ".pytorch_specified_test_cases.csv" def print_to_stderr(message): print(message, file=sys.stderr) def get_test_case_args(test_module, using_pytest) -> List[str]: args = [] # if test_module not specified or specified with '__all__' then run all tests if ( test_module not in SPECIFIED_TEST_CASES_DICT or "__all__" in SPECIFIED_TEST_CASES_DICT[test_module] ): return args if using_pytest: args.append("-k") args.append(" or ".join(SPECIFIED_TEST_CASES_DICT[test_module])) else: for test in SPECIFIED_TEST_CASES_DICT[test_module]: args.append("-k") args.append(test) return args def get_executable_command(options, allow_pytest, disable_coverage=False): if options.coverage and not disable_coverage: executable = ["coverage", "run", "--parallel-mode", "--source=torch"] else: executable = [sys.executable] if options.pytest: if allow_pytest: executable += ["-m", "pytest"] else: print_to_stderr( "Pytest cannot be used for this test. Falling back to unittest." ) return executable def run_test( test_module, test_directory, options, launcher_cmd=None, extra_unittest_args=None ): unittest_args = options.additional_unittest_args.copy() if options.verbose: unittest_args.append(f'-{"v"*options.verbose}') # in case of pytest if test_module in RUN_PARALLEL_BLOCKLIST: unittest_args = [ arg for arg in unittest_args if not arg.startswith("--run-parallel") ] if extra_unittest_args: assert isinstance(extra_unittest_args, list) unittest_args.extend(extra_unittest_args) # If using pytest, replace -f with equivalent -x if options.pytest: unittest_args = [arg if arg != "-f" else "-x" for arg in unittest_args] elif IS_IN_CI: # use the downloaded test cases configuration, not supported in pytest unittest_args.extend(["--import-slow-tests", "--import-disabled-tests"]) # Multiprocessing related tests cannot run with coverage. # Tracking issue: https://github.com/pytorch/pytorch/issues/50661 disable_coverage = ( sys.platform == "win32" and test_module in WINDOWS_COVERAGE_BLOCKLIST ) # Extra arguments are not supported with pytest executable = get_executable_command( options, allow_pytest=not extra_unittest_args, disable_coverage=disable_coverage ) # TODO: move this logic into common_utils.py instead of passing in "-k" individually # The following logic for running specified tests will only run for non-distributed tests, as those are dispatched # to test_distributed and not run_test (this function) if options.run_specified_test_cases: unittest_args.extend(get_test_case_args(test_module, "pytest" in executable)) # Can't call `python -m unittest test_*` here because it doesn't run code # in `if __name__ == '__main__': `. So call `python test_*.py` instead. argv = [test_module + ".py"] + unittest_args command = (launcher_cmd or []) + executable + argv print_to_stderr("Executing {} ... [{}]".format(command, datetime.now())) return shell(command, test_directory) def test_cuda_primary_ctx(test_module, test_directory, options): return run_test( test_module, test_directory, options, extra_unittest_args=["--subprocess"] ) run_test_with_subprocess = functools.partial(run_test, extra_unittest_args=["--subprocess"]) def get_run_test_with_subprocess_fn(): return lambda test_module, test_directory, options: run_test_with_subprocess(test_module, test_directory, options) def _test_cpp_extensions_aot(test_directory, options, use_ninja): if use_ninja: try: cpp_extension.verify_ninja_availability() except RuntimeError: print(CPP_EXTENSIONS_ERROR) return 1 # Wipe the build folder, if it exists already cpp_extensions_test_dir = os.path.join(test_directory, "cpp_extensions") cpp_extensions_test_build_dir = os.path.join(cpp_extensions_test_dir, "build") if os.path.exists(cpp_extensions_test_build_dir): shutil.rmtree(cpp_extensions_test_build_dir) # Build the test cpp extensions modules shell_env = os.environ.copy() shell_env["USE_NINJA"] = str(1 if use_ninja else 0) cmd = [sys.executable, "setup.py", "install", "--root", "./install"] return_code = shell(cmd, cwd=cpp_extensions_test_dir, env=shell_env) if return_code != 0: return return_code if sys.platform != "win32": return_code = shell( cmd, cwd=os.path.join(cpp_extensions_test_dir, "no_python_abi_suffix_test"), env=shell_env, ) if return_code != 0: return return_code # "install" the test modules and run tests python_path = os.environ.get("PYTHONPATH", "") from shutil import copyfile test_module = "test_cpp_extensions_aot" + ("_ninja" if use_ninja else "_no_ninja") copyfile( test_directory + "/test_cpp_extensions_aot.py", test_directory + "/" + test_module + ".py", ) try: cpp_extensions = os.path.join(test_directory, "cpp_extensions") install_directory = "" # install directory is the one that is named site-packages for root, directories, _ in os.walk(os.path.join(cpp_extensions, "install")): for directory in directories: if "-packages" in directory: install_directory = os.path.join(root, directory) assert install_directory, "install_directory must not be empty" os.environ["PYTHONPATH"] = os.pathsep.join([install_directory, python_path]) return run_test(test_module, test_directory, options) finally: os.environ["PYTHONPATH"] = python_path if os.path.exists(test_directory + "/" + test_module + ".py"): os.remove(test_directory + "/" + test_module + ".py") def test_cpp_extensions_aot_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot(test_directory, options, use_ninja=True) def test_cpp_extensions_aot_no_ninja(test_module, test_directory, options): return _test_cpp_extensions_aot(test_directory, options, use_ninja=False) def test_distributed(test_module, test_directory, options): # MPI tests are broken with Python-3.9 mpi_available = subprocess.call( "command -v mpiexec", shell=True ) == 0 and sys.version_info < (3, 9) if options.verbose and not mpi_available: print_to_stderr("MPI not available -- MPI backend tests will be skipped") config = DISTRIBUTED_TESTS_CONFIG for backend, env_vars in config.items(): if sys.platform == "win32" and backend != "gloo": continue if backend == "mpi" and not mpi_available: continue for with_init_file in {True, False}: if sys.platform == "win32" and not with_init_file: continue tmp_dir = tempfile.mkdtemp() if options.verbose: init_str = "with {} init_method" with_init = init_str.format("file" if with_init_file else "env") print_to_stderr( "Running distributed tests for the {} backend {}".format( backend, with_init ) ) old_environ = dict(os.environ) os.environ["TEMP_DIR"] = tmp_dir os.environ["BACKEND"] = backend os.environ["INIT_METHOD"] = "env://" os.environ.update(env_vars) if with_init_file: if test_module == "test_distributed_spawn": init_method = f"{FILE_SCHEMA}{tmp_dir}/" else: init_method = f"{FILE_SCHEMA}{tmp_dir}/shared_init_file" os.environ["INIT_METHOD"] = init_method try: os.mkdir(os.path.join(tmp_dir, "barrier")) os.mkdir(os.path.join(tmp_dir, "test_dir")) if backend == "mpi": # test mpiexec for --noprefix option with open(os.devnull, "w") as devnull: allowrunasroot_opt = ( "--allow-run-as-root" if subprocess.call( 'mpiexec --allow-run-as-root -n 1 bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT, ) == 0 else "" ) noprefix_opt = ( "--noprefix" if subprocess.call( f'mpiexec {allowrunasroot_opt} -n 1 --noprefix bash -c ""', shell=True, stdout=devnull, stderr=subprocess.STDOUT, ) == 0 else "" ) mpiexec = ["mpiexec", "-n", "3", noprefix_opt, allowrunasroot_opt] return_code = run_test( test_module, test_directory, options, launcher_cmd=mpiexec ) else: return_code = run_test(test_module, test_directory, options, extra_unittest_args=["--subprocess"]) if return_code != 0: return return_code finally: shutil.rmtree(tmp_dir) os.environ.clear() os.environ.update(old_environ) return 0 CUSTOM_HANDLERS = { "test_cuda_primary_ctx": test_cuda_primary_ctx, "test_cpp_extensions_aot_no_ninja": test_cpp_extensions_aot_no_ninja, "test_cpp_extensions_aot_ninja": test_cpp_extensions_aot_ninja, "distributed/test_distributed_spawn": test_distributed, "distributed/test_c10d_nccl": get_run_test_with_subprocess_fn(), "distributed/test_c10d_gloo": get_run_test_with_subprocess_fn(), "distributed/test_c10d_common": get_run_test_with_subprocess_fn(), "distributed/test_c10d_spawn_gloo": get_run_test_with_subprocess_fn(), "distributed/test_c10d_spawn_nccl": get_run_test_with_subprocess_fn(), "distributed/test_store": get_run_test_with_subprocess_fn(), "distributed/test_pg_wrapper": get_run_test_with_subprocess_fn(), "distributed/rpc/test_faulty_agent": get_run_test_with_subprocess_fn(), "distributed/rpc/test_tensorpipe_agent": get_run_test_with_subprocess_fn(), "distributed/rpc/test_share_memory": get_run_test_with_subprocess_fn(), "distributed/rpc/cuda/test_tensorpipe_agent": get_run_test_with_subprocess_fn(), } def parse_test_module(test): return test.split(".")[0] class TestChoices(list): def __init__(self, *args, **kwargs): super(TestChoices, self).__init__(args[0]) def __contains__(self, item): return list.__contains__(self, parse_test_module(item)) def parse_args(): parser = argparse.ArgumentParser( description="Run the PyTorch unit test suite", epilog="where TESTS is any of: {}".format(", ".join(TESTS)), formatter_class=argparse.RawTextHelpFormatter, parents=[common_parser] ) parser.add_argument( "-v", "--verbose", action="count", default=0, help="print verbose information and test-by-test results", ) parser.add_argument("--jit", "--jit", action="store_true", help="run all jit tests") parser.add_argument( "--distributed-tests", "--distributed-tests", action="store_true", help="run all distributed tests", ) parser.add_argument( "-core", "--core", action="store_true", help="Only run core tests, or tests that validate PyTorch's ops, modules," "and autograd. They are defined by CORE_TEST_LIST." ) parser.add_argument( "-pt", "--pytest", action="store_true", help="If true, use `pytest` to execute the tests. E.g., this runs " "TestTorch with pytest in verbose and coverage mode: " "python run_test.py -vci torch -pt", ) parser.add_argument( "-c", "--coverage", action="store_true", help="enable coverage", default=PYTORCH_COLLECT_COVERAGE, ) parser.add_argument( "-i", "--include", nargs="+", choices=TestChoices(TESTS), default=TESTS, metavar="TESTS", help="select a set of tests to include (defaults to ALL tests)." " tests must be a part of the TESTS list defined in run_test.py", ) parser.add_argument( "-x", "--exclude", nargs="+", choices=TESTS, metavar="TESTS", default=[], help="select a set of tests to exclude", ) parser.add_argument( "-f", "--first", choices=TESTS, metavar="TESTS", help="select the test to start from (excludes previous tests)", ) parser.add_argument( "-l", "--last", choices=TESTS, metavar="TESTS", help="select the last test to run (excludes following tests)", ) parser.add_argument( "--bring-to-front", nargs="+", choices=TestChoices(TESTS), default=[], metavar="TESTS", help="select a set of tests to run first. This can be used in situations" " where you want to run all tests, but care more about some set, " "e.g. after making a change to a specific component", ) parser.add_argument( "--ignore-win-blocklist", action="store_true", help="always run blocklisted windows tests", ) # NS: Disable target determination until it can be made more reliable # parser.add_argument( # "--determine-from", # help="File of affected source filenames to determine which tests to run.", # ) parser.add_argument( "--continue-through-error", action="store_true", help="Runs the full test suite despite one of the tests failing", default=strtobool(os.environ.get("CONTINUE_THROUGH_ERROR", "False")), ) parser.add_argument( "additional_unittest_args", nargs="*", help="additional arguments passed through to unittest, e.g., " "python run_test.py -i sparse -- TestSparse.test_factory_size_check", ) parser.add_argument( "--export-past-test-times", nargs="?", type=str, const=TEST_TIMES_FILE, help="dumps test times from previous S3 stats into a file, format JSON", ) parser.add_argument( "--shard", nargs=2, type=int, help="runs a shard of the tests (taking into account other selections), e.g., " "--shard 2 3 will break up the selected tests into 3 shards and run the tests " "in the 2nd shard (the first number should not exceed the second)", ) parser.add_argument( "--exclude-jit-executor", action="store_true", help="exclude tests that are run for a specific jit config", ) parser.add_argument( "--exclude-distributed-tests", action="store_true", help="exclude distributed tests", ) parser.add_argument( "--run-specified-test-cases", nargs="?", type=str, const=SPECIFIED_TEST_CASES_FILE, help="load specified test cases file dumped from previous OSS CI stats, format CSV. " " If all test cases should run for a <test_module> please add a single row: \n" " test_filename,test_case_name\n" " ...\n" " <test_module>,__all__\n" " ...\n" 'how we use the stats will be based on option "--use-specified-test-cases-by".', ) parser.add_argument( "--use-specified-test-cases-by", type=str, choices=["include", "bring-to-front"], default="include", help='used together with option "--run-specified-test-cases". When specified test case ' "file is set, this option allows the user to control whether to only run the specified test " "modules or to simply bring the specified modules to front and also run the remaining " "modules. Note: regardless of this option, we will only run the specified test cases " " within a specified test module. For unspecified test modules with the bring-to-front " "option, all test cases will be run, as one may expect.", ) parser.add_argument( "--dry-run", action="store_true", help="Only list the test that will run.", ) return parser.parse_args() def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index`=False) and/or ``options.last``(:attr:`find_last_index`=True) are used. :attr:`selected_tests` can be a list that contains multiple consequent occurrences of tests as part of the same test module, e.g.: ``` selected_tests = ['autograd', 'cuda', **'torch.TestTorch.test_acos', 'torch.TestTorch.test_tan', 'torch.TestTorch.test_add'**, 'utils'] ``` If :attr:`test`='torch' and :attr:`find_last_index`=False, result should be **2**. If :attr:`test`='torch' and :attr:`find_last_index`=True, result should be **4**. Args: test (str): Name of test to lookup selected_tests (list): List of tests find_last_index (bool, optional): should we lookup the index of first or last occurrence (first is default) Returns: index of the first or last occurrence of the given test """ idx = 0 found_idx = -1 for t in selected_tests: if t.startswith(test): found_idx = idx if not find_last_index: break idx += 1 return found_idx def exclude_tests(exclude_list, selected_tests, exclude_message=None): for exclude_test in exclude_list: tests_copy = selected_tests[:] for test in tests_copy: if test.startswith(exclude_test): if exclude_message is not None: print_to_stderr("Excluding {} {}".format(test, exclude_message)) selected_tests.remove(test) return selected_tests def get_selected_tests(options): # First make sure run specific test cases options are processed. if options.run_specified_test_cases: if options.use_specified_test_cases_by == "include": options.include = list(SPECIFIED_TEST_CASES_DICT.keys()) elif options.use_specified_test_cases_by == "bring-to-front": options.bring_to_front = list(SPECIFIED_TEST_CASES_DICT.keys()) selected_tests = options.include # filter if there's JIT only and distributed only test options if options.jit: selected_tests = list( filter(lambda test_name: "jit" in test_name, selected_tests) ) if options.distributed_tests: selected_tests = list( filter(lambda test_name: test_name in DISTRIBUTED_TESTS, selected_tests) ) # Filter to only run core tests when --core option is specified if options.core: selected_tests = list( filter(lambda test_name: test_name in CORE_TEST_LIST, selected_tests) ) # process reordering if options.bring_to_front: to_front = set(options.bring_to_front) selected_tests = options.bring_to_front + list( filter(lambda name: name not in to_front, selected_tests) ) if options.first: first_index = find_test_index(options.first, selected_tests) selected_tests = selected_tests[first_index:] if options.last: last_index = find_test_index(options.last, selected_tests, find_last_index=True) selected_tests = selected_tests[: last_index + 1] # process exclusion if options.exclude_jit_executor: options.exclude.extend(JIT_EXECUTOR_TESTS) if options.exclude_distributed_tests: options.exclude.extend(DISTRIBUTED_TESTS) # these tests failing in CUDA 11.6 temporary disabling. issue https://github.com/pytorch/pytorch/issues/75375 if torch.version.cuda is not None and LooseVersion(torch.version.cuda) == "11.6": options.exclude.extend(["distributions/test_constraints"]) selected_tests = exclude_tests(options.exclude, selected_tests) if sys.platform == "win32" and not options.ignore_win_blocklist: target_arch = os.environ.get("VSCMD_ARG_TGT_ARCH") if target_arch != "x64": WINDOWS_BLOCKLIST.append("cpp_extensions_aot_no_ninja") WINDOWS_BLOCKLIST.append("cpp_extensions_aot_ninja") WINDOWS_BLOCKLIST.append("cpp_extensions_jit") WINDOWS_BLOCKLIST.append("jit") WINDOWS_BLOCKLIST.append("jit_fuser") # This is exception that's caused by this issue https://github.com/pytorch/pytorch/issues/69460 # This below code should be removed once this issue is solved if torch.version.cuda is not None and LooseVersion(torch.version.cuda) >= "11.5": WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot") WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot_ninja") WINDOWS_BLOCKLIST.append("test_cpp_extensions_aot_no_ninja") selected_tests = exclude_tests(WINDOWS_BLOCKLIST, selected_tests, "on Windows") elif TEST_WITH_ROCM: selected_tests = exclude_tests(ROCM_BLOCKLIST, selected_tests, "on ROCm") # sharding if options.shard: assert len(options.shard) == 2, "Unexpected shard format" assert min(options.shard) > 0, "Shards must be positive numbers" which_shard, num_shards = options.shard assert ( which_shard <= num_shards ), "Selected shard must be less than or equal to total number of shards" assert num_shards <= len( selected_tests ), f"Number of shards must be less than {len(selected_tests)}" # TODO: fix this to use test_times_filename, but currently this is not working # because setting the export arg immeidately halts the test execution. selected_tests = get_shard_based_on_S3( which_shard, num_shards, selected_tests, TEST_TIMES_FILE ) # skip all distributed tests if distributed package is not available. if not dist.is_available(): selected_tests = exclude_tests(DISTRIBUTED_TESTS, selected_tests, "PyTorch is built without distributed support.") # skip tests that require LAPACK when it's not available if not torch._C.has_lapack: selected_tests = exclude_tests(TESTS_REQUIRING_LAPACK, selected_tests, "PyTorch is built without LAPACK support.") return selected_tests def run_test_module(test: str, test_directory: str, options) -> Optional[str]: test_module = parse_test_module(test) # Printing the date here can help diagnose which tests are slow print_to_stderr("Running {} ... [{}]".format(test, datetime.now())) handler = CUSTOM_HANDLERS.get(test_module, run_test) return_code = handler(test_module, test_directory, options) assert isinstance(return_code, int) and not isinstance( return_code, bool ), "Return code should be an integer" if return_code == 0: return None message = f"{test} failed!" if return_code < 0: # subprocess.Popen returns the child process' exit signal as # return code -N, where N is the signal number. signal_name = SIGNALS_TO_NAMES_DICT[-return_code] message += f" Received signal: {signal_name}" return message def main(): options = parse_args() # TODO: move this export & download function in tools/ folder test_times_filename = options.export_past_test_times if test_times_filename: print( f"Exporting past test times from S3 to {test_times_filename}, no tests will be run." ) export_S3_test_times(test_times_filename) return specified_test_cases_filename = options.run_specified_test_cases if specified_test_cases_filename: print( f"Loading specified test cases to run from {specified_test_cases_filename}." ) global SPECIFIED_TEST_CASES_DICT SPECIFIED_TEST_CASES_DICT = get_specified_test_cases( specified_test_cases_filename, TESTS ) test_directory = str(REPO_ROOT / "test") selected_tests = get_selected_tests(options) if options.verbose: print_to_stderr("Selected tests:\n {}".format("\n ".join(selected_tests))) if options.dry_run: return if options.coverage and not PYTORCH_COLLECT_COVERAGE: shell(["coverage", "erase"]) # NS: Disable target determination until it can be made more reliable # if options.determine_from is not None and os.path.exists(options.determine_from): # slow_tests = get_slow_tests_based_on_S3( # TESTS, TARGET_DET_LIST, SLOW_TEST_THRESHOLD # ) # print_to_stderr( # "Added the following tests to target_det tests as calculated based on S3:" # ) # print_to_stderr(slow_tests) # with open(options.determine_from, "r") as fh: # touched_files = [ # os.path.normpath(name.strip()) # for name in fh.read().split("\n") # if len(name.strip()) > 0 # ] # # HACK: Ensure the 'test' paths can be traversed by Modulefinder # sys.path.append(test_directory) # selected_tests = [ # test # for test in selected_tests # if should_run_test( # TARGET_DET_LIST + slow_tests, test, touched_files, options # ) # ] # sys.path.remove(test_directory) if IS_IN_CI: selected_tests = get_reordered_tests( selected_tests, ENABLE_PR_HISTORY_REORDERING ) # downloading test cases configuration to local environment get_test_case_configs(dirpath=test_directory) has_failed = False failure_messages = [] try: for test in selected_tests: options_clone = copy.deepcopy(options) if test in USE_PYTEST_LIST: options_clone.pytest = True err_message = run_test_module(test, test_directory, options_clone) if err_message is None: continue has_failed = True failure_messages.append(err_message) if not options_clone.continue_through_error: raise RuntimeError(err_message) print_to_stderr(err_message) finally: if options.coverage: from coverage import Coverage with set_cwd(test_directory): cov = Coverage() if PYTORCH_COLLECT_COVERAGE: cov.load() cov.combine(strict=False) cov.save() if not PYTORCH_COLLECT_COVERAGE: cov.html_report() if options.continue_through_error and has_failed: for err in failure_messages: print_to_stderr(err) sys.exit(1) if __name__ == "__main__": main()
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Foundation in version 3 of the License. # # ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are # applicable granting you additional permissions and placing additional restrictions on your usage of this software. # Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive # this file, see <https://pretix.eu/about/en/license>. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along with this program. If not, see # <https://www.gnu.org/licenses/>. # # This file is based on an earlier version of pretix which was released under the Apache License 2.0. The full text of # the Apache License 2.0 can be obtained at <http://www.apache.org/licenses/LICENSE-2.0>. # # This file may have since been changed and any changes are released under the terms of AGPLv3 as described above. A # full history of changes and contributors is available at <https://github.com/pretix/pretix>. # # This file contains Apache-licensed contributions copyrighted by: Jakob Schnell, Tobias Kunze # # Unless required by applicable law or agreed to in writing, software distributed under the Apache License 2.0 is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under the License. from datetime import datetime, time, timedelta from decimal import Decimal from urllib.parse import urlencode from django import forms from django.apps import apps from django.conf import settings from django.db.models import ( Count, Exists, F, Max, Model, OrderBy, OuterRef, Q, QuerySet, ) from django.db.models.functions import Coalesce, ExtractWeekDay, Upper from django.urls import reverse, reverse_lazy from django.utils.formats import date_format, localize from django.utils.functional import cached_property from django.utils.timezone import get_current_timezone, make_aware, now from django.utils.translation import gettext, gettext_lazy as _, pgettext_lazy from django_scopes.forms import SafeModelChoiceField from pretix.base.channels import get_all_sales_channels from pretix.base.forms.widgets import ( DatePickerWidget, SplitDateTimePickerWidget, TimePickerWidget, ) from pretix.base.models import ( Checkin, CheckinList, Device, Event, EventMetaProperty, EventMetaValue, Gate, Invoice, InvoiceAddress, Item, Order, OrderPayment, OrderPosition, OrderRefund, Organizer, Question, QuestionAnswer, SubEvent, Team, TeamAPIToken, TeamInvite, ) from pretix.base.signals import register_payment_providers from pretix.control.forms.widgets import Select2 from pretix.control.signals import order_search_filter_q from pretix.helpers.countries import CachedCountries from pretix.helpers.database import rolledback_transaction from pretix.helpers.dicts import move_to_end from pretix.helpers.i18n import i18ncomp PAYMENT_PROVIDERS = [] def get_all_payment_providers(): global PAYMENT_PROVIDERS if PAYMENT_PROVIDERS: return PAYMENT_PROVIDERS with rolledback_transaction(): event = Event.objects.create( plugins=",".join([app.name for app in apps.get_app_configs()]), name="INTERNAL", date_from=now(), organizer=Organizer.objects.create(name="INTERNAL") ) provs = register_payment_providers.send( sender=event ) choices = [] for recv, prov in provs: if isinstance(prov, list): for p in prov: p = p(event) if not p.is_meta: choices.append((p.identifier, p.verbose_name)) else: prov = prov(event) if not prov.is_meta: choices.append((prov.identifier, prov.verbose_name)) PAYMENT_PROVIDERS = choices return choices class FilterForm(forms.Form): orders = {} def filter_qs(self, qs): return qs @property def filtered(self): return self.is_valid() and any(self.cleaned_data.values()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ordering'] = forms.ChoiceField( choices=sum([ [(a, a), ('-' + a, '-' + a)] for a in self.orders.keys() ], []), required=False ) def get_order_by(self): o = self.cleaned_data.get('ordering') if o.startswith('-') and o not in self.orders: return '-' + self.orders[o[1:]] else: return self.orders[o] def filter_to_strings(self): string = [] for k, f in self.fields.items(): v = self.cleaned_data.get(k) if v is None or (isinstance(v, (list, str, QuerySet)) and len(v) == 0): continue if k == "saveas": continue if isinstance(v, bool): val = _('Yes') if v else _('No') elif isinstance(v, QuerySet): q = ['"' + str(m) + '"' for m in v] if not q: continue val = ' or '.join(q) elif isinstance(v, Model): val = '"' + str(v) + '"' elif isinstance(f, forms.MultipleChoiceField): valdict = dict(f.choices) val = ' or '.join([str(valdict.get(m)) for m in v]) elif isinstance(f, forms.ChoiceField): val = str(dict(f.choices).get(v)) elif isinstance(v, datetime): val = date_format(v, 'SHORT_DATETIME_FORMAT') elif isinstance(v, Decimal): val = localize(v) else: val = v string.append('{}: {}'.format(f.label, val)) return string class OrderFilterForm(FilterForm): query = forms.CharField( label=_('Search for…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search for…'), 'autofocus': 'autofocus' }), required=False ) provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) status = forms.ChoiceField( label=_('Order status'), choices=( ('', _('All orders')), (_('Valid orders'), ( (Order.STATUS_PAID, _('Paid (or canceled with paid fee)')), (Order.STATUS_PENDING, _('Pending')), (Order.STATUS_PENDING + Order.STATUS_PAID, _('Pending or paid')), )), (_('Cancellations'), ( (Order.STATUS_CANCELED, _('Canceled (fully)')), ('cp', _('Canceled (fully or with paid fee)')), ('rc', _('Cancellation requested')), ('cni', _('Fully canceled but invoice not canceled')), )), (_('Payment process'), ( (Order.STATUS_EXPIRED, _('Expired')), (Order.STATUS_PENDING + Order.STATUS_EXPIRED, _('Pending or expired')), ('o', _('Pending (overdue)')), ('overpaid', _('Overpaid')), ('partially_paid', _('Partially paid')), ('underpaid', _('Underpaid (but confirmed)')), ('pendingpaid', _('Pending (but fully paid)')), )), (_('Approval process'), ( ('na', _('Approved, payment pending')), ('pa', _('Approval pending')), )), (_('Follow-up date'), ( ('custom_followup_at', _('Follow-up configured')), ('custom_followup_due', _('Follow-up due')), )), ('testmode', _('Test mode')), ), required=False, ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): u = fdata.get('query') if "-" in u: code = (Q(event__slug__icontains=u.rsplit("-", 1)[0]) & Q(code__icontains=Order.normalize_code(u.rsplit("-", 1)[1]))) else: code = Q(code__icontains=Order.normalize_code(u)) matching_invoices = Invoice.objects.filter( Q(invoice_no__iexact=u) | Q(invoice_no__iexact=u.zfill(5)) | Q(full_invoice_no__iexact=u) ).values_list('order_id', flat=True) matching_positions = OrderPosition.objects.filter( Q( Q(attendee_name_cached__icontains=u) | Q(attendee_email__icontains=u) | Q(secret__istartswith=u) | Q(pseudonymization_id__istartswith=u) ) ).values_list('order_id', flat=True) matching_invoice_addresses = InvoiceAddress.objects.filter( Q( Q(name_cached__icontains=u) | Q(company__icontains=u) ) ).values_list('order_id', flat=True) matching_orders = Order.objects.filter( code | Q(email__icontains=u) | Q(comment__icontains=u) ).values_list('id', flat=True) mainq = ( Q(pk__in=matching_orders) | Q(pk__in=matching_invoices) | Q(pk__in=matching_positions) | Q(pk__in=matching_invoice_addresses) | Q(pk__in=matching_invoices) ) for recv, q in order_search_filter_q.send(sender=getattr(self, 'event', None), query=u): mainq = mainq | q qs = qs.filter( mainq ) if fdata.get('status'): s = fdata.get('status') if s == 'o': qs = qs.filter(status=Order.STATUS_PENDING, expires__lt=now().replace(hour=0, minute=0, second=0)) elif s == 'np': qs = qs.filter(status__in=[Order.STATUS_PENDING, Order.STATUS_PAID]) elif s == 'ne': qs = qs.filter(status__in=[Order.STATUS_PENDING, Order.STATUS_EXPIRED]) elif s in ('p', 'n', 'e', 'c', 'r'): qs = qs.filter(status=s) elif s == 'overpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(~Q(status=Order.STATUS_CANCELED) & Q(pending_sum_t__lt=0)) | Q(Q(status=Order.STATUS_CANCELED) & Q(pending_sum_rc__lt=0)) ) elif s == 'rc': qs = qs.filter( cancellation_requests__isnull=False ).annotate( cancellation_request_time=Max('cancellation_requests__created') ).order_by( '-cancellation_request_time' ) elif s == 'pendingpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(status__in=(Order.STATUS_EXPIRED, Order.STATUS_PENDING)) & Q(pending_sum_t__lte=0) & Q(require_approval=False) ) elif s == 'partially_paid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__lt=F('total'), computed_payment_refund_sum__gt=Decimal('0.00') ).exclude( status=Order.STATUS_CANCELED ) elif s == 'underpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(status=Order.STATUS_PAID, pending_sum_t__gt=0) | Q(status=Order.STATUS_CANCELED, pending_sum_rc__gt=0) ) elif s == 'cni': i = Invoice.objects.filter( order=OuterRef('pk'), is_cancellation=False, refered__isnull=True, ).order_by().values('order').annotate(k=Count('id')).values('k') qs = qs.annotate( icnt=i ).filter( icnt__gt=0, status=Order.STATUS_CANCELED, ) elif s == 'pa': qs = qs.filter( status=Order.STATUS_PENDING, require_approval=True ) elif s == 'na': qs = qs.filter( status=Order.STATUS_PENDING, require_approval=False ) elif s == 'custom_followup_at': qs = qs.filter( custom_followup_at__isnull=False ) elif s == 'custom_followup_due': qs = qs.filter( custom_followup_at__lte=now().astimezone(get_current_timezone()).date() ) elif s == 'testmode': qs = qs.filter( testmode=True ) elif s == 'cp': s = OrderPosition.objects.filter( order=OuterRef('pk') ) qs = qs.annotate( has_pc=Exists(s) ).filter( Q(status=Order.STATUS_PAID, has_pc=False) | Q(status=Order.STATUS_CANCELED) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) if fdata.get('provider'): qs = qs.annotate( has_payment_with_provider=Exists( OrderPayment.objects.filter( Q(order=OuterRef('pk')) & Q(provider=fdata.get('provider')) ) ) ) qs = qs.filter(has_payment_with_provider=1) return qs class EventOrderFilterForm(OrderFilterForm): orders = {'code': 'code', 'email': 'email', 'total': 'total', 'datetime': 'datetime', 'status': 'status'} item = forms.ChoiceField( label=_('Products'), required=False, ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) question = forms.ModelChoiceField( queryset=Question.objects.none(), required=False, ) answer = forms.CharField( required=False ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['item'].queryset = self.event.items.all() self.fields['question'].queryset = self.event.questions.all() self.fields['provider'].choices += [(k, v.verbose_name) for k, v in self.event.get_payment_providers().items()] if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=str(i)))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (str(i), v.value))) else: choices.append((str(i.pk), str(i))) self.fields['item'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) item = fdata.get('item') if item: if '-' in item: var = item.split('-')[1] qs = qs.filter(all_positions__variation_id=var, all_positions__canceled=False).distinct() else: qs = qs.filter(all_positions__item_id=fdata.get('item'), all_positions__canceled=False).distinct() if fdata.get('subevent'): qs = qs.filter(all_positions__subevent=fdata.get('subevent'), all_positions__canceled=False).distinct() if fdata.get('question') and fdata.get('answer') is not None: q = fdata.get('question') if q.type == Question.TYPE_FILE: answers = QuestionAnswer.objects.filter( orderposition__order_id=OuterRef('pk'), question_id=q.pk, file__isnull=False ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) elif q.type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE): answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), options__pk=fdata.get('answer') ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) else: answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), answer__exact=fdata.get('answer') ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) return qs class FilterNullBooleanSelect(forms.NullBooleanSelect): def __init__(self, attrs=None): choices = ( ('unknown', _('All')), ('true', _('Yes')), ('false', _('No')), ) super(forms.NullBooleanSelect, self).__init__(attrs, choices) class EventOrderExpertFilterForm(EventOrderFilterForm): subevents_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'All dates starting at or after'), required=False, ) subevents_to = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'All dates starting before'), required=False, ) created_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=_('Order placed at or after'), required=False, ) created_to = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=_('Order placed before'), required=False, ) email = forms.CharField( required=False, label=_('E-mail address') ) comment = forms.CharField( required=False, label=_('Comment') ) locale = forms.ChoiceField( required=False, label=_('Locale'), choices=settings.LANGUAGES ) email_known_to_work = forms.NullBooleanField( required=False, widget=FilterNullBooleanSelect, label=_('E-mail address verified'), ) total = forms.DecimalField( localize=True, required=False, label=_('Total amount'), ) payment_sum_min = forms.DecimalField( localize=True, required=False, label=_('Minimal sum of payments and refunds'), ) payment_sum_max = forms.DecimalField( localize=True, required=False, label=_('Maximal sum of payments and refunds'), ) sales_channel = forms.ChoiceField( label=_('Sales channel'), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['query'] del self.fields['question'] del self.fields['answer'] del self.fields['ordering'] if not self.event.has_subevents: del self.fields['subevents_from'] del self.fields['subevents_to'] self.fields['sales_channel'].choices = [('', '')] + [ (k, v.verbose_name) for k, v in get_all_sales_channels().items() ] locale_names = dict(settings.LANGUAGES) self.fields['locale'].choices = [('', '')] + [(a, locale_names[a]) for a in self.event.settings.locales] move_to_end(self.fields, 'item') move_to_end(self.fields, 'provider') self.fields['invoice_address_company'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Company') ) self.fields['invoice_address_name'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Name') ) self.fields['invoice_address_street'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Address') ) self.fields['invoice_address_zipcode'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('ZIP code'), help_text=_('Exact matches only') ) self.fields['invoice_address_city'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('City'), help_text=_('Exact matches only') ) self.fields['invoice_address_country'] = forms.ChoiceField( required=False, label=gettext('Invoice address') + ': ' + gettext('Country'), choices=[('', '')] + list(CachedCountries()) ) self.fields['attendee_name'] = forms.CharField( required=False, label=_('Attendee name') ) self.fields['attendee_email'] = forms.CharField( required=False, label=_('Attendee e-mail address') ) self.fields['attendee_address_company'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('Company') ) self.fields['attendee_address_street'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('Address') ) self.fields['attendee_address_zipcode'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('ZIP code'), help_text=_('Exact matches only') ) self.fields['attendee_address_city'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('City'), help_text=_('Exact matches only') ) self.fields['attendee_address_country'] = forms.ChoiceField( required=False, label=gettext('Attendee address') + ': ' + gettext('Country'), choices=[('', '')] + list(CachedCountries()) ) self.fields['ticket_secret'] = forms.CharField( label=_('Ticket secret'), required=False ) for q in self.event.questions.all(): self.fields['question_{}'.format(q.pk)] = forms.CharField( label=q.question, required=False, help_text=_('Exact matches only') ) def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('subevents_from'): qs = qs.filter( all_positions__subevent__date_from__gte=fdata.get('subevents_from'), all_positions__canceled=False ).distinct() if fdata.get('subevents_to'): qs = qs.filter( all_positions__subevent__date_from__lt=fdata.get('subevents_to'), all_positions__canceled=False ).distinct() if fdata.get('email'): qs = qs.filter( email__icontains=fdata.get('email') ) if fdata.get('created_from'): qs = qs.filter(datetime__gte=fdata.get('created_from')) if fdata.get('created_to'): qs = qs.filter(datetime__lte=fdata.get('created_to')) if fdata.get('comment'): qs = qs.filter(comment__icontains=fdata.get('comment')) if fdata.get('sales_channel'): qs = qs.filter(sales_channel=fdata.get('sales_channel')) if fdata.get('total'): qs = qs.filter(total=fdata.get('total')) if fdata.get('email_known_to_work') is not None: qs = qs.filter(email_known_to_work=fdata.get('email_known_to_work')) if fdata.get('locale'): qs = qs.filter(locale=fdata.get('locale')) if fdata.get('payment_sum_min') is not None: qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__gte=fdata['payment_sum_min'], ) if fdata.get('payment_sum_max') is not None: qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__lte=fdata['payment_sum_max'], ) if fdata.get('invoice_address_company'): qs = qs.filter(invoice_address__company__icontains=fdata.get('invoice_address_company')) if fdata.get('invoice_address_name'): qs = qs.filter(invoice_address__name_cached__icontains=fdata.get('invoice_address_name')) if fdata.get('invoice_address_street'): qs = qs.filter(invoice_address__street__icontains=fdata.get('invoice_address_street')) if fdata.get('invoice_address_zipcode'): qs = qs.filter(invoice_address__zipcode__iexact=fdata.get('invoice_address_zipcode')) if fdata.get('invoice_address_city'): qs = qs.filter(invoice_address__city__iexact=fdata.get('invoice_address_city')) if fdata.get('invoice_address_country'): qs = qs.filter(invoice_address__country=fdata.get('invoice_address_country')) if fdata.get('attendee_name'): qs = qs.filter( all_positions__attendee_name_cached__icontains=fdata.get('attendee_name') ) if fdata.get('attendee_address_company'): qs = qs.filter( all_positions__company__icontains=fdata.get('attendee_address_company') ).distinct() if fdata.get('attendee_address_street'): qs = qs.filter( all_positions__street__icontains=fdata.get('attendee_address_street') ).distinct() if fdata.get('attendee_address_city'): qs = qs.filter( all_positions__city__iexact=fdata.get('attendee_address_city') ).distinct() if fdata.get('attendee_address_country'): qs = qs.filter( all_positions__country=fdata.get('attendee_address_country') ).distinct() if fdata.get('ticket_secret'): qs = qs.filter( all_positions__secret__icontains=fdata.get('ticket_secret') ).distinct() for q in self.event.questions.all(): if fdata.get(f'question_{q.pk}'): answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), answer__iexact=fdata.get(f'question_{q.pk}') ) qs = qs.annotate(**{f'q_{q.pk}': Exists(answers)}).filter(**{f'q_{q.pk}': True}) return qs class OrderSearchFilterForm(OrderFilterForm): orders = {'code': 'code', 'email': 'email', 'total': 'total', 'datetime': 'datetime', 'status': 'status', 'event': 'event'} organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ) ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) self.fields['provider'].choices += get_all_payment_providers() seen = set() for p in self.meta_properties.all(): if p.name in seen: continue seen.add(p.name) self.fields['meta_{}'.format(p.name)] = forms.CharField( label=p.name, required=False, widget=forms.TextInput( attrs={ 'data-typeahead-url': reverse('control:events.meta.typeahead') + '?' + urlencode({ 'property': p.name, 'organizer': '' }) } ) ) def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('organizer'): qs = qs.filter(event__organizer=fdata.get('organizer')) filters_by_property_name = {} for i, p in enumerate(self.meta_properties): d = fdata.get('meta_{}'.format(p.name)) if d: emv_with_value = EventMetaValue.objects.filter( event=OuterRef('event_id'), property__pk=p.pk, value=d ) emv_with_any_value = EventMetaValue.objects.filter( event=OuterRef('event_id'), property__pk=p.pk, ) qs = qs.annotate(**{'attr_{}'.format(i): Exists(emv_with_value)}) if p.name in filters_by_property_name: filters_by_property_name[p.name] |= Q(**{'attr_{}'.format(i): True}) else: filters_by_property_name[p.name] = Q(**{'attr_{}'.format(i): True}) if p.default == d: qs = qs.annotate(**{'attr_{}_any'.format(i): Exists(emv_with_any_value)}) filters_by_property_name[p.name] |= Q(**{ 'attr_{}_any'.format(i): False, 'event__organizer_id': p.organizer_id }) for f in filters_by_property_name.values(): qs = qs.filter(f) return qs @cached_property def meta_properties(self): # We ignore superuser permissions here. This is intentional – we do not want to show super # users a form with all meta properties ever assigned. return EventMetaProperty.objects.filter( organizer_id__in=self.request.user.teams.values_list('organizer', flat=True) ) class OrderPaymentSearchFilterForm(forms.Form): orders = {'id': 'id', 'local_id': 'local_id', 'state': 'state', 'amount': 'amount', 'order': 'order', 'created': 'created', 'payment_date': 'payment_date', 'provider': 'provider', 'info': 'info', 'fee': 'fee'} query = forms.CharField( label=_('Search for…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search for…'), 'autofocus': 'autofocus' }), required=False, ) event = forms.ModelChoiceField( label=_('Event'), queryset=Event.objects.none(), required=False, widget=Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse_lazy('control:events.typeahead'), 'data-placeholder': _('All events') } ) ) organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ), ) state = forms.ChoiceField( label=_('Status'), required=False, choices=[('', _('All payments'))] + list(OrderPayment.PAYMENT_STATES), ) provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) created_from = forms.DateField( label=_('Payment created from'), required=False, widget=DatePickerWidget, ) created_until = forms.DateField( label=_('Payment created until'), required=False, widget=DatePickerWidget, ) completed_from = forms.DateField( label=_('Paid from'), required=False, widget=DatePickerWidget, ) completed_until = forms.DateField( label=_('Paid until'), required=False, widget=DatePickerWidget, ) amount = forms.CharField( label=_('Amount'), required=False, widget=forms.NumberInput(attrs={ 'placeholder': _('Amount'), }), ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) self.fields['ordering'] = forms.ChoiceField( choices=sum([ [(a, a), ('-' + a, '-' + a)] for a in self.orders.keys() ], []), required=False ) if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() self.fields['event'].queryset = Event.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) self.fields['event'].queryset = self.request.user.get_events_with_permission('can_view_orders') self.fields['provider'].choices += get_all_payment_providers() def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('created_from'): date_start = make_aware(datetime.combine( fdata.get('created_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(created__gte=date_start) if fdata.get('created_until'): date_end = make_aware(datetime.combine( fdata.get('created_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(created__lt=date_end) if fdata.get('completed_from'): date_start = make_aware(datetime.combine( fdata.get('completed_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(payment_date__gte=date_start) if fdata.get('completed_until'): date_end = make_aware(datetime.combine( fdata.get('completed_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(payment_date__lt=date_end) if fdata.get('event'): qs = qs.filter(order__event=fdata.get('event')) if fdata.get('organizer'): qs = qs.filter(order__event__organizer=fdata.get('organizer')) if fdata.get('state'): qs = qs.filter(state=fdata.get('state')) if fdata.get('provider'): qs = qs.filter(provider=fdata.get('provider')) if fdata.get('query'): u = fdata.get('query') matching_invoices = Invoice.objects.filter( Q(invoice_no__iexact=u) | Q(invoice_no__iexact=u.zfill(5)) | Q(full_invoice_no__iexact=u) ).values_list('order_id', flat=True) matching_invoice_addresses = InvoiceAddress.objects.filter( Q( Q(name_cached__icontains=u) | Q(company__icontains=u) ) ).values_list('order_id', flat=True) if "-" in u: code = (Q(event__slug__icontains=u.rsplit("-", 1)[0]) & Q(code__icontains=Order.normalize_code(u.rsplit("-", 1)[1]))) else: code = Q(code__icontains=Order.normalize_code(u)) matching_orders = Order.objects.filter( Q( code | Q(email__icontains=u) | Q(comment__icontains=u) ) ).values_list('id', flat=True) mainq = ( Q(order__id__in=matching_invoices) | Q(order__id__in=matching_invoice_addresses) | Q(order__id__in=matching_orders) ) qs = qs.filter(mainq) if fdata.get('amount'): amount = fdata.get('amount') def is_decimal(value): result = True parts = value.split('.', maxsplit=1) for part in parts: result = result & part.isdecimal() return result if is_decimal(amount): qs = qs.filter(amount=Decimal(amount)) if fdata.get('ordering'): p = self.cleaned_data.get('ordering') if p.startswith('-') and p not in self.orders: qs = qs.order_by('-' + self.orders[p[1:]]) else: qs = qs.order_by(self.orders[p]) else: qs = qs.order_by('-created') return qs class SubEventFilterForm(FilterForm): orders = { 'date_from': 'date_from', 'active': 'active', 'sum_quota_available': 'sum_quota_available' } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('active', _('Active')), ('running', _('Shop live and presale running')), ('inactive', _('Inactive')), ('future', _('Presale not started')), ('past', _('Presale over')), ), required=False ) date_from = forms.DateField( label=_('Date from'), required=False, widget=DatePickerWidget({ 'placeholder': _('Date from'), }), ) date_until = forms.DateField( label=_('Date until'), required=False, widget=DatePickerWidget({ 'placeholder': _('Date until'), }), ) time_from = forms.TimeField( label=_('Start time from'), required=False, widget=TimePickerWidget({}), ) time_until = forms.TimeField( label=_('Start time until'), required=False, widget=TimePickerWidget({}), ) weekday = forms.MultipleChoiceField( label=_('Weekday'), choices=( ('2', _('Monday')), ('3', _('Tuesday')), ('4', _('Wednesday')), ('5', _('Thursday')), ('6', _('Friday')), ('7', _('Saturday')), ('1', _('Sunday')), ), widget=forms.CheckboxSelectMultiple, required=False ) query = forms.CharField( label=_('Event name'), widget=forms.TextInput(attrs={ 'placeholder': _('Event name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['date_from'].widget = DatePickerWidget() self.fields['date_until'].widget = DatePickerWidget() def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'active': qs = qs.filter(active=True) elif fdata.get('status') == 'running': qs = qs.filter( active=True ).filter( Q(presale_start__isnull=True) | Q(presale_start__lte=now()) ).filter( Q(Q(presale_end__isnull=True) & Q( Q(date_to__gte=now()) | Q(date_to__isnull=True, date_from__gte=now()) )) | Q(presale_end__gte=now()) ) elif fdata.get('status') == 'inactive': qs = qs.filter(active=False) elif fdata.get('status') == 'future': qs = qs.filter(presale_start__gte=now()) elif fdata.get('status') == 'past': qs = qs.filter( Q(presale_end__lte=now()) | Q( Q(presale_end__isnull=True) & Q( Q(date_to__lte=now()) | Q(date_to__isnull=True, date_from__gte=now()) ) ) ) if fdata.get('weekday'): qs = qs.annotate(wday=ExtractWeekDay('date_from')).filter(wday__in=fdata.get('weekday')) if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=i18ncomp(query)) | Q(location__icontains=query) ) if fdata.get('date_until'): date_end = make_aware(datetime.combine( fdata.get('date_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter( Q(date_to__isnull=True, date_from__lt=date_end) | Q(date_to__isnull=False, date_to__lt=date_end) ) if fdata.get('date_from'): date_start = make_aware(datetime.combine( fdata.get('date_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(date_from__gte=date_start) if fdata.get('time_until'): qs = qs.filter(date_from__time__lte=fdata.get('time_until')) if fdata.get('time_from'): qs = qs.filter(date_from__time__gte=fdata.get('time_from')) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-date_from') return qs class OrganizerFilterForm(FilterForm): orders = { 'slug': 'slug', 'name': 'name', } query = forms.CharField( label=_('Organizer name'), widget=forms.TextInput(attrs={ 'placeholder': _('Organizer name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=query) | Q(slug__icontains=query) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs class GiftCardFilterForm(FilterForm): orders = { 'issuance': 'issuance', 'expires': F('expires').asc(nulls_last=True), '-expires': F('expires').desc(nulls_first=True), 'secret': 'secret', 'value': 'cached_value', } testmode = forms.ChoiceField( label=_('Test mode'), choices=( ('', _('All')), ('yes', _('Test mode')), ('no', _('Live')), ), required=False ) state = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('empty', _('Empty')), ('valid_value', _('Valid and with value')), ('expired_value', _('Expired and with value')), ('expired', _('Expired')), ), required=False ) query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(secret__icontains=query) | Q(transactions__text__icontains=query) | Q(transactions__order__code__icontains=query) ) if fdata.get('testmode') == 'yes': qs = qs.filter(testmode=True) elif fdata.get('testmode') == 'no': qs = qs.filter(testmode=False) if fdata.get('state') == 'empty': qs = qs.filter(cached_value=0) elif fdata.get('state') == 'valid_value': qs = qs.exclude(cached_value=0).filter(Q(expires__isnull=True) | Q(expires__gte=now())) elif fdata.get('state') == 'expired_value': qs = qs.exclude(cached_value=0).filter(expires__lt=now()) elif fdata.get('state') == 'expired': qs = qs.filter(expires__lt=now()) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-issuance') return qs.distinct() class CustomerFilterForm(FilterForm): orders = { 'email': 'email', 'identifier': 'identifier', 'name_cached': 'name_cached', } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) status = forms.ChoiceField( label=_('Status'), required=False, choices=( ('', _('All')), ('active', _('active')), ('disabled', _('disabled')), ('unverified', _('not yet activated')), ) ) memberships = forms.ChoiceField( label=_('Memberships'), required=False, choices=( ('', _('All')), ('no', _('Has no memberships')), ('any', _('Has any membership')), ('valid', _('Has valid membership')), ) ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(email__icontains=query) | Q(name_cached__icontains=query) | Q(identifier__istartswith=query) ) if fdata.get('status') == 'active': qs = qs.filter(is_active=True, is_verified=True) elif fdata.get('status') == 'disabled': qs = qs.filter(is_active=False) elif fdata.get('status') == 'unverified': qs = qs.filter(is_verified=False) if fdata.get('memberships') == 'no': qs = qs.filter(memberships__isnull=True) elif fdata.get('memberships') == 'any': qs = qs.filter(memberships__isnull=False) elif fdata.get('memberships') == 'valid': qs = qs.filter(memberships__date_start__lt=now(), memberships__date_end__gt=now(), memberships__canceled=False) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-email') return qs.distinct() class TeamFilterForm(FilterForm): orders = { 'name': 'name', } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(Exists( Team.members.through.objects.filter( Q(user__email__icontains=query) | Q(user__fullname__icontains=query), team_id=OuterRef('pk'), ) )) | Q(Exists( TeamInvite.objects.filter( email__icontains=query, team_id=OuterRef('pk'), ) )) | Q(Exists( TeamAPIToken.objects.filter( name__icontains=query, team_id=OuterRef('pk'), ) )) | Q(name__icontains=query) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('name') return qs.distinct() class EventFilterForm(FilterForm): orders = { 'slug': 'slug', 'organizer': 'organizer__name', 'date_from': 'order_from', 'date_to': 'order_to', 'live': 'live', } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All events')), ('live', _('Shop live')), ('running', _('Shop live and presale running')), ('notlive', _('Shop not live')), ('future', _('Presale not started')), ('past', _('Presale over')), ('date_future', _('Single event running or in the future')), ('date_past', _('Single event in the past')), ('series', _('Event series')), ), required=False ) organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ) ) query = forms.CharField( label=_('Event name'), widget=forms.TextInput(attrs={ 'placeholder': _('Event name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.organizer = kwargs.pop('organizer', None) super().__init__(*args, **kwargs) seen = set() for p in self.meta_properties.all(): if p.name in seen: continue seen.add(p.name) self.fields['meta_{}'.format(p.name)] = forms.CharField( label=p.name, required=False, widget=forms.TextInput( attrs={ 'data-typeahead-url': reverse('control:events.meta.typeahead') + '?' + urlencode({ 'property': p.name, 'organizer': self.organizer.slug if self.organizer else '' }) } ) ) if self.organizer: del self.fields['organizer'] else: if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'live': qs = qs.filter(live=True) elif fdata.get('status') == 'running': qs = qs.filter( live=True ).annotate( p_end=Coalesce(F('presale_end'), F('date_to'), F('date_from')) ).filter( Q(presale_start__isnull=True) | Q(presale_start__lte=now()) ).filter( Q(p_end__gte=now()) ) elif fdata.get('status') == 'notlive': qs = qs.filter(live=False) elif fdata.get('status') == 'future': qs = qs.filter(presale_start__gte=now()) elif fdata.get('status') == 'past': qs = qs.filter(presale_end__lte=now()) elif fdata.get('status') == 'date_future': qs = qs.filter( Q(has_subevents=False) & Q( Q(Q(date_to__isnull=True) & Q(date_from__gte=now())) | Q(Q(date_to__isnull=False) & Q(date_to__gte=now())) ) ) elif fdata.get('status') == 'date_past': qs = qs.filter( Q(has_subevents=False) & Q( Q(Q(date_to__isnull=True) & Q(date_from__lt=now())) | Q(Q(date_to__isnull=False) & Q(date_to__lt=now())) ) ) elif fdata.get('status') == 'series': qs = qs.filter(has_subevents=True) if fdata.get('organizer'): qs = qs.filter(organizer=fdata.get('organizer')) if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=i18ncomp(query)) | Q(slug__icontains=query) ) filters_by_property_name = {} for i, p in enumerate(self.meta_properties): d = fdata.get('meta_{}'.format(p.name)) if d: emv_with_value = EventMetaValue.objects.filter( event=OuterRef('pk'), property__pk=p.pk, value=d ) emv_with_any_value = EventMetaValue.objects.filter( event=OuterRef('pk'), property__pk=p.pk, ) qs = qs.annotate(**{'attr_{}'.format(i): Exists(emv_with_value)}) if p.name in filters_by_property_name: filters_by_property_name[p.name] |= Q(**{'attr_{}'.format(i): True}) else: filters_by_property_name[p.name] = Q(**{'attr_{}'.format(i): True}) if p.default == d: qs = qs.annotate(**{'attr_{}_any'.format(i): Exists(emv_with_any_value)}) filters_by_property_name[p.name] |= Q(**{'attr_{}_any'.format(i): False, 'organizer_id': p.organizer_id}) for f in filters_by_property_name.values(): qs = qs.filter(f) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs @cached_property def meta_properties(self): if self.organizer: return self.organizer.meta_properties.all() else: # We ignore superuser permissions here. This is intentional – we do not want to show super # users a form with all meta properties ever assigned. return EventMetaProperty.objects.filter( organizer_id__in=self.request.user.teams.values_list('organizer', flat=True) ) class CheckinListAttendeeFilterForm(FilterForm): orders = { 'code': ('order__code', 'item__name'), '-code': ('-order__code', '-item__name'), 'email': ('order__email', 'item__name'), '-email': ('-order__email', '-item__name'), 'status': (OrderBy(F('last_entry'), nulls_first=True, descending=True), 'order__code'), '-status': (OrderBy(F('last_entry'), nulls_last=True), '-order__code'), 'timestamp': (OrderBy(F('last_entry'), nulls_first=True), 'order__code'), '-timestamp': (OrderBy(F('last_entry'), nulls_last=True, descending=True), '-order__code'), 'item': ('item__name', 'variation__value', 'order__code'), '-item': ('-item__name', '-variation__value', '-order__code'), 'seat': ('seat__sorting_rank', 'seat__guid'), '-seat': ('-seat__sorting_rank', '-seat__guid'), 'date': ('subevent__date_from', 'subevent__id', 'order__code'), '-date': ('-subevent__date_from', 'subevent__id', '-order__code'), 'name': {'_order': F('display_name').asc(nulls_first=True), 'display_name': Coalesce('attendee_name_cached', 'addon_to__attendee_name_cached')}, '-name': {'_order': F('display_name').desc(nulls_last=True), 'display_name': Coalesce('attendee_name_cached', 'addon_to__attendee_name_cached')}, } user = forms.CharField( label=_('Search attendee…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search attendee…'), 'autofocus': 'autofocus' }), required=False ) status = forms.ChoiceField( label=_('Check-in status'), choices=( ('', _('All attendees')), ('3', pgettext_lazy('checkin state', 'Checked in but left')), ('2', pgettext_lazy('checkin state', 'Present')), ('1', _('Checked in')), ('0', _('Not checked in')), ), required=False, ) item = forms.ModelChoiceField( label=_('Products'), queryset=Item.objects.none(), required=False, empty_label=_('All products') ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) subevent_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'Date start from'), required=False, ) subevent_until = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'Date start until'), required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') self.list = kwargs.pop('list') super().__init__(*args, **kwargs) if self.list.all_products: self.fields['item'].queryset = self.event.items.all() else: self.fields['item'].queryset = self.list.limit_products.all() if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices else: del self.fields['subevent'] del self.fields['subevent_from'] del self.fields['subevent_until'] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('user'): u = fdata.get('user') qs = qs.filter( Q(order__code__istartswith=u) | Q(secret__istartswith=u) | Q(pseudonymization_id__istartswith=u) | Q(order__email__icontains=u) | Q(attendee_name_cached__icontains=u) | Q(attendee_email__icontains=u) | Q(voucher__code__istartswith=u) | Q(order__invoice_address__name_cached__icontains=u) | Q(order__invoice_address__company__icontains=u) ) if fdata.get('status'): s = fdata.get('status') if s == '1': qs = qs.filter(last_entry__isnull=False) elif s == '2': qs = qs.filter(last_entry__isnull=False).filter( Q(last_exit__isnull=True) | Q(last_exit__lt=F('last_entry')) ) elif s == '3': qs = qs.filter(last_entry__isnull=False).filter( Q(last_exit__isnull=False) & Q(last_exit__gte=F('last_entry')) ) elif s == '0': qs = qs.filter(last_entry__isnull=True) if fdata.get('ordering'): ob = self.orders[fdata.get('ordering')] if isinstance(ob, dict): ob = dict(ob) o = ob.pop('_order') qs = qs.annotate(**ob).order_by(o) elif isinstance(ob, (list, tuple)): qs = qs.order_by(*ob) else: qs = qs.order_by(ob) if fdata.get('item'): qs = qs.filter(item=fdata.get('item')) if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) if fdata.get('subevent_from'): qs = qs.filter(subevent__date_from__gte=fdata.get('subevent_from')) if fdata.get('subevent_until'): qs = qs.filter(subevent__date_from__lte=fdata.get('subevent_until')) return qs class UserFilterForm(FilterForm): orders = { 'fullname': 'fullname', 'email': 'email', } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('active', _('Active')), ('inactive', _('Inactive')), ), required=False ) superuser = forms.ChoiceField( label=_('Administrator'), choices=( ('', _('All')), ('yes', _('Administrator')), ('no', _('No administrator')), ), required=False ) query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'active': qs = qs.filter(is_active=True) elif fdata.get('status') == 'inactive': qs = qs.filter(is_active=False) if fdata.get('superuser') == 'yes': qs = qs.filter(is_staff=True) elif fdata.get('superuser') == 'no': qs = qs.filter(is_staff=False) if fdata.get('query'): qs = qs.filter( Q(email__icontains=fdata.get('query')) | Q(fullname__icontains=fdata.get('query')) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs class VoucherFilterForm(FilterForm): orders = { 'code': 'code', '-code': '-code', 'redeemed': 'redeemed', '-redeemed': '-redeemed', 'valid_until': 'valid_until', '-valid_until': '-valid_until', 'tag': 'tag', '-tag': '-tag', 'item': ( 'seat__sorting_rank', 'item__category__position', 'item__category', 'item__position', 'item__variation__position', 'quota__name', ), 'subevent': 'subevent__date_from', '-subevent': '-subevent__date_from', '-item': ( '-seat__sorting_rank', '-item__category__position', '-item__category', '-item__position', '-item__variation__position', '-quota__name', ) } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('v', _('Valid')), ('u', _('Unredeemed')), ('r', _('Redeemed at least once')), ('f', _('Fully redeemed')), ('e', _('Expired')), ('c', _('Redeemed and checked in with ticket')), ), required=False ) qm = forms.ChoiceField( label=_('Quota handling'), choices=( ('', _('All')), ('b', _('Reserve ticket from quota')), ('i', _('Allow to ignore quota')), ), required=False ) tag = forms.CharField( label=_('Filter by tag'), widget=forms.TextInput(attrs={ 'placeholder': _('Filter by tag'), }), required=False ) search = forms.CharField( label=_('Search voucher'), widget=forms.TextInput(attrs={ 'placeholder': _('Search voucher'), 'autofocus': 'autofocus' }), required=False ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) itemvar = forms.ChoiceField( label=_("Product"), required=False ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=i.name))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (i.name, v.value))) else: choices.append((str(i.pk), i.name)) for q in self.event.quotas.all(): choices.append(('q-%d' % q.pk, _('Any product in quota "{quota}"').format(quota=q))) self.fields['itemvar'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('search'): s = fdata.get('search').strip() qs = qs.filter(Q(code__icontains=s) | Q(tag__icontains=s) | Q(comment__icontains=s)) if fdata.get('tag'): s = fdata.get('tag').strip() if s == '<>': qs = qs.filter(Q(tag__isnull=True) | Q(tag='')) elif s[0] == '"' and s[-1] == '"': qs = qs.filter(tag__exact=s[1:-1]) else: qs = qs.filter(tag__icontains=s) if fdata.get('qm'): s = fdata.get('qm') if s == 'b': qs = qs.filter(block_quota=True) elif s == 'i': qs = qs.filter(allow_ignore_quota=True) if fdata.get('status'): s = fdata.get('status') if s == 'v': qs = qs.filter(Q(valid_until__isnull=True) | Q(valid_until__gt=now())).filter(redeemed__lt=F('max_usages')) elif s == 'r': qs = qs.filter(redeemed__gt=0) elif s == 'u': qs = qs.filter(redeemed=0) elif s == 'f': qs = qs.filter(redeemed__gte=F('max_usages')) elif s == 'e': qs = qs.filter(Q(valid_until__isnull=False) & Q(valid_until__lt=now())).filter(redeemed=0) elif s == 'c': checkins = Checkin.objects.filter( position__voucher=OuterRef('pk') ) qs = qs.annotate(has_checkin=Exists(checkins)).filter( redeemed__gt=0, has_checkin=True ) if fdata.get('itemvar'): if fdata.get('itemvar').startswith('q-'): qs = qs.filter(quota_id=fdata.get('itemvar').split('-')[1]) elif '-' in fdata.get('itemvar'): qs = qs.filter(item_id=fdata.get('itemvar').split('-')[0], variation_id=fdata.get('itemvar').split('-')[1]) else: qs = qs.filter(item_id=fdata.get('itemvar')) if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) if fdata.get('ordering'): ob = self.orders[fdata.get('ordering')] if isinstance(ob, dict): ob = dict(ob) o = ob.pop('_order') qs = qs.annotate(**ob).order_by(o) elif isinstance(ob, (list, tuple)): qs = qs.order_by(*ob) else: qs = qs.order_by(ob) return qs class VoucherTagFilterForm(FilterForm): subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) return qs class RefundFilterForm(FilterForm): orders = {'provider': 'provider', 'state': 'state', 'order': 'order__code', 'source': 'source', 'amount': 'amount', 'created': 'created'} provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) status = forms.ChoiceField( label=_('Refund status'), choices=( ('', _('All open refunds')), ('all', _('All refunds')), ) + OrderRefund.REFUND_STATES, required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['provider'].choices += [(k, v.verbose_name) for k, v in self.event.get_payment_providers().items()] def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('provider'): qs = qs.filter(provider=fdata.get('provider')) if fdata.get('status'): if fdata.get('status') != 'all': qs = qs.filter(state=fdata.get('status')) else: qs = qs.filter(state__in=[OrderRefund.REFUND_STATE_CREATED, OrderRefund.REFUND_STATE_TRANSIT, OrderRefund.REFUND_STATE_EXTERNAL]) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-created') return qs class OverviewFilterForm(FilterForm): subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) date_axis = forms.ChoiceField( label=_('Date filter'), choices=( ('', _('Filter by…')), ('order_date', _('Order date')), ('last_payment_date', _('Date of last successful payment')), ), required=False, ) date_from = forms.DateField( label=_('Date from'), required=False, widget=DatePickerWidget, ) date_until = forms.DateField( label=_('Date until'), required=False, widget=DatePickerWidget, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] class CheckinFilterForm(FilterForm): status = forms.ChoiceField( label=_('Status'), choices=[ ('', _('All check-ins')), ('successful', _('Successful check-ins')), ('unsuccessful', _('Unsuccessful check-ins')), ] + list(Checkin.REASONS), required=False ) type = forms.ChoiceField( label=_('Scan type'), choices=[ ('', _('All directions')), ] + list(Checkin.CHECKIN_TYPES), required=False ) itemvar = forms.ChoiceField( label=_("Product"), required=False ) device = SafeModelChoiceField( label=_('Device'), empty_label=_('All devices'), queryset=Device.objects.none(), required=False ) gate = SafeModelChoiceField( label=_('Gate'), empty_label=_('All gates'), queryset=Gate.objects.none(), required=False ) checkin_list = SafeModelChoiceField(queryset=CheckinList.objects.none(), required=False) # overridden later datetime_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('filter', 'Start date'), required=False, ) datetime_until = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('filter', 'End date'), required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['device'].queryset = self.event.organizer.devices.all() self.fields['gate'].queryset = self.event.organizer.gates.all() self.fields['checkin_list'].queryset = self.event.checkin_lists.all() self.fields['checkin_list'].widget = Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse('control:event.orders.checkinlists.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': _('Check-in list'), } ) self.fields['checkin_list'].widget.choices = self.fields['checkin_list'].choices self.fields['checkin_list'].label = _('Check-in list') choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=i.name))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (i.name, v.value))) else: choices.append((str(i.pk), i.name)) self.fields['itemvar'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status'): s = fdata.get('status') if s == 'successful': qs = qs.filter(successful=True) elif s == 'unsuccessful': qs = qs.filter(successful=False) elif s: qs = qs.filter(successful=False, error_reason=s) if fdata.get('type'): qs = qs.filter(type=fdata.get('type')) if fdata.get('itemvar'): if '-' in fdata.get('itemvar'): qs = qs.alias( item_id=Coalesce('raw_item_id', 'position__item_id'), variation_id=Coalesce('raw_variation_id', 'position__variation_id'), ).filter( item_id=fdata.get('itemvar').split('-')[0], variation_id=fdata.get('itemvar').split('-')[1] ) else: qs = qs.alias( item_id=Coalesce('raw_item_id', 'position__item_id'), ).filter(item_id=fdata.get('itemvar')) if fdata.get('device'): qs = qs.filter(device_id=fdata.get('device').pk) if fdata.get('gate'): qs = qs.filter(gate_id=fdata.get('gate').pk) if fdata.get('checkin_list'): qs = qs.filter(list_id=fdata.get('checkin_list').pk) if fdata.get('datetime_from'): qs = qs.filter(datetime__gte=fdata.get('datetime_from')) if fdata.get('datetime_until'): qs = qs.filter(datetime__lte=fdata.get('datetime_until')) return qs class DeviceFilterForm(FilterForm): orders = { 'name': Upper('name'), '-name': Upper('name').desc(), 'device_id': 'device_id', 'initialized': F('initialized').asc(nulls_last=True), '-initialized': F('initialized').desc(nulls_first=True), } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) gate = forms.ModelChoiceField( queryset=Gate.objects.none(), label=_('Gate'), empty_label=_('All gates'), required=False, ) software_brand = forms.ChoiceField( label=_('Software'), choices=[ ('', _('All')), ], required=False, ) state = forms.ChoiceField( label=_('Device status'), choices=[ ('', _('All devices')), ('active', _('Active devices')), ('revoked', _('Revoked devices')) ], required=False ) def __init__(self, *args, **kwargs): request = kwargs.pop('request') super().__init__(*args, **kwargs) self.fields['gate'].queryset = request.organizer.gates.all() self.fields['software_brand'].choices = [ ('', _('All')), ] + [ (f['software_brand'], f['software_brand']) for f in request.organizer.devices.order_by().values('software_brand').annotate(c=Count('*')) if f['software_brand'] ] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=query) | Q(unique_serial__icontains=query) | Q(hardware_brand__icontains=query) | Q(hardware_model__icontains=query) | Q(software_brand__icontains=query) ) if fdata.get('gate'): qs = qs.filter(gate=fdata['gate']) if fdata.get('state') == 'active': qs = qs.filter(revoked=False) elif fdata.get('state') == 'revoked': qs = qs.filter(revoked=True) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-device_id') return qs
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by the Free Software Foundation in version 3 of the License. # # ADDITIONAL TERMS APPLY: Pursuant to Section 7 of the GNU Affero General Public License, additional terms are # applicable granting you additional permissions and placing additional restrictions on your usage of this software. # Please refer to the pretix LICENSE file to obtain the full terms applicable to this work. If you did not receive # this file, see <https://pretix.eu/about/en/license>. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License along with this program. If not, see # <https://www.gnu.org/licenses/>. # # This file is based on an earlier version of pretix which was released under the Apache License 2.0. The full text of # the Apache License 2.0 can be obtained at <http://www.apache.org/licenses/LICENSE-2.0>. # # This file may have since been changed and any changes are released under the terms of AGPLv3 as described above. A # full history of changes and contributors is available at <https://github.com/pretix/pretix>. # # This file contains Apache-licensed contributions copyrighted by: Jakob Schnell, Tobias Kunze # # Unless required by applicable law or agreed to in writing, software distributed under the Apache License 2.0 is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under the License. from datetime import datetime, time, timedelta from decimal import Decimal from urllib.parse import urlencode from django import forms from django.apps import apps from django.conf import settings from django.db.models import ( Count, Exists, F, Max, Model, OrderBy, OuterRef, Q, QuerySet, ) from django.db.models.functions import Coalesce, ExtractWeekDay, Upper from django.urls import reverse, reverse_lazy from django.utils.formats import date_format, localize from django.utils.functional import cached_property from django.utils.timezone import get_current_timezone, make_aware, now from django.utils.translation import gettext, gettext_lazy as _, pgettext_lazy from django_scopes.forms import SafeModelChoiceField from pretix.base.channels import get_all_sales_channels from pretix.base.forms.widgets import ( DatePickerWidget, SplitDateTimePickerWidget, TimePickerWidget, ) from pretix.base.models import ( Checkin, CheckinList, Device, Event, EventMetaProperty, EventMetaValue, Gate, Invoice, InvoiceAddress, Item, Order, OrderPayment, OrderPosition, OrderRefund, Organizer, Question, QuestionAnswer, SubEvent, Team, TeamAPIToken, TeamInvite, ) from pretix.base.signals import register_payment_providers from pretix.control.forms.widgets import Select2 from pretix.control.signals import order_search_filter_q from pretix.helpers.countries import CachedCountries from pretix.helpers.database import rolledback_transaction from pretix.helpers.dicts import move_to_end from pretix.helpers.i18n import i18ncomp PAYMENT_PROVIDERS = [] def get_all_payment_providers(): global PAYMENT_PROVIDERS if PAYMENT_PROVIDERS: return PAYMENT_PROVIDERS with rolledback_transaction(): event = Event.objects.create( plugins=",".join([app.name for app in apps.get_app_configs()]), name="INTERNAL", date_from=now(), organizer=Organizer.objects.create(name="INTERNAL") ) provs = register_payment_providers.send( sender=event ) choices = [] for recv, prov in provs: if isinstance(prov, list): for p in prov: p = p(event) if not p.is_meta: choices.append((p.identifier, p.verbose_name)) else: prov = prov(event) if not prov.is_meta: choices.append((prov.identifier, prov.verbose_name)) PAYMENT_PROVIDERS = choices return choices class FilterForm(forms.Form): orders = {} def filter_qs(self, qs): return qs @property def filtered(self): return self.is_valid() and any(self.cleaned_data.values()) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['ordering'] = forms.ChoiceField( choices=sum([ [(a, a), ('-' + a, '-' + a)] for a in self.orders.keys() ], []), required=False ) def get_order_by(self): o = self.cleaned_data.get('ordering') if o.startswith('-') and o not in self.orders: return '-' + self.orders[o[1:]] else: return self.orders[o] def filter_to_strings(self): string = [] for k, f in self.fields.items(): v = self.cleaned_data.get(k) if v is None or (isinstance(v, (list, str, QuerySet)) and len(v) == 0): continue if k == "saveas": continue if isinstance(v, bool): val = _('Yes') if v else _('No') elif isinstance(v, QuerySet): q = ['"' + str(m) + '"' for m in v] if not q: continue val = ' or '.join(q) elif isinstance(v, Model): val = '"' + str(v) + '"' elif isinstance(f, forms.MultipleChoiceField): valdict = dict(f.choices) val = ' or '.join([str(valdict.get(m)) for m in v]) elif isinstance(f, forms.ChoiceField): val = str(dict(f.choices).get(v)) elif isinstance(v, datetime): val = date_format(v, 'SHORT_DATETIME_FORMAT') elif isinstance(v, Decimal): val = localize(v) else: val = v string.append('{}: {}'.format(f.label, val)) return string class OrderFilterForm(FilterForm): query = forms.CharField( label=_('Search for…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search for…'), 'autofocus': 'autofocus' }), required=False ) provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) status = forms.ChoiceField( label=_('Order status'), choices=( ('', _('All orders')), (_('Valid orders'), ( (Order.STATUS_PAID, _('Paid (or canceled with paid fee)')), (Order.STATUS_PENDING, _('Pending')), (Order.STATUS_PENDING + Order.STATUS_PAID, _('Pending or paid')), )), (_('Cancellations'), ( (Order.STATUS_CANCELED, _('Canceled (fully)')), ('cp', _('Canceled (fully or with paid fee)')), ('rc', _('Cancellation requested')), ('cni', _('Fully canceled but invoice not canceled')), )), (_('Payment process'), ( (Order.STATUS_EXPIRED, _('Expired')), (Order.STATUS_PENDING + Order.STATUS_EXPIRED, _('Pending or expired')), ('o', _('Pending (overdue)')), ('overpaid', _('Overpaid')), ('partially_paid', _('Partially paid')), ('underpaid', _('Underpaid (but confirmed)')), ('pendingpaid', _('Pending (but fully paid)')), )), (_('Approval process'), ( ('na', _('Approved, payment pending')), ('pa', _('Approval pending')), )), (_('Follow-up date'), ( ('custom_followup_at', _('Follow-up configured')), ('custom_followup_due', _('Follow-up due')), )), ('testmode', _('Test mode')), ), required=False, ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): u = fdata.get('query') if "-" in u: code = (Q(event__slug__icontains=u.rsplit("-", 1)[0]) & Q(code__icontains=Order.normalize_code(u.rsplit("-", 1)[1]))) else: code = Q(code__icontains=Order.normalize_code(u)) matching_invoices = Invoice.objects.filter( Q(invoice_no__iexact=u) | Q(invoice_no__iexact=u.zfill(5)) | Q(full_invoice_no__iexact=u) ).values_list('order_id', flat=True) matching_positions = OrderPosition.objects.filter( Q( Q(attendee_name_cached__icontains=u) | Q(attendee_email__icontains=u) | Q(secret__istartswith=u) | Q(pseudonymization_id__istartswith=u) ) ).values_list('order_id', flat=True) matching_invoice_addresses = InvoiceAddress.objects.filter( Q( Q(name_cached__icontains=u) | Q(company__icontains=u) ) ).values_list('order_id', flat=True) matching_orders = Order.objects.filter( code | Q(email__icontains=u) | Q(comment__icontains=u) ).values_list('id', flat=True) mainq = ( Q(pk__in=matching_orders) | Q(pk__in=matching_invoices) | Q(pk__in=matching_positions) | Q(pk__in=matching_invoice_addresses) | Q(pk__in=matching_invoices) ) for recv, q in order_search_filter_q.send(sender=getattr(self, 'event', None), query=u): mainq = mainq | q qs = qs.filter( mainq ) if fdata.get('status'): s = fdata.get('status') if s == 'o': qs = qs.filter(status=Order.STATUS_PENDING, expires__lt=now().replace(hour=0, minute=0, second=0)) elif s == 'np': qs = qs.filter(status__in=[Order.STATUS_PENDING, Order.STATUS_PAID]) elif s == 'ne': qs = qs.filter(status__in=[Order.STATUS_PENDING, Order.STATUS_EXPIRED]) elif s in ('p', 'n', 'e', 'c', 'r'): qs = qs.filter(status=s) elif s == 'overpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(~Q(status=Order.STATUS_CANCELED) & Q(pending_sum_t__lt=0)) | Q(Q(status=Order.STATUS_CANCELED) & Q(pending_sum_rc__lt=0)) ) elif s == 'rc': qs = qs.filter( cancellation_requests__isnull=False ).annotate( cancellation_request_time=Max('cancellation_requests__created') ).order_by( '-cancellation_request_time' ) elif s == 'pendingpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(status__in=(Order.STATUS_EXPIRED, Order.STATUS_PENDING)) & Q(pending_sum_t__lte=0) & Q(require_approval=False) ) elif s == 'partially_paid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__lt=F('total'), computed_payment_refund_sum__gt=Decimal('0.00') ).exclude( status=Order.STATUS_CANCELED ) elif s == 'underpaid': qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( Q(status=Order.STATUS_PAID, pending_sum_t__gt=0) | Q(status=Order.STATUS_CANCELED, pending_sum_rc__gt=0) ) elif s == 'cni': i = Invoice.objects.filter( order=OuterRef('pk'), is_cancellation=False, refered__isnull=True, ).order_by().values('order').annotate(k=Count('id')).values('k') qs = qs.annotate( icnt=i ).filter( icnt__gt=0, status=Order.STATUS_CANCELED, ) elif s == 'pa': qs = qs.filter( status=Order.STATUS_PENDING, require_approval=True ) elif s == 'na': qs = qs.filter( status=Order.STATUS_PENDING, require_approval=False ) elif s == 'custom_followup_at': qs = qs.filter( custom_followup_at__isnull=False ) elif s == 'custom_followup_due': qs = qs.filter( custom_followup_at__lte=now().astimezone(get_current_timezone()).date() ) elif s == 'testmode': qs = qs.filter( testmode=True ) elif s == 'cp': s = OrderPosition.objects.filter( order=OuterRef('pk') ) qs = qs.annotate( has_pc=Exists(s) ).filter( Q(status=Order.STATUS_PAID, has_pc=False) | Q(status=Order.STATUS_CANCELED) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) if fdata.get('provider'): qs = qs.annotate( has_payment_with_provider=Exists( OrderPayment.objects.filter( Q(order=OuterRef('pk')) & Q(provider=fdata.get('provider')) ) ) ) qs = qs.filter(has_payment_with_provider=1) return qs class EventOrderFilterForm(OrderFilterForm): orders = {'code': 'code', 'email': 'email', 'total': 'total', 'datetime': 'datetime', 'status': 'status'} item = forms.ChoiceField( label=_('Products'), required=False, ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) question = forms.ModelChoiceField( queryset=Question.objects.none(), required=False, ) answer = forms.CharField( required=False ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['item'].queryset = self.event.items.all() self.fields['question'].queryset = self.event.questions.all() self.fields['provider'].choices += [(k, v.verbose_name) for k, v in self.event.get_payment_providers().items()] if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=str(i)))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (str(i), v.value))) else: choices.append((str(i.pk), str(i))) self.fields['item'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) item = fdata.get('item') if item: if '-' in item: var = item.split('-')[1] qs = qs.filter(all_positions__variation_id=var, all_positions__canceled=False).distinct() else: qs = qs.filter(all_positions__item_id=fdata.get('item'), all_positions__canceled=False).distinct() if fdata.get('subevent'): qs = qs.filter(all_positions__subevent=fdata.get('subevent'), all_positions__canceled=False).distinct() if fdata.get('question') and fdata.get('answer') is not None: q = fdata.get('question') if q.type == Question.TYPE_FILE: answers = QuestionAnswer.objects.filter( orderposition__order_id=OuterRef('pk'), question_id=q.pk, file__isnull=False ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) elif q.type in (Question.TYPE_CHOICE, Question.TYPE_CHOICE_MULTIPLE): answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), options__pk=fdata.get('answer') ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) else: answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), answer__exact=fdata.get('answer') ) qs = qs.annotate(has_answer=Exists(answers)).filter(has_answer=True) return qs class FilterNullBooleanSelect(forms.NullBooleanSelect): def __init__(self, attrs=None): choices = ( ('unknown', _('All')), ('true', _('Yes')), ('false', _('No')), ) super(forms.NullBooleanSelect, self).__init__(attrs, choices) class EventOrderExpertFilterForm(EventOrderFilterForm): subevents_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'All dates starting at or after'), required=False, ) subevents_to = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'All dates starting before'), required=False, ) created_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=_('Order placed at or after'), required=False, ) created_to = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=_('Order placed before'), required=False, ) email = forms.CharField( required=False, label=_('E-mail address') ) comment = forms.CharField( required=False, label=_('Comment') ) locale = forms.ChoiceField( required=False, label=_('Locale'), choices=settings.LANGUAGES ) email_known_to_work = forms.NullBooleanField( required=False, widget=FilterNullBooleanSelect, label=_('E-mail address verified'), ) total = forms.DecimalField( localize=True, required=False, label=_('Total amount'), ) payment_sum_min = forms.DecimalField( localize=True, required=False, label=_('Minimal sum of payments and refunds'), ) payment_sum_max = forms.DecimalField( localize=True, required=False, label=_('Maximal sum of payments and refunds'), ) sales_channel = forms.ChoiceField( label=_('Sales channel'), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['query'] del self.fields['question'] del self.fields['answer'] del self.fields['ordering'] if not self.event.has_subevents: del self.fields['subevents_from'] del self.fields['subevents_to'] self.fields['sales_channel'].choices = [('', '')] + [ (k, v.verbose_name) for k, v in get_all_sales_channels().items() ] locale_names = dict(settings.LANGUAGES) self.fields['locale'].choices = [('', '')] + [(a, locale_names[a]) for a in self.event.settings.locales] move_to_end(self.fields, 'item') move_to_end(self.fields, 'provider') self.fields['invoice_address_company'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Company') ) self.fields['invoice_address_name'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Name') ) self.fields['invoice_address_street'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('Address') ) self.fields['invoice_address_zipcode'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('ZIP code'), help_text=_('Exact matches only') ) self.fields['invoice_address_city'] = forms.CharField( required=False, label=gettext('Invoice address') + ': ' + gettext('City'), help_text=_('Exact matches only') ) self.fields['invoice_address_country'] = forms.ChoiceField( required=False, label=gettext('Invoice address') + ': ' + gettext('Country'), choices=[('', '')] + list(CachedCountries()) ) self.fields['attendee_name'] = forms.CharField( required=False, label=_('Attendee name') ) self.fields['attendee_email'] = forms.CharField( required=False, label=_('Attendee e-mail address') ) self.fields['attendee_address_company'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('Company') ) self.fields['attendee_address_street'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('Address') ) self.fields['attendee_address_zipcode'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('ZIP code'), help_text=_('Exact matches only') ) self.fields['attendee_address_city'] = forms.CharField( required=False, label=gettext('Attendee address') + ': ' + gettext('City'), help_text=_('Exact matches only') ) self.fields['attendee_address_country'] = forms.ChoiceField( required=False, label=gettext('Attendee address') + ': ' + gettext('Country'), choices=[('', '')] + list(CachedCountries()) ) self.fields['ticket_secret'] = forms.CharField( label=_('Ticket secret'), required=False ) for q in self.event.questions.all(): self.fields['question_{}'.format(q.pk)] = forms.CharField( label=q.question, required=False, help_text=_('Exact matches only') ) def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('subevents_from'): qs = qs.filter( all_positions__subevent__date_from__gte=fdata.get('subevents_from'), all_positions__canceled=False ).distinct() if fdata.get('subevents_to'): qs = qs.filter( all_positions__subevent__date_from__lt=fdata.get('subevents_to'), all_positions__canceled=False ).distinct() if fdata.get('email'): qs = qs.filter( email__icontains=fdata.get('email') ) if fdata.get('created_from'): qs = qs.filter(datetime__gte=fdata.get('created_from')) if fdata.get('created_to'): qs = qs.filter(datetime__lte=fdata.get('created_to')) if fdata.get('comment'): qs = qs.filter(comment__icontains=fdata.get('comment')) if fdata.get('sales_channel'): qs = qs.filter(sales_channel=fdata.get('sales_channel')) if fdata.get('total'): qs = qs.filter(total=fdata.get('total')) if fdata.get('email_known_to_work') is not None: qs = qs.filter(email_known_to_work=fdata.get('email_known_to_work')) if fdata.get('locale'): qs = qs.filter(locale=fdata.get('locale')) if fdata.get('payment_sum_min') is not None: qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__gte=fdata['payment_sum_min'], ) if fdata.get('payment_sum_max') is not None: qs = Order.annotate_overpayments(qs, refunds=False, results=False, sums=True) qs = qs.filter( computed_payment_refund_sum__lte=fdata['payment_sum_max'], ) if fdata.get('invoice_address_company'): qs = qs.filter(invoice_address__company__icontains=fdata.get('invoice_address_company')) if fdata.get('invoice_address_name'): qs = qs.filter(invoice_address__name_cached__icontains=fdata.get('invoice_address_name')) if fdata.get('invoice_address_street'): qs = qs.filter(invoice_address__street__icontains=fdata.get('invoice_address_street')) if fdata.get('invoice_address_zipcode'): qs = qs.filter(invoice_address__zipcode__iexact=fdata.get('invoice_address_zipcode')) if fdata.get('invoice_address_city'): qs = qs.filter(invoice_address__city__iexact=fdata.get('invoice_address_city')) if fdata.get('invoice_address_country'): qs = qs.filter(invoice_address__country=fdata.get('invoice_address_country')) if fdata.get('attendee_name'): qs = qs.filter( all_positions__attendee_name_cached__icontains=fdata.get('attendee_name') ) if fdata.get('attendee_address_company'): qs = qs.filter( all_positions__company__icontains=fdata.get('attendee_address_company') ).distinct() if fdata.get('attendee_address_street'): qs = qs.filter( all_positions__street__icontains=fdata.get('attendee_address_street') ).distinct() if fdata.get('attendee_address_city'): qs = qs.filter( all_positions__city__iexact=fdata.get('attendee_address_city') ).distinct() if fdata.get('attendee_address_country'): qs = qs.filter( all_positions__country=fdata.get('attendee_address_country') ).distinct() if fdata.get('ticket_secret'): qs = qs.filter( all_positions__secret__icontains=fdata.get('ticket_secret') ).distinct() for q in self.event.questions.all(): if fdata.get(f'question_{q.pk}'): answers = QuestionAnswer.objects.filter( question_id=q.pk, orderposition__order_id=OuterRef('pk'), answer__iexact=fdata.get(f'question_{q.pk}') ) qs = qs.annotate(**{f'q_{q.pk}': Exists(answers)}).filter(**{f'q_{q.pk}': True}) return qs class OrderSearchFilterForm(OrderFilterForm): orders = {'code': 'code', 'email': 'email', 'total': 'total', 'datetime': 'datetime', 'status': 'status', 'event': 'event'} organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ) ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) self.fields['provider'].choices += get_all_payment_providers() seen = set() for p in self.meta_properties.all(): if p.name in seen: continue seen.add(p.name) self.fields['meta_{}'.format(p.name)] = forms.CharField( label=p.name, required=False, widget=forms.TextInput( attrs={ 'data-typeahead-url': reverse('control:events.meta.typeahead') + '?' + urlencode({ 'property': p.name, 'organizer': '' }) } ) ) def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('organizer'): qs = qs.filter(event__organizer=fdata.get('organizer')) filters_by_property_name = {} for i, p in enumerate(self.meta_properties): d = fdata.get('meta_{}'.format(p.name)) if d: emv_with_value = EventMetaValue.objects.filter( event=OuterRef('event_id'), property__pk=p.pk, value=d ) emv_with_any_value = EventMetaValue.objects.filter( event=OuterRef('event_id'), property__pk=p.pk, ) qs = qs.annotate(**{'attr_{}'.format(i): Exists(emv_with_value)}) if p.name in filters_by_property_name: filters_by_property_name[p.name] |= Q(**{'attr_{}'.format(i): True}) else: filters_by_property_name[p.name] = Q(**{'attr_{}'.format(i): True}) if p.default == d: qs = qs.annotate(**{'attr_{}_any'.format(i): Exists(emv_with_any_value)}) filters_by_property_name[p.name] |= Q(**{ 'attr_{}_any'.format(i): False, 'event__organizer_id': p.organizer_id }) for f in filters_by_property_name.values(): qs = qs.filter(f) return qs @cached_property def meta_properties(self): # We ignore superuser permissions here. This is intentional – we do not want to show super # users a form with all meta properties ever assigned. return EventMetaProperty.objects.filter( organizer_id__in=self.request.user.teams.values_list('organizer', flat=True) ) class OrderPaymentSearchFilterForm(forms.Form): orders = {'id': 'id', 'local_id': 'local_id', 'state': 'state', 'amount': 'amount', 'order': 'order', 'created': 'created', 'payment_date': 'payment_date', 'provider': 'provider', 'info': 'info', 'fee': 'fee'} query = forms.CharField( label=_('Search for…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search for…'), 'autofocus': 'autofocus' }), required=False, ) event = forms.ModelChoiceField( label=_('Event'), queryset=Event.objects.none(), required=False, widget=Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse_lazy('control:events.typeahead'), 'data-placeholder': _('All events') } ) ) organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ), ) state = forms.ChoiceField( label=_('Status'), required=False, choices=[('', _('All payments'))] + list(OrderPayment.PAYMENT_STATES), ) provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) created_from = forms.DateField( label=_('Payment created from'), required=False, widget=DatePickerWidget, ) created_until = forms.DateField( label=_('Payment created until'), required=False, widget=DatePickerWidget, ) completed_from = forms.DateField( label=_('Paid from'), required=False, widget=DatePickerWidget, ) completed_until = forms.DateField( label=_('Paid until'), required=False, widget=DatePickerWidget, ) amount = forms.CharField( label=_('Amount'), required=False, widget=forms.NumberInput(attrs={ 'placeholder': _('Amount'), }), ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) self.fields['ordering'] = forms.ChoiceField( choices=sum([ [(a, a), ('-' + a, '-' + a)] for a in self.orders.keys() ], []), required=False ) if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() self.fields['event'].queryset = Event.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) self.fields['event'].queryset = self.request.user.get_events_with_permission('can_view_orders') self.fields['provider'].choices += get_all_payment_providers() def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('created_from'): date_start = make_aware(datetime.combine( fdata.get('created_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(created__gte=date_start) if fdata.get('created_until'): date_end = make_aware(datetime.combine( fdata.get('created_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(created__lt=date_end) if fdata.get('completed_from'): date_start = make_aware(datetime.combine( fdata.get('completed_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(payment_date__gte=date_start) if fdata.get('completed_until'): date_end = make_aware(datetime.combine( fdata.get('completed_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(payment_date__lt=date_end) if fdata.get('event'): qs = qs.filter(order__event=fdata.get('event')) if fdata.get('organizer'): qs = qs.filter(order__event__organizer=fdata.get('organizer')) if fdata.get('state'): qs = qs.filter(state=fdata.get('state')) if fdata.get('provider'): qs = qs.filter(provider=fdata.get('provider')) if fdata.get('query'): u = fdata.get('query') matching_invoices = Invoice.objects.filter( Q(invoice_no__iexact=u) | Q(invoice_no__iexact=u.zfill(5)) | Q(full_invoice_no__iexact=u) ).values_list('order_id', flat=True) matching_invoice_addresses = InvoiceAddress.objects.filter( Q( Q(name_cached__icontains=u) | Q(company__icontains=u) ) ).values_list('order_id', flat=True) if "-" in u: code = (Q(event__slug__icontains=u.rsplit("-", 1)[0]) & Q(code__icontains=Order.normalize_code(u.rsplit("-", 1)[1]))) else: code = Q(code__icontains=Order.normalize_code(u)) matching_orders = Order.objects.filter( Q( code | Q(email__icontains=u) | Q(comment__icontains=u) ) ).values_list('id', flat=True) mainq = ( Q(order__id__in=matching_invoices) | Q(order__id__in=matching_invoice_addresses) | Q(order__id__in=matching_orders) ) qs = qs.filter(mainq) if fdata.get('amount'): amount = fdata.get('amount') def is_decimal(value): result = True parts = value.split('.', maxsplit=1) for part in parts: result = result & part.isdecimal() return result if is_decimal(amount): qs = qs.filter(amount=Decimal(amount)) if fdata.get('ordering'): p = self.cleaned_data.get('ordering') if p.startswith('-') and p not in self.orders: qs = qs.order_by('-' + self.orders[p[1:]]) else: qs = qs.order_by(self.orders[p]) else: qs = qs.order_by('-created') return qs class SubEventFilterForm(FilterForm): orders = { 'date_from': 'date_from', 'active': 'active', 'sum_quota_available': 'sum_quota_available' } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('active', _('Active')), ('running', _('Shop live and presale running')), ('inactive', _('Inactive')), ('future', _('Presale not started')), ('past', _('Presale over')), ), required=False ) date_from = forms.DateField( label=_('Date from'), required=False, widget=DatePickerWidget({ 'placeholder': _('Date from'), }), ) date_until = forms.DateField( label=_('Date until'), required=False, widget=DatePickerWidget({ 'placeholder': _('Date until'), }), ) time_from = forms.TimeField( label=_('Start time from'), required=False, widget=TimePickerWidget({}), ) time_until = forms.TimeField( label=_('Start time until'), required=False, widget=TimePickerWidget({}), ) weekday = forms.MultipleChoiceField( label=_('Weekday'), choices=( ('2', _('Monday')), ('3', _('Tuesday')), ('4', _('Wednesday')), ('5', _('Thursday')), ('6', _('Friday')), ('7', _('Saturday')), ('1', _('Sunday')), ), widget=forms.CheckboxSelectMultiple, required=False ) query = forms.CharField( label=_('Event name'), widget=forms.TextInput(attrs={ 'placeholder': _('Event name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['date_from'].widget = DatePickerWidget() self.fields['date_until'].widget = DatePickerWidget() def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'active': qs = qs.filter(active=True) elif fdata.get('status') == 'running': qs = qs.filter( active=True ).filter( Q(presale_start__isnull=True) | Q(presale_start__lte=now()) ).filter( Q(Q(presale_end__isnull=True) & Q( Q(date_to__gte=now()) | Q(date_to__isnull=True, date_from__gte=now()) )) | Q(presale_end__gte=now()) ) elif fdata.get('status') == 'inactive': qs = qs.filter(active=False) elif fdata.get('status') == 'future': qs = qs.filter(presale_start__gte=now()) elif fdata.get('status') == 'past': qs = qs.filter( Q(presale_end__lte=now()) | Q( Q(presale_end__isnull=True) & Q( Q(date_to__lte=now()) | Q(date_to__isnull=True, date_from__gte=now()) ) ) ) if fdata.get('weekday'): qs = qs.annotate(wday=ExtractWeekDay('date_from')).filter(wday__in=fdata.get('weekday')) if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=i18ncomp(query)) | Q(location__icontains=query) ) if fdata.get('date_until'): date_end = make_aware(datetime.combine( fdata.get('date_until') + timedelta(days=1), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter( Q(date_to__isnull=True, date_from__lt=date_end) | Q(date_to__isnull=False, date_to__lt=date_end) ) if fdata.get('date_from'): date_start = make_aware(datetime.combine( fdata.get('date_from'), time(hour=0, minute=0, second=0, microsecond=0) ), get_current_timezone()) qs = qs.filter(date_from__gte=date_start) if fdata.get('time_until'): qs = qs.filter(date_from__time__lte=fdata.get('time_until')) if fdata.get('time_from'): qs = qs.filter(date_from__time__gte=fdata.get('time_from')) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-date_from') return qs class OrganizerFilterForm(FilterForm): orders = { 'slug': 'slug', 'name': 'name', } query = forms.CharField( label=_('Organizer name'), widget=forms.TextInput(attrs={ 'placeholder': _('Organizer name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=query) | Q(slug__icontains=query) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs class GiftCardFilterForm(FilterForm): orders = { 'issuance': 'issuance', 'expires': F('expires').asc(nulls_last=True), '-expires': F('expires').desc(nulls_first=True), 'secret': 'secret', 'value': 'cached_value', } testmode = forms.ChoiceField( label=_('Test mode'), choices=( ('', _('All')), ('yes', _('Test mode')), ('no', _('Live')), ), required=False ) state = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('empty', _('Empty')), ('valid_value', _('Valid and with value')), ('expired_value', _('Expired and with value')), ('expired', _('Expired')), ), required=False ) query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(secret__icontains=query) | Q(transactions__text__icontains=query) | Q(transactions__order__code__icontains=query) ) if fdata.get('testmode') == 'yes': qs = qs.filter(testmode=True) elif fdata.get('testmode') == 'no': qs = qs.filter(testmode=False) if fdata.get('state') == 'empty': qs = qs.filter(cached_value=0) elif fdata.get('state') == 'valid_value': qs = qs.exclude(cached_value=0).filter(Q(expires__isnull=True) | Q(expires__gte=now())) elif fdata.get('state') == 'expired_value': qs = qs.exclude(cached_value=0).filter(expires__lt=now()) elif fdata.get('state') == 'expired': qs = qs.filter(expires__lt=now()) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-issuance') return qs.distinct() class CustomerFilterForm(FilterForm): orders = { 'email': 'email', 'identifier': 'identifier', 'name_cached': 'name_cached', } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) status = forms.ChoiceField( label=_('Status'), required=False, choices=( ('', _('All')), ('active', _('active')), ('disabled', _('disabled')), ('unverified', _('not yet activated')), ) ) memberships = forms.ChoiceField( label=_('Memberships'), required=False, choices=( ('', _('All')), ('no', _('Has no memberships')), ('any', _('Has any membership')), ('valid', _('Has valid membership')), ) ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(email__icontains=query) | Q(name_cached__icontains=query) | Q(identifier__istartswith=query) ) if fdata.get('status') == 'active': qs = qs.filter(is_active=True, is_verified=True) elif fdata.get('status') == 'disabled': qs = qs.filter(is_active=False) elif fdata.get('status') == 'unverified': qs = qs.filter(is_verified=False) if fdata.get('memberships') == 'no': qs = qs.filter(memberships__isnull=True) elif fdata.get('memberships') == 'any': qs = qs.filter(memberships__isnull=False) elif fdata.get('memberships') == 'valid': qs = qs.filter(memberships__date_start__lt=now(), memberships__date_end__gt=now(), memberships__canceled=False) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-email') return qs.distinct() class TeamFilterForm(FilterForm): orders = { 'name': 'name', } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): kwargs.pop('request') super().__init__(*args, **kwargs) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(Exists( Team.members.through.objects.filter( Q(user__email__icontains=query) | Q(user__fullname__icontains=query), team_id=OuterRef('pk'), ) )) | Q(Exists( TeamInvite.objects.filter( email__icontains=query, team_id=OuterRef('pk'), ) )) | Q(Exists( TeamAPIToken.objects.filter( name__icontains=query, team_id=OuterRef('pk'), ) )) | Q(name__icontains=query) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('name') return qs.distinct() class EventFilterForm(FilterForm): orders = { 'slug': 'slug', 'organizer': 'organizer__name', 'date_from': 'order_from', 'date_to': 'order_to', 'live': 'live', } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All events')), ('live', _('Shop live')), ('running', _('Shop live and presale running')), ('notlive', _('Shop not live')), ('future', _('Presale not started')), ('past', _('Presale over')), ('date_future', _('Single event running or in the future')), ('date_past', _('Single event in the past')), ('series', _('Event series')), ), required=False ) organizer = forms.ModelChoiceField( label=_('Organizer'), queryset=Organizer.objects.none(), required=False, empty_label=_('All organizers'), widget=Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse_lazy('control:organizers.select2'), 'data-placeholder': _('All organizers') } ) ) query = forms.CharField( label=_('Event name'), widget=forms.TextInput(attrs={ 'placeholder': _('Event name'), 'autofocus': 'autofocus' }), required=False ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') self.organizer = kwargs.pop('organizer', None) super().__init__(*args, **kwargs) seen = set() for p in self.meta_properties.all(): if p.name in seen: continue seen.add(p.name) self.fields['meta_{}'.format(p.name)] = forms.CharField( label=p.name, required=False, widget=forms.TextInput( attrs={ 'data-typeahead-url': reverse('control:events.meta.typeahead') + '?' + urlencode({ 'property': p.name, 'organizer': self.organizer.slug if self.organizer else '' }) } ) ) if self.organizer: del self.fields['organizer'] else: if self.request.user.has_active_staff_session(self.request.session.session_key): self.fields['organizer'].queryset = Organizer.objects.all() else: self.fields['organizer'].queryset = Organizer.objects.filter( pk__in=self.request.user.teams.values_list('organizer', flat=True) ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'live': qs = qs.filter(live=True) elif fdata.get('status') == 'running': qs = qs.filter( live=True ).annotate( p_end=Coalesce(F('presale_end'), F('date_to'), F('date_from')) ).filter( Q(presale_start__isnull=True) | Q(presale_start__lte=now()) ).filter( Q(p_end__gte=now()) ) elif fdata.get('status') == 'notlive': qs = qs.filter(live=False) elif fdata.get('status') == 'future': qs = qs.filter(presale_start__gte=now()) elif fdata.get('status') == 'past': qs = qs.filter(presale_end__lte=now()) elif fdata.get('status') == 'date_future': qs = qs.filter( Q(has_subevents=False) & Q( Q(Q(date_to__isnull=True) & Q(date_from__gte=now())) | Q(Q(date_to__isnull=False) & Q(date_to__gte=now())) ) ) elif fdata.get('status') == 'date_past': qs = qs.filter( Q(has_subevents=False) & Q( Q(Q(date_to__isnull=True) & Q(date_from__lt=now())) | Q(Q(date_to__isnull=False) & Q(date_to__lt=now())) ) ) elif fdata.get('status') == 'series': qs = qs.filter(has_subevents=True) if fdata.get('organizer'): qs = qs.filter(organizer=fdata.get('organizer')) if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=i18ncomp(query)) | Q(slug__icontains=query) ) filters_by_property_name = {} for i, p in enumerate(self.meta_properties): d = fdata.get('meta_{}'.format(p.name)) if d: emv_with_value = EventMetaValue.objects.filter( event=OuterRef('pk'), property__pk=p.pk, value=d ) emv_with_any_value = EventMetaValue.objects.filter( event=OuterRef('pk'), property__pk=p.pk, ) qs = qs.annotate(**{'attr_{}'.format(i): Exists(emv_with_value)}) if p.name in filters_by_property_name: filters_by_property_name[p.name] |= Q(**{'attr_{}'.format(i): True}) else: filters_by_property_name[p.name] = Q(**{'attr_{}'.format(i): True}) if p.default == d: qs = qs.annotate(**{'attr_{}_any'.format(i): Exists(emv_with_any_value)}) filters_by_property_name[p.name] |= Q(**{'attr_{}_any'.format(i): False, 'organizer_id': p.organizer_id}) for f in filters_by_property_name.values(): qs = qs.filter(f) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs @cached_property def meta_properties(self): if self.organizer: return self.organizer.meta_properties.all() else: # We ignore superuser permissions here. This is intentional – we do not want to show super # users a form with all meta properties ever assigned. return EventMetaProperty.objects.filter( organizer_id__in=self.request.user.teams.values_list('organizer', flat=True) ) class CheckinListAttendeeFilterForm(FilterForm): orders = { 'code': ('order__code', 'item__name'), '-code': ('-order__code', '-item__name'), 'email': ('order__email', 'item__name'), '-email': ('-order__email', '-item__name'), 'status': (OrderBy(F('last_entry'), nulls_first=True, descending=True), 'order__code'), '-status': (OrderBy(F('last_entry'), nulls_last=True), '-order__code'), 'timestamp': (OrderBy(F('last_entry'), nulls_first=True), 'order__code'), '-timestamp': (OrderBy(F('last_entry'), nulls_last=True, descending=True), '-order__code'), 'item': ('item__name', 'variation__value', 'order__code'), '-item': ('-item__name', '-variation__value', '-order__code'), 'seat': ('seat__sorting_rank', 'seat__guid'), '-seat': ('-seat__sorting_rank', '-seat__guid'), 'date': ('subevent__date_from', 'subevent__id', 'order__code'), '-date': ('-subevent__date_from', 'subevent__id', '-order__code'), 'name': {'_order': F('display_name').asc(nulls_first=True), 'display_name': Coalesce('attendee_name_cached', 'addon_to__attendee_name_cached')}, '-name': {'_order': F('display_name').desc(nulls_last=True), 'display_name': Coalesce('attendee_name_cached', 'addon_to__attendee_name_cached')}, } user = forms.CharField( label=_('Search attendee…'), widget=forms.TextInput(attrs={ 'placeholder': _('Search attendee…'), 'autofocus': 'autofocus' }), required=False ) status = forms.ChoiceField( label=_('Check-in status'), choices=( ('', _('All attendees')), ('3', pgettext_lazy('checkin state', 'Checked in but left')), ('2', pgettext_lazy('checkin state', 'Present')), ('1', _('Checked in')), ('0', _('Not checked in')), ), required=False, ) item = forms.ModelChoiceField( label=_('Products'), queryset=Item.objects.none(), required=False, empty_label=_('All products') ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) subevent_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'Date start from'), required=False, ) subevent_until = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('subevent', 'Date start until'), required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') self.list = kwargs.pop('list') super().__init__(*args, **kwargs) if self.list.all_products: self.fields['item'].queryset = self.event.items.all() else: self.fields['item'].queryset = self.list.limit_products.all() if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices else: del self.fields['subevent'] del self.fields['subevent_from'] del self.fields['subevent_until'] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('user'): u = fdata.get('user') qs = qs.filter( Q(order__code__istartswith=u) | Q(secret__istartswith=u) | Q(pseudonymization_id__istartswith=u) | Q(order__email__icontains=u) | Q(attendee_name_cached__icontains=u) | Q(attendee_email__icontains=u) | Q(voucher__code__istartswith=u) | Q(order__invoice_address__name_cached__icontains=u) | Q(order__invoice_address__company__icontains=u) ) if fdata.get('status'): s = fdata.get('status') if s == '1': qs = qs.filter(last_entry__isnull=False) elif s == '2': qs = qs.filter(last_entry__isnull=False).filter( Q(last_exit__isnull=True) | Q(last_exit__lt=F('last_entry')) ) elif s == '3': qs = qs.filter(last_entry__isnull=False).filter( Q(last_exit__isnull=False) & Q(last_exit__gte=F('last_entry')) ) elif s == '0': qs = qs.filter(last_entry__isnull=True) if fdata.get('ordering'): ob = self.orders[fdata.get('ordering')] if isinstance(ob, dict): ob = dict(ob) o = ob.pop('_order') qs = qs.annotate(**ob).order_by(o) elif isinstance(ob, (list, tuple)): qs = qs.order_by(*ob) else: qs = qs.order_by(ob) if fdata.get('item'): qs = qs.filter(item=fdata.get('item')) if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) if fdata.get('subevent_from'): qs = qs.filter(subevent__date_from__gte=fdata.get('subevent_from')) if fdata.get('subevent_until'): qs = qs.filter(subevent__date_from__lte=fdata.get('subevent_until')) return qs class UserFilterForm(FilterForm): orders = { 'fullname': 'fullname', 'email': 'email', } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('active', _('Active')), ('inactive', _('Inactive')), ), required=False ) superuser = forms.ChoiceField( label=_('Administrator'), choices=( ('', _('All')), ('yes', _('Administrator')), ('no', _('No administrator')), ), required=False ) query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status') == 'active': qs = qs.filter(is_active=True) elif fdata.get('status') == 'inactive': qs = qs.filter(is_active=False) if fdata.get('superuser') == 'yes': qs = qs.filter(is_staff=True) elif fdata.get('superuser') == 'no': qs = qs.filter(is_staff=False) if fdata.get('query'): qs = qs.filter( Q(email__icontains=fdata.get('query')) | Q(fullname__icontains=fdata.get('query')) ) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) return qs class VoucherFilterForm(FilterForm): orders = { 'code': 'code', '-code': '-code', 'redeemed': 'redeemed', '-redeemed': '-redeemed', 'valid_until': 'valid_until', '-valid_until': '-valid_until', 'tag': 'tag', '-tag': '-tag', 'item': ( 'seat__sorting_rank', 'item__category__position', 'item__category', 'item__position', 'item__variation__position', 'quota__name', ), 'subevent': 'subevent__date_from', '-subevent': '-subevent__date_from', '-item': ( '-seat__sorting_rank', '-item__category__position', '-item__category', '-item__position', '-item__variation__position', '-quota__name', ) } status = forms.ChoiceField( label=_('Status'), choices=( ('', _('All')), ('v', _('Valid')), ('u', _('Unredeemed')), ('r', _('Redeemed at least once')), ('f', _('Fully redeemed')), ('e', _('Expired')), ('c', _('Redeemed and checked in with ticket')), ), required=False ) qm = forms.ChoiceField( label=_('Quota handling'), choices=( ('', _('All')), ('b', _('Reserve ticket from quota')), ('i', _('Allow to ignore quota')), ), required=False ) tag = forms.CharField( label=_('Filter by tag'), widget=forms.TextInput(attrs={ 'placeholder': _('Filter by tag'), }), required=False ) search = forms.CharField( label=_('Search voucher'), widget=forms.TextInput(attrs={ 'placeholder': _('Search voucher'), 'autofocus': 'autofocus' }), required=False ) subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) itemvar = forms.ChoiceField( label=_("Product"), required=False ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=i.name))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (i.name, v.value))) else: choices.append((str(i.pk), i.name)) for q in self.event.quotas.all(): choices.append(('q-%d' % q.pk, _('Any product in quota "{quota}"').format(quota=q))) self.fields['itemvar'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('search'): s = fdata.get('search').strip() qs = qs.filter(Q(code__icontains=s) | Q(tag__icontains=s) | Q(comment__icontains=s)) if fdata.get('tag'): s = fdata.get('tag').strip() if s == '<>': qs = qs.filter(Q(tag__isnull=True) | Q(tag='')) elif s[0] == '"' and s[-1] == '"': qs = qs.filter(tag__exact=s[1:-1]) else: qs = qs.filter(tag__icontains=s) if fdata.get('qm'): s = fdata.get('qm') if s == 'b': qs = qs.filter(block_quota=True) elif s == 'i': qs = qs.filter(allow_ignore_quota=True) if fdata.get('status'): s = fdata.get('status') if s == 'v': qs = qs.filter(Q(valid_until__isnull=True) | Q(valid_until__gt=now())).filter(redeemed__lt=F('max_usages')) elif s == 'r': qs = qs.filter(redeemed__gt=0) elif s == 'u': qs = qs.filter(redeemed=0) elif s == 'f': qs = qs.filter(redeemed__gte=F('max_usages')) elif s == 'e': qs = qs.filter(Q(valid_until__isnull=False) & Q(valid_until__lt=now())).filter(redeemed=0) elif s == 'c': checkins = Checkin.objects.filter( position__voucher=OuterRef('pk') ) qs = qs.annotate(has_checkin=Exists(checkins)).filter( redeemed__gt=0, has_checkin=True ) if fdata.get('itemvar'): if fdata.get('itemvar').startswith('q-'): qs = qs.filter(quota_id=fdata.get('itemvar').split('-')[1]) elif '-' in fdata.get('itemvar'): qs = qs.filter(item_id=fdata.get('itemvar').split('-')[0], variation_id=fdata.get('itemvar').split('-')[1]) else: qs = qs.filter(item_id=fdata.get('itemvar')) if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) if fdata.get('ordering'): ob = self.orders[fdata.get('ordering')] if isinstance(ob, dict): ob = dict(ob) o = ob.pop('_order') qs = qs.annotate(**ob).order_by(o) elif isinstance(ob, (list, tuple)): qs = qs.order_by(*ob) else: qs = qs.order_by(ob) return qs class VoucherTagFilterForm(FilterForm): subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('subevent'): qs = qs.filter(subevent_id=fdata.get('subevent').pk) return qs class RefundFilterForm(FilterForm): orders = {'provider': 'provider', 'state': 'state', 'order': 'order__code', 'source': 'source', 'amount': 'amount', 'created': 'created'} provider = forms.ChoiceField( label=_('Payment provider'), choices=[ ('', _('All payment providers')), ], required=False, ) status = forms.ChoiceField( label=_('Refund status'), choices=( ('', _('All open refunds')), ('all', _('All refunds')), ) + OrderRefund.REFUND_STATES, required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['provider'].choices += [(k, v.verbose_name) for k, v in self.event.get_payment_providers().items()] def filter_qs(self, qs): fdata = self.cleaned_data qs = super().filter_qs(qs) if fdata.get('provider'): qs = qs.filter(provider=fdata.get('provider')) if fdata.get('status'): if fdata.get('status') != 'all': qs = qs.filter(state=fdata.get('status')) else: qs = qs.filter(state__in=[OrderRefund.REFUND_STATE_CREATED, OrderRefund.REFUND_STATE_TRANSIT, OrderRefund.REFUND_STATE_EXTERNAL]) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-created') return qs class OverviewFilterForm(FilterForm): subevent = forms.ModelChoiceField( label=pgettext_lazy('subevent', 'Date'), queryset=SubEvent.objects.none(), required=False, empty_label=pgettext_lazy('subevent', 'All dates') ) date_axis = forms.ChoiceField( label=_('Date filter'), choices=( ('', _('Filter by…')), ('order_date', _('Order date')), ('last_payment_date', _('Date of last successful payment')), ), required=False, ) date_from = forms.DateField( label=_('Date from'), required=False, widget=DatePickerWidget, ) date_until = forms.DateField( label=_('Date until'), required=False, widget=DatePickerWidget, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) if self.event.has_subevents: self.fields['subevent'].queryset = self.event.subevents.all() self.fields['subevent'].widget = Select2( attrs={ 'data-model-select2': 'event', 'data-select2-url': reverse('control:event.subevents.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': pgettext_lazy('subevent', 'All dates') } ) self.fields['subevent'].widget.choices = self.fields['subevent'].choices elif 'subevent': del self.fields['subevent'] class CheckinFilterForm(FilterForm): status = forms.ChoiceField( label=_('Status'), choices=[ ('', _('All check-ins')), ('successful', _('Successful check-ins')), ('unsuccessful', _('Unsuccessful check-ins')), ] + list(Checkin.REASONS), required=False ) type = forms.ChoiceField( label=_('Scan type'), choices=[ ('', _('All directions')), ] + list(Checkin.CHECKIN_TYPES), required=False ) itemvar = forms.ChoiceField( label=_("Product"), required=False ) device = SafeModelChoiceField( label=_('Device'), empty_label=_('All devices'), queryset=Device.objects.none(), required=False ) gate = SafeModelChoiceField( label=_('Gate'), empty_label=_('All gates'), queryset=Gate.objects.none(), required=False ) checkin_list = SafeModelChoiceField(queryset=CheckinList.objects.none(), required=False) # overridden later datetime_from = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('filter', 'Start date'), required=False, ) datetime_until = forms.SplitDateTimeField( widget=SplitDateTimePickerWidget(attrs={ }), label=pgettext_lazy('filter', 'End date'), required=False, ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) self.fields['device'].queryset = self.event.organizer.devices.all() self.fields['gate'].queryset = self.event.organizer.gates.all() self.fields['checkin_list'].queryset = self.event.checkin_lists.all() self.fields['checkin_list'].widget = Select2( attrs={ 'data-model-select2': 'generic', 'data-select2-url': reverse('control:event.orders.checkinlists.select2', kwargs={ 'event': self.event.slug, 'organizer': self.event.organizer.slug, }), 'data-placeholder': _('Check-in list'), } ) self.fields['checkin_list'].widget.choices = self.fields['checkin_list'].choices self.fields['checkin_list'].label = _('Check-in list') choices = [('', _('All products'))] for i in self.event.items.prefetch_related('variations').all(): variations = list(i.variations.all()) if variations: choices.append((str(i.pk), _('{product} – Any variation').format(product=i.name))) for v in variations: choices.append(('%d-%d' % (i.pk, v.pk), '%s – %s' % (i.name, v.value))) else: choices.append((str(i.pk), i.name)) self.fields['itemvar'].choices = choices def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('status'): s = fdata.get('status') if s == 'successful': qs = qs.filter(successful=True) elif s == 'unsuccessful': qs = qs.filter(successful=False) elif s: qs = qs.filter(successful=False, error_reason=s) if fdata.get('type'): qs = qs.filter(type=fdata.get('type')) if fdata.get('itemvar'): if '-' in fdata.get('itemvar'): qs = qs.alias( item_id=Coalesce('raw_item_id', 'position__item_id'), variation_id=Coalesce('raw_variation_id', 'position__variation_id'), ).filter( item_id=fdata.get('itemvar').split('-')[0], variation_id=fdata.get('itemvar').split('-')[1] ) else: qs = qs.alias( item_id=Coalesce('raw_item_id', 'position__item_id'), ).filter(item_id=fdata.get('itemvar')) if fdata.get('device'): qs = qs.filter(device_id=fdata.get('device').pk) if fdata.get('gate'): qs = qs.filter(gate_id=fdata.get('gate').pk) if fdata.get('checkin_list'): qs = qs.filter(list_id=fdata.get('checkin_list').pk) if fdata.get('datetime_from'): qs = qs.filter(datetime__gte=fdata.get('datetime_from')) if fdata.get('datetime_until'): qs = qs.filter(datetime__lte=fdata.get('datetime_until')) return qs class DeviceFilterForm(FilterForm): orders = { 'name': Upper('name'), '-name': Upper('name').desc(), 'device_id': 'device_id', 'initialized': F('initialized').asc(nulls_last=True), '-initialized': F('initialized').desc(nulls_first=True), } query = forms.CharField( label=_('Search query'), widget=forms.TextInput(attrs={ 'placeholder': _('Search query'), 'autofocus': 'autofocus' }), required=False ) gate = forms.ModelChoiceField( queryset=Gate.objects.none(), label=_('Gate'), empty_label=_('All gates'), required=False, ) software_brand = forms.ChoiceField( label=_('Software'), choices=[ ('', _('All')), ], required=False, ) state = forms.ChoiceField( label=_('Device status'), choices=[ ('', _('All devices')), ('active', _('Active devices')), ('revoked', _('Revoked devices')) ], required=False ) def __init__(self, *args, **kwargs): request = kwargs.pop('request') super().__init__(*args, **kwargs) self.fields['gate'].queryset = request.organizer.gates.all() self.fields['software_brand'].choices = [ ('', _('All')), ] + [ (f['software_brand'], f['software_brand']) for f in request.organizer.devices.order_by().values('software_brand').annotate(c=Count('*')) if f['software_brand'] ] def filter_qs(self, qs): fdata = self.cleaned_data if fdata.get('query'): query = fdata.get('query') qs = qs.filter( Q(name__icontains=query) | Q(unique_serial__icontains=query) | Q(hardware_brand__icontains=query) | Q(hardware_model__icontains=query) | Q(software_brand__icontains=query) ) if fdata.get('gate'): qs = qs.filter(gate=fdata['gate']) if fdata.get('state') == 'active': qs = qs.filter(revoked=False) elif fdata.get('state') == 'revoked': qs = qs.filter(revoked=True) if fdata.get('ordering'): qs = qs.order_by(self.get_order_by()) else: qs = qs.order_by('-device_id') return qs
import torch import pandas as pd from io import BytesIO from subprocess import check_output from . import writing import time def memory(device=0): total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_mem) torch.cuda.reset_max_memory_cached() writing.max(f'gpu-memory/alloc/{device}', torch.cuda.max_memory_allocated(device)/total_mem) torch.cuda.reset_max_memory_allocated() torch.cuda.reset_max_memory_cached() def dataframe(): """Use `nvidia-smi --help-query-gpu` to get a list of query params""" params = { 'device': 'index', 'compute': 'utilization.gpu', 'access': 'utilization.memory', 'memused': 'memory.used', 'memtotal': 'memory.total', 'fan': 'fan.speed', 'power': 'power.draw', 'temp': 'temperature.gpu'} command = f"""nvidia-smi --format=csv,nounits,noheader --query-gpu={",".join(params.values())}""" df = pd.read_csv(BytesIO(check_output(command, shell=True)), header=None) df.columns = list(params.keys()) df = df.set_index('device') df = df.apply(pd.to_numeric, errors='coerce') return df _last = -1 def vitals(device=None, throttle=0): # This is a fairly expensive op, so let's avoid doing it too often global _last if time.time() - _last < throttle: return _last = time.time() df = dataframe() if device is None: pass elif isinstance(device, int): df = df.loc[[device]] else: df = df.loc[device] fields = ['compute', 'access', 'fan', 'power', 'temp'] for (device, field), value in df[fields].stack().iteritems(): writing.mean(f'gpu/{field}/{device}', value) for device in df.index: writing.mean(f'gpu/memory/{device}', 100*df.loc[device, 'memused']/df.loc[device, 'memtotal'])
import torch import pandas as pd from io import BytesIO from subprocess import check_output from . import writing import time def memory(device=0): total_mem = torch.cuda.get_device_properties(f'cuda:{device}').total_memory writing.max(f'gpu-memory/cache/{device}', torch.cuda.max_memory_cached(device)/total_mem) torch.cuda.reset_max_memory_cached() writing.max(f'gpu-memory/alloc/{device}', torch.cuda.max_memory_allocated(device)/total_mem) torch.cuda.reset_max_memory_allocated() torch.cuda.reset_max_memory_cached() def dataframe(): """Use `nvidia-smi --help-query-gpu` to get a list of query params""" params = { 'device': 'index', 'compute': 'utilization.gpu', 'access': 'utilization.memory', 'memused': 'memory.used', 'memtotal': 'memory.total', 'fan': 'fan.speed', 'power': 'power.draw', 'temp': 'temperature.gpu'} command = f"""nvidia-smi --format=csv,nounits,noheader --query-gpu={','.join(params.values())}""" df = pd.read_csv(BytesIO(check_output(command, shell=True)), header=None) df.columns = list(params.keys()) df = df.set_index('device') df = df.apply(pd.to_numeric, errors='coerce') return df _last = -1 def vitals(device=None, throttle=0): # This is a fairly expensive op, so let's avoid doing it too often global _last if time.time() - _last < throttle: return _last = time.time() df = dataframe() if device is None: pass elif isinstance(device, int): df = df.loc[[device]] else: df = df.loc[device] fields = ['compute', 'access', 'fan', 'power', 'temp'] for (device, field), value in df[fields].stack().iteritems(): writing.mean(f'gpu/{field}/{device}', value) for device in df.index: writing.mean(f'gpu/memory/{device}', 100*df.loc[device, 'memused']/df.loc[device, 'memtotal'])