import copy
import re
from collections import Counter as CollectionCounter, defaultdict, deque
from collections.abc import Callable, Hashable as CollectionsHashable, Iterable as CollectionsIterable
from typing import (
    TYPE_CHECKING,
    Any,
    Counter,
    DefaultDict,
    Deque,
    Dict,
    ForwardRef,
    FrozenSet,
    Generator,
    Iterable,
    Iterator,
    List,
    Mapping,
    Optional,
    Pattern,
    Sequence,
    Set,
    Tuple,
    Type,
    TypeVar,
    Union,
)

from pipenv.patched.pip._vendor.typing_extensions import Annotated, Final

from . import errors as errors_
from .class_validators import Validator, make_generic_validator, prep_validators
from .error_wrappers import ErrorWrapper
from .errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError
from .types import Json, JsonWrapper
from .typing import (
    NoArgAnyCallable,
    convert_generics,
    display_as_type,
    get_args,
    get_origin,
    is_finalvar,
    is_literal_type,
    is_new_type,
    is_none_type,
    is_typeddict,
    is_typeddict_special,
    is_union,
    new_type_supertype,
)
from .utils import (
    PyObjectStr,
    Representation,
    ValueItems,
    get_discriminator_alias_and_values,
    get_unique_discriminator_alias,
    lenient_isinstance,
    lenient_issubclass,
    sequence_like,
    smart_deepcopy,
)
from .validators import constant_validator, dict_validator, find_validators, validate_json

Required: Any = Ellipsis

T = TypeVar('T')

class UndefinedType:
    def __repr__(self) -> str:
        return 'PydanticUndefined'

    def __copy__(self: T) -> T:
        return self

    def __reduce__(self) -> str:
        return 'Undefined'

    def __deepcopy__(self: T, _: Any) -> T:
        return self

Undefined = UndefinedType()

if TYPE_CHECKING:
    from .class_validators import ValidatorsList
    from .config import BaseConfig
    from .error_wrappers import ErrorList
    from .types import ModelOrDc
    from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs

    ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]]
    LocStr = Union[Tuple[Union[int, str], ...], str]
    BoolUndefined = Union[bool, UndefinedType]

class FieldInfo(Representation):
    """
    Captures extra information about a field.
    """

    __slots__ = (
        'default',
        'default_factory',
        'alias',
        'alias_priority',
        'title',
        'description',
        'exclude',
        'include',
        'const',
        'gt',
        'ge',
        'lt',
        'le',
        'multiple_of',
        'allow_inf_nan',
        'max_digits',
        'decimal_places',
        'min_items',
        'max_items',
        'unique_items',
        'min_length',
        'max_length',
        'allow_mutation',
        'repr',
        'regex',
        'discriminator',
        'extra',
    )

    # field constraints with the default value, it's also used in update_from_config below
    __field_constraints__ = {
        'min_length': None,
        'max_length': None,
        'regex': None,
        'gt': None,
        'lt': None,
        'ge': None,
        'le': None,
        'multiple_of': None,
        'allow_inf_nan': None,
        'max_digits': None,
        'decimal_places': None,
        'min_items': None,
        'max_items': None,
        'unique_items': None,
        'allow_mutation': True,
    }

    def __init__(self, default: Any = Undefined, **kwargs: Any) -> None:
        self.default = default
        self.default_factory = kwargs.pop('default_factory', None)
        self.alias = kwargs.pop('alias', None)
        self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias is not None else None)
        self.title = kwargs.pop('title', None)
        self.description = kwargs.pop('description', None)
        self.exclude = kwargs.pop('exclude', None)
        self.include = kwargs.pop('include', None)
        self.const = kwargs.pop('const', None)
        self.gt = kwargs.pop('gt', None)
        self.ge = kwargs.pop('ge', None)
        self.lt = kwargs.pop('lt', None)
        self.le = kwargs.pop('le', None)
        self.multiple_of = kwargs.pop('multiple_of', None)
        self.allow_inf_nan = kwargs.pop('allow_inf_nan', None)
        self.max_digits = kwargs.pop('max_digits', None)
        self.decimal_places = kwargs.pop('decimal_places', None)
        self.min_items = kwargs.pop('min_items', None)
        self.max_items = kwargs.pop('max_items', None)
        self.unique_items = kwargs.pop('unique_items', None)
        self.min_length = kwargs.pop('min_length', None)
        self.max_length = kwargs.pop('max_length', None)
        self.allow_mutation = kwargs.pop('allow_mutation', True)
        self.regex = kwargs.pop('regex', None)
        self.discriminator = kwargs.pop('discriminator', None)
        self.repr = kwargs.pop('repr', True)
        self.extra = kwargs

    def __repr_args__(self) -> 'ReprArgs':

        field_defaults_to_hide: Dict[str, Any] = {
            'repr': True,
            **self.__field_constraints__,
        }

        attrs = ((s, getattr(self, s)) for s in self.__slots__)
        return [(a, v) for a, v in attrs if v != field_defaults_to_hide.get(a, None)]

    def get_constraints(self) -> Set[str]:
        """
        Gets the constraints set on the field by comparing the constraint value with its default value

        :return: the constraints set on field_info
        """
        return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default}

    def update_from_config(self, from_config: Dict[str, Any]) -> None:
        """
        Update this FieldInfo based on a dict from get_field_info, only fields which have not been set are dated.
        """
        for attr_name, value in from_config.items():
            try:
                current_value = getattr(self, attr_name)
            except AttributeError:
                # attr_name is not an attribute of FieldInfo, it should therefore be added to extra
                # (except if extra already has this value!)
                self.extra.setdefault(attr_name, value)
            else:
                if current_value is self.__field_constraints__.get(attr_name, None):
                    setattr(self, attr_name, value)
                elif attr_name == 'exclude':
                    self.exclude = ValueItems.merge(value, current_value)
                elif attr_name == 'include':
                    self.include = ValueItems.merge(value, current_value, intersect=True)

    def _validate(self) -> None:
        if self.default is not Undefined and self.default_factory is not None:
            raise ValueError('cannot specify both default and default_factory')

def Field(
    default: Any = Undefined,
    *,
    default_factory: Optional[NoArgAnyCallable] = None,
    alias: Optional[str] = None,
    title: Optional[str] = None,
    description: Optional[str] = None,
    exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny', Any]] = None,
    include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny', Any]] = None,
    const: Optional[bool] = None,
    gt: Optional[float] = None,
    ge: Optional[float] = None,
    lt: Optional[float] = None,
    le: Optional[float] = None,
    multiple_of: Optional[float] = None,
    allow_inf_nan: Optional[bool] = None,
    max_digits: Optional[int] = None,
    decimal_places: Optional[int] = None,
    min_items: Optional[int] = None,
    max_items: Optional[int] = None,
    unique_items: Optional[bool] = None,
    min_length: Optional[int] = None,
    max_length: Optional[int] = None,
    allow_mutation: bool = True,
    regex: Optional[str] = None,
    discriminator: Optional[str] = None,
    repr: bool = True,
    **extra: Any,
) -> Any:
    """
    Used to provide extra information about a field, either for the model schema or complex validation. Some arguments
    apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str``.

    :param default: since this is replacing the field’s default, its first argument is used
      to set the default, use ellipsis (``...``) to indicate the field is required
    :param default_factory: callable that will be called when a default value is needed for this field
      If both `default` and `default_factory` are set, an error is raised.
    :param alias: the public name of the field
    :param title: can be any string, used in the schema
    :param description: can be any string, used in the schema
    :param exclude: exclude this field while dumping.
      Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method.
    :param include: include this field while dumping.
      Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method.
    :param const: this field is required and *must* take it's default value
    :param gt: only applies to numbers, requires the field to be "greater than". The schema
      will have an ``exclusiveMinimum`` validation keyword
    :param ge: only applies to numbers, requires the field to be "greater than or equal to". The
      schema will have a ``minimum`` validation keyword
    :param lt: only applies to numbers, requires the field to be "less than". The schema
      will have an ``exclusiveMaximum`` validation keyword
    :param le: only applies to numbers, requires the field to be "less than or equal to". The
      schema will have a ``maximum`` validation keyword
    :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The
      schema will have a ``multipleOf`` validation keyword
    :param allow_inf_nan: only applies to numbers, allows the field to be NaN or infinity (+inf or -inf),
        which is a valid Python float. Default True, set to False for compatibility with JSON.
    :param max_digits: only applies to Decimals, requires the field to have a maximum number
      of digits within the decimal. It does not include a zero before the decimal point or trailing decimal zeroes.
    :param decimal_places: only applies to Decimals, requires the field to have at most a number of decimal places
      allowed. It does not include trailing decimal zeroes.
    :param min_items: only applies to lists, requires the field to have a minimum number of
      elements. The schema will have a ``minItems`` validation keyword
    :param max_items: only applies to lists, requires the field to have a maximum number of
      elements. The schema will have a ``maxItems`` validation keyword
    :param unique_items: only applies to lists, requires the field not to have duplicated
      elements. The schema will have a ``uniqueItems`` validation keyword
    :param min_length: only applies to strings, requires the field to have a minimum length. The
      schema will have a ``minLength`` validation keyword
    :param max_length: only applies to strings, requires the field to have a maximum length. The
      schema will have a ``maxLength`` validation keyword
    :param allow_mutation: a boolean which defaults to True. When False, the field raises a TypeError if the field is
      assigned on an instance.  The BaseModel Config must set validate_assignment to True
    :param regex: only applies to strings, requires the field match against a regular expression
      pattern string. The schema will have a ``pattern`` validation keyword
    :param discriminator: only useful with a (discriminated a.k.a. tagged) `Union` of sub models with a common field.
      The `discriminator` is the name of this common field to shorten validation and improve generated schema
    :param repr: show this field in the representation
    :param **extra: any additional keyword arguments will be added as is to the schema
    """
    field_info = FieldInfo(
        default,
        default_factory=default_factory,
        alias=alias,
        title=title,
        description=description,
        exclude=exclude,
        include=include,
        const=const,
        gt=gt,
        ge=ge,
        lt=lt,
        le=le,
        multiple_of=multiple_of,
        allow_inf_nan=allow_inf_nan,
        max_digits=max_digits,
        decimal_places=decimal_places,
        min_items=min_items,
        max_items=max_items,
        unique_items=unique_items,
        min_length=min_length,
        max_length=max_length,
        allow_mutation=allow_mutation,
        regex=regex,
        discriminator=discriminator,
        repr=repr,
        **extra,
    )
    field_info._validate()
    return field_info

# used to be an enum but changed to int's for small performance improvement as less access overhead
SHAPE_SINGLETON = 1
SHAPE_LIST = 2
SHAPE_SET = 3
SHAPE_MAPPING = 4
SHAPE_TUPLE = 5
SHAPE_TUPLE_ELLIPSIS = 6
SHAPE_SEQUENCE = 7
SHAPE_FROZENSET = 8
SHAPE_ITERABLE = 9
SHAPE_GENERIC = 10
SHAPE_DEQUE = 11
SHAPE_DICT = 12
SHAPE_DEFAULTDICT = 13
SHAPE_COUNTER = 14
SHAPE_NAME_LOOKUP = {
    SHAPE_LIST: 'List[{}]',
    SHAPE_SET: 'Set[{}]',
    SHAPE_TUPLE_ELLIPSIS: 'Tuple[{}, ...]',
    SHAPE_SEQUENCE: 'Sequence[{}]',
    SHAPE_FROZENSET: 'FrozenSet[{}]',
    SHAPE_ITERABLE: 'Iterable[{}]',
    SHAPE_DEQUE: 'Deque[{}]',
    SHAPE_DICT: 'Dict[{}]',
    SHAPE_DEFAULTDICT: 'DefaultDict[{}]',
    SHAPE_COUNTER: 'Counter[{}]',
}

MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER}

class ModelField(Representation):
    __slots__ = (
        'type_',
        'outer_type_',
        'annotation',
        'sub_fields',
        'sub_fields_mapping',
        'key_field',
        'validators',
        'pre_validators',
        'post_validators',
        'default',
        'default_factory',
        'required',
        'final',
        'model_config',
        'name',
        'alias',
        'has_alias',
        'field_info',
        'discriminator_key',
        'discriminator_alias',
        'validate_always',
        'allow_none',
        'shape',
        'class_validators',
        'parse_json',
    )

    def __init__(
        self,
        *,
        name: str,
        type_: Type[Any],
        class_validators: Optional[Dict[str, Validator]],
        model_config: Type['BaseConfig'],
        default: Any = None,
        default_factory: Optional[NoArgAnyCallable] = None,
        required: 'BoolUndefined' = Undefined,
        final: bool = False,
        alias: Optional[str] = None,
        field_info: Optional[FieldInfo] = None,
    ) -> None:

        self.name: str = name
        self.has_alias: bool = alias is not None
        self.alias: str = alias if alias is not None else name
        self.annotation = type_
        self.type_: Any = convert_generics(type_)
        self.outer_type_: Any = type_
        self.class_validators = class_validators or {}
        self.default: Any = default
        self.default_factory: Optional[NoArgAnyCallable] = default_factory
        self.required: 'BoolUndefined' = required
        self.final: bool = final
        self.model_config = model_config
        self.field_info: FieldInfo = field_info or FieldInfo(default)
        self.discriminator_key: Optional[str] = self.field_info.discriminator
        self.discriminator_alias: Optional[str] = self.discriminator_key

        self.allow_none: bool = False
        self.validate_always: bool = False
        self.sub_fields: Optional[List[ModelField]] = None
        self.sub_fields_mapping: Optional[Dict[str, 'ModelField']] = None  # used for discriminated union
        self.key_field: Optional[ModelField] = None
        self.validators: 'ValidatorsList' = []
        self.pre_validators: Optional['ValidatorsList'] = None
        self.post_validators: Optional['ValidatorsList'] = None
        self.parse_json: bool = False
        self.shape: int = SHAPE_SINGLETON
        self.model_config.prepare_field(self)
        self.prepare()

    def get_default(self) -> Any:
        return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()

    @staticmethod
    def _get_field_info(
        field_name: str, annotation: Any, value: Any, config: Type['BaseConfig']
    ) -> Tuple[FieldInfo, Any]:
        """
        Get a FieldInfo from a root typing.Annotated annotation, value, or config default.

        The FieldInfo may be set in typing.Annotated or the value, but not both. If neither contain
        a FieldInfo, a new one will be created using the config.

        :param field_name: name of the field for use in error messages
        :param annotation: a type hint such as `str` or `Annotated[str, Field(..., min_length=5)]`
        :param value: the field's assigned value
        :param config: the model's config object
        :return: the FieldInfo contained in the `annotation`, the value, or a new one from the config.
        """
        field_info_from_config = config.get_field_info(field_name)

        field_info = None
        if get_origin(annotation) is Annotated:
            field_infos = [arg for arg in get_args(annotation)[1:] if isinstance(arg, FieldInfo)]
            if len(field_infos) > 1:
                raise ValueError(f'cannot specify multiple `Annotated` `Field`s for {field_name!r}')
            field_info = next(iter(field_infos), None)
            if field_info is not None:
                field_info = copy.copy(field_info)
                field_info.update_from_config(field_info_from_config)
                if field_info.default not in (Undefined, Required):
                    raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}')
                if value is not Undefined and value is not Required:
                    # check also `Required` because of `validate_arguments` that sets `...` as default value
                    field_info.default = value

        if isinstance(value, FieldInfo):
            if field_info is not None:
                raise ValueError(f'cannot specify `Annotated` and value `Field`s together for {field_name!r}')
            field_info = value
            field_info.update_from_config(field_info_from_config)
        elif field_info is None:
            field_info = FieldInfo(value, **field_info_from_config)
        value = None if field_info.default_factory is not None else field_info.default
        field_info._validate()
        return field_info, value

    @classmethod
    def infer(
        cls,
        *,
        name: str,
        value: Any,
        annotation: Any,
        class_validators: Optional[Dict[str, Validator]],
        config: Type['BaseConfig'],
    ) -> 'ModelField':
        from .schema import get_annotation_from_field_info

        field_info, value = cls._get_field_info(name, annotation, value, config)
        required: 'BoolUndefined' = Undefined
        if value is Required:
            required = True
            value = None
        elif value is not Undefined:
            required = False
        annotation = get_annotation_from_field_info(annotation, field_info, name, config.validate_assignment)

        return cls(
            name=name,
            type_=annotation,
            alias=field_info.alias,
            class_validators=class_validators,
            default=value,
            default_factory=field_info.default_factory,
            required=required,
            model_config=config,
            field_info=field_info,
        )

    def set_config(self, config: Type['BaseConfig']) -> None:
        self.model_config = config
        info_from_config = config.get_field_info(self.name)
        config.prepare_field(self)
        new_alias = info_from_config.get('alias')
        new_alias_priority = info_from_config.get('alias_priority') or 0
        if new_alias and new_alias_priority >= (self.field_info.alias_priority or 0):
            self.field_info.alias = new_alias
            self.field_info.alias_priority = new_alias_priority
            self.alias = new_alias
        new_exclude = info_from_config.get('exclude')
        if new_exclude is not None:
            self.field_info.exclude = ValueItems.merge(self.field_info.exclude, new_exclude)
        new_include = info_from_config.get('include')
        if new_include is not None:
            self.field_info.include = ValueItems.merge(self.field_info.include, new_include, intersect=True)

    @property
    def alt_alias(self) -> bool:
        return self.name != self.alias

    def prepare(self) -> None:
        """
        Prepare the field but inspecting self.default, self.type_ etc.

        Note: this method is **not** idempotent (because _type_analysis is not idempotent),
        e.g. calling it it multiple times may modify the field and configure it incorrectly.
        """
        self._set_default_and_type()
        if self.type_.__class__ is ForwardRef or self.type_.__class__ is DeferredType:
            # self.type_ is currently a ForwardRef and there's nothing we can do now,
            # user will need to call model.update_forward_refs()
            return

        self._type_analysis()
        if self.required is Undefined:
            self.required = True
        if self.default is Undefined and self.default_factory is None:
            self.default = None
        self.populate_validators()

    def _set_default_and_type(self) -> None:
        """
        Set the default value, infer the type if needed and check if `None` value is valid.
        """
        if self.default_factory is not None:
            if self.type_ is Undefined:
                raise errors_.ConfigError(
                    f'you need to set the type of field {self.name!r} when using `default_factory`'
                )
            return

        default_value = self.get_default()

        if default_value is not None and self.type_ is Undefined:
            self.type_ = default_value.__class__
            self.outer_type_ = self.type_
            self.annotation = self.type_

        if self.type_ is Undefined:
            raise errors_.ConfigError(f'unable to infer type for attribute "{self.name}"')

        if self.required is False and default_value is None:
            self.allow_none = True

    def _type_analysis(self) -> None:  # noqa: C901 (ignore complexity)
        # typing interface is horrible, we have to do some ugly checks
        if lenient_issubclass(self.type_, JsonWrapper):
            self.type_ = self.type_.inner_type
            self.parse_json = True
        elif lenient_issubclass(self.type_, Json):
            self.type_ = Any
            self.parse_json = True
        elif isinstance(self.type_, TypeVar):
            if self.type_.__bound__:
                self.type_ = self.type_.__bound__
            elif self.type_.__constraints__:
                self.type_ = Union[self.type_.__constraints__]
            else:
                self.type_ = Any
        elif is_new_type(self.type_):
            self.type_ = new_type_supertype(self.type_)

        if self.type_ is Any or self.type_ is object:
            if self.required is Undefined:
                self.required = False
            self.allow_none = True
            return
        elif self.type_ is Pattern or self.type_ is re.Pattern:
            # python 3.7 only, Pattern is a typing object but without sub fields
            return
        elif is_literal_type(self.type_):
            return
        elif is_typeddict(self.type_):
            return

        if is_finalvar(self.type_):
            self.final = True

            if self.type_ is Final:
                self.type_ = Any
            else:
                self.type_ = get_args(self.type_)[0]

            self._type_analysis()
            return

        origin = get_origin(self.type_)

        if origin is Annotated or is_typeddict_special(origin):
            self.type_ = get_args(self.type_)[0]
            self._type_analysis()
            return

        if self.discriminator_key is not None and not is_union(origin):
            raise TypeError('`discriminator` can only be used with `Union` type with more than one variant')

        # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None`
        if origin is None or origin is CollectionsHashable:
            # field is not "typing" object eg. Union, Dict, List etc.
            # allow None for virtual superclasses of NoneType, e.g. Hashable
            if isinstance(self.type_, type) and isinstance(None, self.type_):
                self.allow_none = True
            return
        elif origin is Callable:
            return
        elif is_union(origin):
            types_ = []
            for type_ in get_args(self.type_):
                if is_none_type(type_) or type_ is Any or type_ is object:
                    if self.required is Undefined:
                        self.required = False
                    self.allow_none = True
                if is_none_type(type_):
                    continue
                types_.append(type_)

            if len(types_) == 1:
                # Optional[]
                self.type_ = types_[0]
                # this is the one case where the "outer type" isn't just the original type
                self.outer_type_ = self.type_
                # re-run to correctly interpret the new self.type_
                self._type_analysis()
            else:
                self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_]

                if self.discriminator_key is not None:
                    self.prepare_discriminated_union_sub_fields()
            return
        elif issubclass(origin, Tuple):  # type: ignore
            # origin == Tuple without item type
            args = get_args(self.type_)
            if not args:  # plain tuple
                self.type_ = Any
                self.shape = SHAPE_TUPLE_ELLIPSIS
            elif len(args) == 2 and args[1] is Ellipsis:  # e.g. Tuple[int, ...]
                self.type_ = args[0]
                self.shape = SHAPE_TUPLE_ELLIPSIS
                self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')]
            elif args == ((),):  # Tuple[()] means empty tuple
                self.shape = SHAPE_TUPLE
                self.type_ = Any
                self.sub_fields = []
            else:
                self.shape = SHAPE_TUPLE
                self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)]
            return
        elif issubclass(origin, List):
            # Create self validators
            get_validators = getattr(self.type_, '__get_validators__', None)
            if get_validators:
                self.class_validators.update(
                    {f'list_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
                )

            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_LIST
        elif issubclass(origin, Set):
            # Create self validators
            get_validators = getattr(self.type_, '__get_validators__', None)
            if get_validators:
                self.class_validators.update(
                    {f'set_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
                )

            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_SET
        elif issubclass(origin, FrozenSet):
            # Create self validators
            get_validators = getattr(self.type_, '__get_validators__', None)
            if get_validators:
                self.class_validators.update(
                    {f'frozenset_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())}
                )

            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_FROZENSET
        elif issubclass(origin, Deque):
            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_DEQUE
        elif issubclass(origin, Sequence):
            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_SEQUENCE
        # priority to most common mapping: dict
        elif origin is dict or origin is Dict:
            self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
            self.type_ = get_args(self.type_)[1]
            self.shape = SHAPE_DICT
        elif issubclass(origin, DefaultDict):
            self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
            self.type_ = get_args(self.type_)[1]
            self.shape = SHAPE_DEFAULTDICT
        elif issubclass(origin, Counter):
            self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
            self.type_ = int
            self.shape = SHAPE_COUNTER
        elif issubclass(origin, Mapping):
            self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True)
            self.type_ = get_args(self.type_)[1]
            self.shape = SHAPE_MAPPING
        # Equality check as almost everything inherits form Iterable, including str
        # check for Iterable and CollectionsIterable, as it could receive one even when declared with the other
        elif origin in {Iterable, CollectionsIterable}:
            self.type_ = get_args(self.type_)[0]
            self.shape = SHAPE_ITERABLE
            self.sub_fields = [self._create_sub_type(self.type_, f'{self.name}_type')]
        elif issubclass(origin, Type):  # type: ignore
            return
        elif hasattr(origin, '__get_validators__') or self.model_config.arbitrary_types_allowed:
            # Is a Pydantic-compatible generic that handles itself
            # or we have arbitrary_types_allowed = True
            self.shape = SHAPE_GENERIC
            self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(get_args(self.type_))]
            self.type_ = origin
            return
        else:
            raise TypeError(f'Fields of type "{origin}" are not supported.')

        # type_ has been refined eg. as the type of a List and sub_fields needs to be populated
        self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)]

    def prepare_discriminated_union_sub_fields(self) -> None:
        """
        Prepare the mapping <discriminator key> -> <ModelField> and update `sub_fields`
        Note that this process can be aborted if a `ForwardRef` is encountered
        """
        assert self.discriminator_key is not None

        if self.type_.__class__ is DeferredType:
            return

        assert self.sub_fields is not None
        sub_fields_mapping: Dict[str, 'ModelField'] = {}
        all_aliases: Set[str] = set()

        for sub_field in self.sub_fields:
            t = sub_field.type_
            if t.__class__ is ForwardRef:
                # Stopping everything...will need to call `update_forward_refs`
                return

            alias, discriminator_values = get_discriminator_alias_and_values(t, self.discriminator_key)
            all_aliases.add(alias)
            for discriminator_value in discriminator_values:
                sub_fields_mapping[discriminator_value] = sub_field

        self.sub_fields_mapping = sub_fields_mapping
        self.discriminator_alias = get_unique_discriminator_alias(all_aliases, self.discriminator_key)

    def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField':
        if for_keys:
            class_validators = None
        else:
            # validators for sub items should not have `each_item` as we want to check only the first sublevel
            class_validators = {
                k: Validator(
                    func=v.func,
                    pre=v.pre,
                    each_item=False,
                    always=v.always,
                    check_fields=v.check_fields,
                    skip_on_failure=v.skip_on_failure,
                )
                for k, v in self.class_validators.items()
                if v.each_item
            }

        field_info, _ = self._get_field_info(name, type_, None, self.model_config)

        return self.__class__(
            type_=type_,
            name=name,
            class_validators=class_validators,
            model_config=self.model_config,
            field_info=field_info,
        )

    def populate_validators(self) -> None:
        """
        Prepare self.pre_validators, self.validators, and self.post_validators based on self.type_'s  __get_validators__
        and class validators. This method should be idempotent, e.g. it should be safe to call multiple times
        without mis-configuring the field.
        """
        self.validate_always = getattr(self.type_, 'validate_always', False) or any(
            v.always for v in self.class_validators.values()
        )

        class_validators_ = self.class_validators.values()
        if not self.sub_fields or self.shape == SHAPE_GENERIC:
            get_validators = getattr(self.type_, '__get_validators__', None)
            v_funcs = (
                *[v.func for v in class_validators_ if v.each_item and v.pre],
                *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))),
                *[v.func for v in class_validators_ if v.each_item and not v.pre],
            )
            self.validators = prep_validators(v_funcs)

        self.pre_validators = []
        self.post_validators = []

        if self.field_info and self.field_info.const:
            self.post_validators.append(make_generic_validator(constant_validator))

        if class_validators_:
            self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre)
            self.post_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and not v.pre)

        if self.parse_json:
            self.pre_validators.append(make_generic_validator(validate_json))

        self.pre_validators = self.pre_validators or None
        self.post_validators = self.post_validators or None

    def validate(
        self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None
    ) -> 'ValidateReturn':

        assert self.type_.__class__ is not DeferredType

        if self.type_.__class__ is ForwardRef:
            assert cls is not None
            raise ConfigError(
                f'field "{self.name}" not yet prepared so type is still a ForwardRef, '
                f'you might need to call {cls.__name__}.update_forward_refs().'
            )

        errors: Optional['ErrorList']
        if self.pre_validators:
            v, errors = self._apply_validators(v, values, loc, cls, self.pre_validators)
            if errors:
                return v, errors

        if v is None:
            if is_none_type(self.type_):
                # keep validating
                pass
            elif self.allow_none:
                if self.post_validators:
                    return self._apply_validators(v, values, loc, cls, self.post_validators)
                else:
                    return None, None
            else:
                return v, ErrorWrapper(NoneIsNotAllowedError(), loc)

        if self.shape == SHAPE_SINGLETON:
            v, errors = self._validate_singleton(v, values, loc, cls)
        elif self.shape in MAPPING_LIKE_SHAPES:
            v, errors = self._validate_mapping_like(v, values, loc, cls)
        elif self.shape == SHAPE_TUPLE:
            v, errors = self._validate_tuple(v, values, loc, cls)
        elif self.shape == SHAPE_ITERABLE:
            v, errors = self._validate_iterable(v, values, loc, cls)
        elif self.shape == SHAPE_GENERIC:
            v, errors = self._apply_validators(v, values, loc, cls, self.validators)
        else:
            #  sequence, list, set, generator, tuple with ellipsis, frozen set
            v, errors = self._validate_sequence_like(v, values, loc, cls)

        if not errors and self.post_validators:
            v, errors = self._apply_validators(v, values, loc, cls, self.post_validators)
        return v, errors

    def _validate_sequence_like(  # noqa: C901 (ignore complexity)
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        """
        Validate sequence-like containers: lists, tuples, sets and generators
        Note that large if-else blocks are necessary to enable Cython
        optimization, which is why we disable the complexity check above.
        """
        if not sequence_like(v):
            e: errors_.PydanticTypeError
            if self.shape == SHAPE_LIST:
                e = errors_.ListError()
            elif self.shape in (SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS):
                e = errors_.TupleError()
            elif self.shape == SHAPE_SET:
                e = errors_.SetError()
            elif self.shape == SHAPE_FROZENSET:
                e = errors_.FrozenSetError()
            else:
                e = errors_.SequenceError()
            return v, ErrorWrapper(e, loc)

        loc = loc if isinstance(loc, tuple) else (loc,)
        result = []
        errors: List[ErrorList] = []
        for i, v_ in enumerate(v):
            v_loc = *loc, i
            r, ee = self._validate_singleton(v_, values, v_loc, cls)
            if ee:
                errors.append(ee)
            else:
                result.append(r)

        if errors:
            return v, errors

        converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any], Deque[Any]] = result

        if self.shape == SHAPE_SET:
            converted = set(result)
        elif self.shape == SHAPE_FROZENSET:
            converted = frozenset(result)
        elif self.shape == SHAPE_TUPLE_ELLIPSIS:
            converted = tuple(result)
        elif self.shape == SHAPE_DEQUE:
            converted = deque(result, maxlen=getattr(v, 'maxlen', None))
        elif self.shape == SHAPE_SEQUENCE:
            if isinstance(v, tuple):
                converted = tuple(result)
            elif isinstance(v, set):
                converted = set(result)
            elif isinstance(v, Generator):
                converted = iter(result)
            elif isinstance(v, deque):
                converted = deque(result, maxlen=getattr(v, 'maxlen', None))
        return converted, None

    def _validate_iterable(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        """
        Validate Iterables.

        This intentionally doesn't validate values to allow infinite generators.
        """

        try:
            iterable = iter(v)
        except TypeError:
            return v, ErrorWrapper(errors_.IterableError(), loc)
        return iterable, None

    def _validate_tuple(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        e: Optional[Exception] = None
        if not sequence_like(v):
            e = errors_.TupleError()
        else:
            actual_length, expected_length = len(v), len(self.sub_fields)  # type: ignore
            if actual_length != expected_length:
                e = errors_.TupleLengthError(actual_length=actual_length, expected_length=expected_length)

        if e:
            return v, ErrorWrapper(e, loc)

        loc = loc if isinstance(loc, tuple) else (loc,)
        result = []
        errors: List[ErrorList] = []
        for i, (v_, field) in enumerate(zip(v, self.sub_fields)):  # type: ignore
            v_loc = *loc, i
            r, ee = field.validate(v_, values, loc=v_loc, cls=cls)
            if ee:
                errors.append(ee)
            else:
                result.append(r)

        if errors:
            return v, errors
        else:
            return tuple(result), None

    def _validate_mapping_like(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        try:
            v_iter = dict_validator(v)
        except TypeError as exc:
            return v, ErrorWrapper(exc, loc)

        loc = loc if isinstance(loc, tuple) else (loc,)
        result, errors = {}, []
        for k, v_ in v_iter.items():
            v_loc = *loc, '__key__'
            key_result, key_errors = self.key_field.validate(k, values, loc=v_loc, cls=cls)  # type: ignore
            if key_errors:
                errors.append(key_errors)
                continue

            v_loc = *loc, k
            value_result, value_errors = self._validate_singleton(v_, values, v_loc, cls)
            if value_errors:
                errors.append(value_errors)
                continue

            result[key_result] = value_result
        if errors:
            return v, errors
        elif self.shape == SHAPE_DICT:
            return result, None
        elif self.shape == SHAPE_DEFAULTDICT:
            return defaultdict(self.type_, result), None
        elif self.shape == SHAPE_COUNTER:
            return CollectionCounter(result), None
        else:
            return self._get_mapping_value(v, result), None

    def _get_mapping_value(self, original: T, converted: Dict[Any, Any]) -> Union[T, Dict[Any, Any]]:
        """
        When type is `Mapping[KT, KV]` (or another unsupported mapping), we try to avoid
        coercing to `dict` unwillingly.
        """
        original_cls = original.__class__

        if original_cls == dict or original_cls == Dict:
            return converted
        elif original_cls in {defaultdict, DefaultDict}:
            return defaultdict(self.type_, converted)
        else:
            try:
                # Counter, OrderedDict, UserDict, ...
                return original_cls(converted)  # type: ignore
            except TypeError:
                raise RuntimeError(f'Could not convert dictionary to {original_cls.__name__!r}') from None

    def _validate_singleton(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        if self.sub_fields:
            if self.discriminator_key is not None:
                return self._validate_discriminated_union(v, values, loc, cls)

            errors = []

            if self.model_config.smart_union and is_union(get_origin(self.type_)):
                # 1st pass: check if the value is an exact instance of one of the Union types
                # (e.g. to avoid coercing a bool into an int)
                for field in self.sub_fields:
                    if v.__class__ is field.outer_type_:
                        return v, None

                # 2nd pass: check if the value is an instance of any subclass of the Union types
                for field in self.sub_fields:
                    # This whole logic will be improved later on to support more complex `isinstance` checks
                    # It will probably be done once a strict mode is added and be something like:
                    # ```
                    #     value, error = field.validate(v, values, strict=True)
                    #     if error is None:
                    #         return value, None
                    # ```
                    try:
                        if isinstance(v, field.outer_type_):
                            return v, None
                    except TypeError:
                        # compound type
                        if lenient_isinstance(v, get_origin(field.outer_type_)):
                            value, error = field.validate(v, values, loc=loc, cls=cls)
                            if not error:
                                return value, None

            # 1st pass by default or 3rd pass with `smart_union` enabled:
            # check if the value can be coerced into one of the Union types
            for field in self.sub_fields:
                value, error = field.validate(v, values, loc=loc, cls=cls)
                if error:
                    errors.append(error)
                else:
                    return value, None
            return v, errors
        else:
            return self._apply_validators(v, values, loc, cls, self.validators)

    def _validate_discriminated_union(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc']
    ) -> 'ValidateReturn':
        assert self.discriminator_key is not None
        assert self.discriminator_alias is not None

        try:
            try:
                discriminator_value = v[self.discriminator_alias]
            except KeyError:
                if self.model_config.allow_population_by_field_name:
                    discriminator_value = v[self.discriminator_key]
                else:
                    raise
        except KeyError:
            return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc)
        except TypeError:
            try:
                # BaseModel or dataclass
                discriminator_value = getattr(v, self.discriminator_key)
            except (AttributeError, TypeError):
                return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc)

        if self.sub_fields_mapping is None:
            assert cls is not None
            raise ConfigError(
                f'field "{self.name}" not yet prepared so type is still a ForwardRef, '
                f'you might need to call {cls.__name__}.update_forward_refs().'
            )

        try:
            sub_field = self.sub_fields_mapping[discriminator_value]
        except (KeyError, TypeError):
            # KeyError: `discriminator_value` is not in the dictionary.
            # TypeError: `discriminator_value` is unhashable.
            assert self.sub_fields_mapping is not None
            return v, ErrorWrapper(
                InvalidDiscriminator(
                    discriminator_key=self.discriminator_key,
                    discriminator_value=discriminator_value,
                    allowed_values=list(self.sub_fields_mapping),
                ),
                loc,
            )
        else:
            if not isinstance(loc, tuple):
                loc = (loc,)
            return sub_field.validate(v, values, loc=(*loc, display_as_type(sub_field.type_)), cls=cls)

    def _apply_validators(
        self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'], validators: 'ValidatorsList'
    ) -> 'ValidateReturn':
        for validator in validators:
            try:
                v = validator(cls, v, values, self, self.model_config)
            except (ValueError, TypeError, AssertionError) as exc:
                return v, ErrorWrapper(exc, loc)
        return v, None

    def is_complex(self) -> bool:
        """
        Whether the field is "complex" eg. env variables should be parsed as JSON.
        """
        from .main import BaseModel

        return (
            self.shape != SHAPE_SINGLETON
            or hasattr(self.type_, '__pydantic_model__')
            or lenient_issubclass(self.type_, (BaseModel, list, set, frozenset, dict))
        )

    def _type_display(self) -> PyObjectStr:
        t = display_as_type(self.type_)

        if self.shape in MAPPING_LIKE_SHAPES:
            t = f'Mapping[{display_as_type(self.key_field.type_)}, {t}]'  # type: ignore
        elif self.shape == SHAPE_TUPLE:
            t = 'Tuple[{}]'.format(', '.join(display_as_type(f.type_) for f in self.sub_fields))  # type: ignore
        elif self.shape == SHAPE_GENERIC:
            assert self.sub_fields
            t = '{}[{}]'.format(
                display_as_type(self.type_), ', '.join(display_as_type(f.type_) for f in self.sub_fields)
            )
        elif self.shape != SHAPE_SINGLETON:
            t = SHAPE_NAME_LOOKUP[self.shape].format(t)

        if self.allow_none and (self.shape != SHAPE_SINGLETON or not self.sub_fields):
            t = f'Optional[{t}]'
        return PyObjectStr(t)

    def __repr_args__(self) -> 'ReprArgs':
        args = [('name', self.name), ('type', self._type_display()), ('required', self.required)]

        if not self.required:
            if self.default_factory is not None:
                args.append(('default_factory', f'<function {self.default_factory.__name__}>'))
            else:
                args.append(('default', self.default))

        if self.alt_alias:
            args.append(('alias', self.alias))
        return args

class ModelPrivateAttr(Representation):
    __slots__ = ('default', 'default_factory')

    def __init__(self, default: Any = Undefined, *, default_factory: Optional[NoArgAnyCallable] = None) -> None:
        self.default = default
        self.default_factory = default_factory

    def get_default(self) -> Any:
        return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory()

    def __eq__(self, other: Any) -> bool:
        return isinstance(other, self.__class__) and (self.default, self.default_factory) == (
            other.default,
            other.default_factory,
        )

def PrivateAttr(
    default: Any = Undefined,
    *,
    default_factory: Optional[NoArgAnyCallable] = None,
) -> Any:
    """
    Indicates that attribute is only used internally and never mixed with regular fields.

    Types or values of private attrs are not checked by pydantic and it's up to you to keep them relevant.

    Private attrs are stored in model __slots__.

    :param default: the attribute’s default value
    :param default_factory: callable that will be called when a default value is needed for this attribute
      If both `default` and `default_factory` are set, an error is raised.
    """
    if default is not Undefined and default_factory is not None:
        raise ValueError('cannot specify both default and default_factory')

    return ModelPrivateAttr(
        default,
        default_factory=default_factory,
    )

class DeferredType:
    """
    Used to postpone field preparation, while creating recursive generic models.
    """

def is_finalvar_with_default_val(type_: Type[Any], val: Any) -> bool:
    return is_finalvar(type_) and val is not Undefined and not isinstance(val, FieldInfo)


#!/usr/bin/env python3
import logging
from threading import Thread
from time import sleep
from serial import Serial
from ublox import StreamMuxDemux, UBXSerializer, StreamMuxDemuxError
from pyubx2.ubxreader import UBXReader

log = logging.getLogger('rover')
REPLUG_WAIT_TIME = 3

def rtcm_handler(rtcm_stream):
    xbee_stream = None
    while True:
        try:
            xbee_stream = Serial("/dev/xbee", 115200, timeout=5)
            while True:
                byte = xbee_stream.read()
                rtcm_stream.write(byte)

        except StreamMuxDemuxError as e:
            log.error(e)
            rtcm_stream.owner.close()
            return

        except Exception as e:
            log.error(e)
            if xbee_stream:
                xbee_stream.close()
            sleep(REPLUG_WAIT_TIME)

def nmea_handler(nmea_stream):
    bluetooth_stream = None
    while True:
        try:
            bluetooth_stream = Serial('/dev/rfcomm0', 115200, timeout=5)
            while True:
                byte = nmea_stream.read()
                bluetooth_stream.write(byte)

        except StreamMuxDemuxError as e:
            log.error(e)
            nmea_stream.owner.close()
            return

        except Exception as e:
            log.error(e)
            if bluetooth_stream:
                bluetooth_stream.close()
            sleep(REPLUG_WAIT_TIME)

def ubx_handler(ubx_stream):
    while True:
        try:
            ubr = UBXReader(ubx_stream)
            raw, msg = ubr.read()
            log.info(msg)

        except StreamMuxDemuxError as e:
            log.error(e)
            ubx_stream.owner.close()
            return

        # TODO: except parse errors

        except Exception as e:
            log.error(e)
            # sleep(REPLUG_WAIT_TIME)

def main():
    # connect to serial port
    PORT = "/dev/gps-uart1"
    BAUDRATE = 460800
    TIMEOUT = 5
    log.info(f'Connecting to serial port {PORT}')
    original_stream = Serial(PORT, BAUDRATE, timeout=TIMEOUT)

    # split serial stream into a stream for each protocol
    log.info(f'Splitting serial stream into a stream for each protocol')
    streams = StreamMuxDemux(original_stream)

    # load configuration
    CONFIG_FILE = open("./config/rover.yml", "r")
    log.info(f'Loading configuration from {CONFIG_FILE}')
    config = UBXSerializer.serialize(CONFIG_FILE)
    streams.UBX.write(config)
    # TODO: verify ubx answer

    # run UBX thread
    log.info(f'Creating a thread for handling UBX')
    ubx_thread = Thread(target=ubx_handler, daemon=True, args=[streams.UBX])
    ubx_thread.start()

    # run RTCM thread
    log.info(f'Creating a thread for handling RTCM')
    rtcm_thread = Thread(target=rtcm_handler, daemon=True, args=[streams.RTCM])
    rtcm_thread.start()

    # run NMEA thread
    log.info(f'Creating a thread for handling NMEA')
    nmea_thread = Thread(target=nmea_handler, daemon=True, args=[streams.NMEA])
    nmea_thread.start()

    # cleanup
    ubx_thread.join()
    rtcm_thread.join()
    nmea_thread.join()
    streams.close()
    original_stream.close()

if __name__ == '__main__':
    logging.basicConfig(format="%(levelname)s:%(name)s:%(asctime)s:  %(message)s", level=logging.DEBUG)

    while True:
        try:
            main()
        except Exception as e:
            log.error(e)
        sleep(REPLUG_WAIT_TIME)


""" Core definition of a Molecule Document """
from typing import Any, Dict, List, Mapping, Union

from pydantic import Field

from pymatgen.core.structure import Molecule
from pymatgen.analysis.molecule_matcher import MoleculeMatcher

from emmet.core.mpid import MPID
from emmet.core.settings import EmmetSettings
from emmet.core.material import MoleculeDoc as CoreMoleculeDoc
from emmet.core.material import PropertyOrigin
from emmet.core.structure import MoleculeMetadata
from emmet.core.qchem.calc_types import CalcType, LevelOfTheory, TaskType
from emmet.core.qchem.task import TaskDocument

__author__ = "Evan Spotte-Smith <ewcspottesmith@lbl.gov>"

SETTINGS = EmmetSettings()

def evaluate_lot(
    lot: Union[LevelOfTheory, str],
    funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES,
    basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES,
    solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES,
):
    """
    Score the various components of a level of theory (functional, basis set,
    and solvent model), where a lower score is better than a higher score.

    :param lot: Level of theory to be evaluated
    :param funct_scores: Scores for various density functionals
    :param basis_scores: Scores for various basis sets
    :param solvent_scores: Scores for various implicit solvent models
    :return:
    """

    if isinstance(lot, LevelOfTheory):
        lot_comp = lot.value.split("/")
    else:
        lot_comp = lot.split("/")

    return (
        -1 * funct_scores.get(lot_comp[0], 0),
        -1 * basis_scores.get(lot_comp[1], 0),
        -1 * solvent_scores.get(lot_comp[2].split("(")[0], 0),
    )

def evaluate_task(
    task: TaskDocument,
    funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES,
    basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES,
    solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES,
    task_quality_scores: Dict[str, int] = SETTINGS.QCHEM_TASK_QUALITY_SCORES,
):
    """
    Helper function to order optimization calcs by
    - Level of theory
    - Electronic energy

    Note that lower scores indicate a higher quality.

    :param task: Task to be evaluated
    :param funct_scores: Scores for various density functionals
    :param basis_scores: Scores for various basis sets
    :param solvent_scores: Scores for various implicit solvent models
    :param task_quality_scores: Scores for various task types
    :return:
    """

    lot = task.level_of_theory

    lot_eval = evaluate_lot(
        lot,
        funct_scores=funct_scores,
        basis_scores=basis_scores,
        solvent_scores=solvent_scores,
    )

    return (
        -1 * int(task.is_valid),
        sum(lot_eval),
        -1 * task_quality_scores.get(task.task_type.value, 0),
        task.output.final_energy,
    )

class MoleculeDoc(CoreMoleculeDoc, MoleculeMetadata):

    calc_types: Mapping[str, CalcType] = Field(  # type: ignore
        None,
        description="Calculation types for all the calculations that make up this molecule",
    )
    task_types: Mapping[str, TaskType] = Field(
        None,
        description="Task types for all the calculations that make up this molecule",
    )
    levels_of_theory: Mapping[str, LevelOfTheory] = Field(
        None,
        description="Levels of theory types for all the calculations that make up this material",
    )

    origins: List[PropertyOrigin] = Field(
        None,
        description="List of property origins for tracking the provenance of properties",
    )

    entries: List[Dict[str, Any]] = Field(
        None,
        description="Dictionary representations of all task documents for this molecule",
    )

    best_entries: Mapping[LevelOfTheory, Dict[str, Any]] = Field(
        None,
        description="Mapping for tracking the best entries at each level of theory for Q-Chem calculations",
    )

    similar_molecules: List[MPID] = Field(
        None,
        description="List of MPIDs with of molecules similar (by e.g. structure) to this one",
    )

    @classmethod
    def from_tasks(
        cls,
        task_group: List[TaskDocument],
    ) -> "MoleculeDoc":

        """
        Converts a group of tasks into one molecule document

        Args:
            task_group: List of task document
        """
        if len(task_group) == 0:
            raise Exception("Must have more than one task in the group.")

        entries = [t.entry for t in task_group]

        # Metadata
        last_updated = max(task.last_updated for task in task_group)
        created_at = min(task.last_updated for task in task_group)
        task_ids = list({task.task_id for task in task_group})

        deprecated_tasks = {task.task_id for task in task_group if not task.is_valid}
        levels_of_theory = {task.task_id: task.level_of_theory for task in task_group}
        task_types = {task.task_id: task.task_type for task in task_group}
        calc_types = {task.task_id: task.calc_type for task in task_group}

        mols = [task.output.initial_molecule for task in task_group]

        # If we're dealing with single-atoms, process is much different
        if all([len(m) == 1 for m in mols]):
            sorted_tasks = sorted(task_group, key=evaluate_task)

            molecule_id = sorted_tasks[0].task_id

            molecule = sorted_tasks[0].output.initial_molecule

            # Initial molecules. No geometry should change for a single atom
            initial_molecules = [molecule]

            # Deprecated
            deprecated = all(task.task_id in deprecated_tasks for task in task_group)

            # Origins
            origins = [
                PropertyOrigin(
                    name="molecule",
                    task_id=molecule_id,
                    last_updated=sorted_tasks[0].last_updated,
                )
            ]

            # entries
            best_entries = {}
            all_lots = set(levels_of_theory.values())
            for lot in all_lots:
                relevant_calcs = sorted(
                    [doc for doc in task_group if doc.level_of_theory == lot and doc.is_valid],
                    key=evaluate_task,
                )

                if len(relevant_calcs) > 0:
                    best_task_doc = relevant_calcs[0]
                    entry = best_task_doc.entry
                    entry["task_id"] = entry["entry_id"]
                    entry["entry_id"] = molecule_id
                    best_entries[lot] = entry

        else:
            geometry_optimizations = [
                task
                for task in task_group
                if task.task_type
                in [TaskType.Geometry_Optimization, TaskType.Frequency_Flattening_Geometry_Optimization]  # noqa: E501
            ]

            # Molecule ID
            possible_mol_ids = [task.task_id for task in geometry_optimizations]

            molecule_id = min(possible_mol_ids)

            best_molecule_calc = sorted(geometry_optimizations, key=evaluate_task)[0]
            molecule = best_molecule_calc.output.optimized_molecule

            # Initial molecules
            initial_molecules = list()
            for task in task_group:
                if isinstance(task.orig["molecule"], Molecule):
                    initial_molecules.append(task.orig["molecule"])
                else:
                    initial_molecules.append(Molecule.from_dict(task.orig["molecule"]))

            mm = MoleculeMatcher()
            initial_molecules = [group[0] for group in mm.group_molecules(initial_molecules)]

            # Deprecated
            deprecated = all(task.task_id in deprecated_tasks for task in geometry_optimizations)
            deprecated = deprecated or best_molecule_calc.task_id in deprecated_tasks

            # Origins
            origins = [
                PropertyOrigin(
                    name="molecule",
                    task_id=best_molecule_calc.task_id,
                    last_updated=best_molecule_calc.last_updated,
                )
            ]

            # entries
            best_entries = {}
            all_lots = set(levels_of_theory.values())
            for lot in all_lots:
                relevant_calcs = sorted(
                    [doc for doc in geometry_optimizations if doc.level_of_theory == lot and doc.is_valid],
                    key=evaluate_task,
                )

                if len(relevant_calcs) > 0:
                    best_task_doc = relevant_calcs[0]
                    entry = best_task_doc.entry
                    best_entries[lot] = entry

        for entry in entries:
            entry["entry_id"] = molecule_id

        return cls.from_molecule(
            molecule=molecule,
            molecule_id=molecule_id,
            initial_molecules=initial_molecules,
            last_updated=last_updated,
            created_at=created_at,
            task_ids=task_ids,
            calc_types=calc_types,
            levels_of_theory=levels_of_theory,
            task_types=task_types,
            deprecated=deprecated,
            deprecated_tasks=deprecated_tasks,
            origins=origins,
            entries=entries,
            best_entries=best_entries,
        )

    @classmethod
    def construct_deprecated_molecule(
        cls,
        task_group: List[TaskDocument],
    ) -> "MoleculeDoc":
        """
        Converts a group of tasks into a deprecated molecule document

        Args:
            task_group: List of task document
        """
        if len(task_group) == 0:
            raise Exception("Must have more than one task in the group.")

        # Metadata
        last_updated = max(task.last_updated for task in task_group)
        created_at = min(task.last_updated for task in task_group)
        task_ids = list({task.task_id for task in task_group})

        deprecated_tasks = {task.task_id for task in task_group}
        levels_of_theory = {task.task_id: task.level_of_theory for task in task_group}
        task_types = {task.task_id: task.task_type for task in task_group}
        calc_types = {task.task_id: task.calc_type for task in task_group}

        # Molecule ID
        molecule_id = min([task.task_id for task in task_group])

        # Choose any random structure for metadata
        molecule = task_group[0].output.initial_molecule

        # Deprecated
        deprecated = True

        return cls.from_molecule(
            molecule=molecule,
            molecule_id=molecule_id,
            last_updated=last_updated,
            created_at=created_at,
            task_ids=task_ids,
            calc_types=calc_types,
            levels_of_theory=levels_of_theory,
            task_types=task_types,
            deprecated=deprecated,
            deprecated_tasks=deprecated_tasks,
        )

def best_lot(
    mol_doc: MoleculeDoc,
    funct_scores: Dict[str, int] = SETTINGS.QCHEM_FUNCTIONAL_QUALITY_SCORES,
    basis_scores: Dict[str, int] = SETTINGS.QCHEM_BASIS_QUALITY_SCORES,
    solvent_scores: Dict[str, int] = SETTINGS.QCHEM_SOLVENT_MODEL_QUALITY_SCORES,
) -> LevelOfTheory:
    """

    Return the best level of theory used within a MoleculeDoc

    :param mol_doc: MoleculeDoc
    :param funct_scores: Scores for various density functionals
    :param basis_scores: Scores for various basis sets
    :param solvent_scores: Scores for various implicit solvent models

    :return: LevelOfTheory
    """

    sorted_lots = sorted(
        mol_doc.best_entries.keys(),
        key=lambda x: evaluate_lot(x, funct_scores, basis_scores, solvent_scores),
    )

    return sorted_lots[0]


try:
    import requests
except Exception as e:
    print(e)
url = input('Enter Url to display robots.txt:- ')+'/robots.txt'
try:
    response = requests.get(url)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(e)
except requests.exceptions.ConnectionError:
    print('Server Not Found')
else:
    text = response.text
print(f'Robots.txt for {url}\n ----------------------------------------- \n{text}')


import telebot
from telebot import types
import pandas as pd
import math
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

bot = telebot.TeleBot('***')
df = pd.read_csv('Final_joined.csv')

def haversine(lat1, lon1, lat2, lon2):
    lat1 = math.radians(lat1)
    lon1 = math.radians(lon1)
    lat2 = math.radians(lat2)
    lon2 = math.radians(lon2)
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    distance = 6371.01 * c  # Earth's radius in kilometers
    return distance

def calc_distances(current_lat, current_lon, places_df, lat_column, lon_column, name_column):
    nearest_place = None
    places_df['distance'] = None
    for index, row in places_df.iterrows():
        place_name = row[name_column]
        place_lat = row[lat_column]
        place_lon = row[lon_column]
        distance = haversine(current_lat, current_lon, place_lat, place_lon)
        places_df.loc[index, 'distance'] = distance
    return places_df

users = {}

@bot.message_handler(commands=['start'])
def start(message):
    user_id = message.chat.id

    # Отправляем инструкцию по использованию бота
    instructions = "Давайте начнем!\nИнструкция по использованию бота.\n\n" \
                   "1. Команда для начала поиска - /poisk\n" \
                   "2. Отправьте мне ваше местоположение, чтобы я мог найти ближайшие заправки.\n" \
                   "3. Выберите ваш регион.\n" \
                   "4. Выберите вид топлива.\n" \
                   "5. Я покажу вам ближайшие заправки и их геопозиции.\n"
    bot.send_message(user_id, instructions)
    logger.info(f'User {user_id} started interaction with the bot')

@bot.message_handler(commands=['guide'])
def guide(message):
    user_id = message.chat.id

    # Отправляем инструкцию по использованию бота
    instructions = "Как пользоваться ботом?\n\n" \
                   "1. Команда для начала поиска - /poisk\n" \
                   "2. Отправьте мне ваше местоположение, чтобы я мог найти ближайшие заправки.\n" \
                   "3. Выберите ваш регион.\n" \
                   "4. Выберите вид топлива.\n" \
                   "5. Я покажу вам ближайшие заправки и их геопозиции.\n"
    bot.send_message(user_id, instructions)
    logger.info(f'User {user_id} started interaction with the bot')

@bot.message_handler(commands=['poisk'])
def poisk(message):
    user_id = message.chat.id
    if user_id not in users:
        users[user_id] = {
            'lat': None,
            'long': None,
            'region': None,
            'fuel': None,
            'fuel_type': None,
            'zapravka': None,
            'page': 0
        }
        logger.info(f'New user registered with user_id={user_id}')

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    location_button = types.KeyboardButton("Отправить местоположение", request_location=True)
    markup.add(location_button)

    bot.send_message(user_id, "Чтобы найти ближайшие заправки, нажмите кнопку ниже:", reply_markup=markup)
    logger.info(f'User {user_id} started interaction with the bot')

@bot.callback_query_handler(func=lambda call: call.data == "send_location")
def send_location(call):
    user_id = call.message.chat.id
    bot.send_message(user_id, "Отправьте ваше местоположение, чтобы найти ближайшие заправки.",
                     reply_markup=types.ReplyKeyboardRemove(selective=True))
    bot.send_location(user_id, latitude=0.0, longitude=0.0)  # Это пример координат

@bot.message_handler(content_types=['location'])
def handle_location(message):
    user_id = message.chat.id
    users[user_id]['lat'] = message.location.latitude
    users[user_id]['long'] = message.location.longitude
    region_buttons = [
        telebot.types.InlineKeyboardButton(title, callback_data=title)
        for title in df['REGION'].unique()
    ]
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(*region_buttons)
    bot.send_message(user_id, 'Выберите ваш регион:', reply_markup=markup)
    logger.info(f'User {user_id} sent their location')

@bot.callback_query_handler(func=lambda call: call.data in df['NEFTEPRODUKT_VID'].unique())
def choose_fuel_type(call):
    user_id = call.message.chat.id
    users[user_id]['fuel_type'] = call.data
    df_filter = df[
        (df['NEFTEPRODUKT_NAME'] == users[user_id]['fuel']) &
        (df['NEFTEPRODUKT_VID'] == users[user_id]['fuel_type']) &
        (df['REGION'] == users[user_id]['region']) &
        (df['PROC'] > 0.30)
    ]
    new_df = calc_distances(users[user_id]['lat'], users[user_id]['long'], df_filter, 'Latitude', 'Longitude', 'AZS')
    new_df = new_df[['AZS', 'Address', 'Latitude', 'Longitude', 'distance']].sort_values('distance', ascending=True)
    users[user_id]['zapravka'] = new_df.to_dict('records')
    users[user_id]['page'] = 0

    send_next_page(user_id)

def send_next_page(user_id):
    start_idx = users[user_id]['page'] * 5
    end_idx = start_idx + 5
    zapravki = users[user_id]['zapravka'][start_idx:end_idx]

    output = f"Ваш выбор: {users[user_id]['fuel_type']} {users[user_id]['fuel']}\n\nБлижайшие заправки:\n"

    for x in zapravki:
        output += f"{x['AZS']}\n{x['Address']}\nДистанция в км: {round(x['distance'], 1)}\n\n"

    markup = telebot.types.InlineKeyboardMarkup()
    if end_idx < len(users[user_id]['zapravka']):
        markup.add(telebot.types.InlineKeyboardButton(text="Показать следующие 5 заправок", callback_data="next_page"))

    for x in zapravki:
        bot.send_venue(user_id, x['Latitude'], x['Longitude'], x['AZS'], x['Address'])

    bot.send_message(user_id, output, parse_mode='Markdown', reply_markup=markup)

@bot.callback_query_handler(func=lambda call: call.data == "next_page")
def show_next_page(call):
    user_id = call.message.chat.id
    users[user_id]['page'] += 1
    send_next_page(user_id)

@bot.callback_query_handler(func=lambda call: call.data in df[df['REGION'] == users[call.message.chat.id]['region']]['NEFTEPRODUKT_NAME'].unique())
def choose_fuel(call):
    user_id = call.message.chat.id  # Получаем user_id из call.message
    users[user_id]['fuel'] = call.data
    fuel_buttons = [
        telebot.types.InlineKeyboardButton(title, callback_data=title)
        for title in df[(df['REGION'] == users[user_id]['region']) & (df['NEFTEPRODUKT_NAME'] == users[user_id]['fuel'])]['NEFTEPRODUKT_VID'].unique()
    ]
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(*fuel_buttons)
    bot.edit_message_text('Выберите вид топлива: \n 📛 Продажа топлива регулируется АЗС!', user_id, call.message.message_id, reply_markup=markup)
    logger.info(f'User {user_id} chose fuel: {call.data}')

@bot.callback_query_handler(func=lambda call: call.data in df['REGION'].unique())
def choose_region(call):
    user_id = call.message.chat.id
    users[user_id]['region'] = call.data
    fuel_buttons = [
        telebot.types.InlineKeyboardButton(title, callback_data=title)
        for title in df[df['REGION'] == users[user_id]['region']]['NEFTEPRODUKT_NAME'].unique()
    ]
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(*fuel_buttons)
    bot.edit_message_text('Выберите вид топлива: \n 📛 Продажа топлива регулируется АЗС!', user_id, call.message.message_id, reply_markup=markup)
    logger.info(f'User {user_id} chose region: {call.data}')

bot.polling()


import cv2
import os
import serial
import time

smallsize = 15000
mediumsize = 30000
bigsize = 45000

# your Serial port should be different!
arduino = serial.Serial('COM9', 115200)
#cam = serial.Serial('COM1',115200)

def captureCircle():
    size = 0
    #sleep for a the time to capture image
    time.sleep(7)
    #
    items = os.listdir('c:\out')
    num2 = 0
    for name in items:
        num, tmp = name.split(".bmp")
        num = int(num)
        num = max(num, num2)
        num2 = num

    img = cv2.imread("C:/out/"+str(num2)+".bmp")

    cb=0
    cw=0
    xx=img.shape[0]
    yy=img.shape[1]
    for i in range(0,xx):
        for j in range(0,yy):
            if img[i,j,2]< 50:
                cb+=1
            if img[i,j,2]>100:
                cw+=1
    print("Black : ",cb," White : ",cw)
    if cb > bigsize:
        size = 1
    elif cb > mediumsize:
        size = 2
    elif cb > smallsize:
        size = 3
    return str(size)

while True:
    a = input()
    arduino.write(a.encode())
    if(a == "q"):
        break
    print("size of cb ",captureCircle())


from prompt_toolkit import PromptSession

if __name__ == '__main__':
    session = PromptSession()

    # You can use the up arrow to enter the same text twice
    text1 = session.prompt('Text1: ')
    text2 = session.prompt('Text2: ')

    print(f'{text1} | {text2}')


# python Thread not real parallel running -- python use GIL - 'Global in Lock' (CPython only) strategy
from threading import Thread
import time
import cv2
import numpy as np
import face_recognition
import pickle

print(cv2.__version__)

with open('/home/xj/Desktop/pyPro/faceRecognizer/train.pkl','rb') as f:
    Names = pickle.load(f)
    Encodings = pickle.load(f)

class vStream:
    # resize camera
    # launch camera
    # capture frame
    # show frame
    def __init__(self,src,width,height):
        self.width = width
        self.height = height
        self.capture = cv2.VideoCapture(src)
        self.thread = Thread(target = self.update, args=())
        self.thread.daemon = True  # when kill the program also kill the thread
        self.thread.start()
    def update(self):
        while True:
            _,self.frame = self.capture.read()
            self.frame2 = cv2.resize(self.frame,(self.width,self.height))
    def getFrame(self):
        return self.frame2

# if 2nd camera is Raspi-Camera
# flip = 2
dispW = 640
dispH = 480
# camSet='nvarguscamerasrc !  video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method='+str(flip)+' ! video/x-raw, width='+str(dispW)+', height='+str(dispH)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'

cam1 = vStream(0,dispW,dispH)
cam2 = vStream(1,dispW,dispH)
# cam2 = vStream(camSet)

font = cv2.FONT_HERSHEY_SIMPLEX
startTime = time.time()
dtav = 0 # dt average

scaleFactor = .2
while True:
    try:
        myFrame1 = cam1.getFrame()
        myFrame2 = cam2.getFrame()
        # print(cam2.getFrame())
        myFrame3 = np.hstack((myFrame1,myFrame2))

        frameRGB = cv2.cvtColor(myFrame3,cv2.COLOR_BGR2RGB)
        frameRGBsmall = cv2.resize(frameRGB,(0,0),fx=scaleFactor,fy = scaleFactor)
        facePositions = face_recognition.face_locations(frameRGBsmall, model = 'cnn')
        allEncodings = face_recognition.face_encodings(frameRGBsmall, facePositions)
        for (top,right,bottom,left), face_encoding in zip(facePositions, allEncodings):
            name = 'unkonw person'
            matches = face_recognition.compare_faces(Encodings, face_encoding, tolerance=.38)
            if True in matches:
                first_match_index = matches.index(True)
                name = Names[first_match_index]
                print(name)
            top = int(top/scaleFactor)
            left = int(left/scaleFactor)
            right = int(right/scaleFactor)
            bottom = int(bottom/scaleFactor)
            cv2.rectangel(myFrame3, (left,top),(right,bottom),(0,0,255),-1)
            cv2.putText(myFrame3,name,(left,top-6),font,.75,(0,0,255),2)

        dt = time.time()-startTime
        startTime = time.time()
        dtav = .9*dtav + .1*dt
        fps = 1 / dtav  # maybe we are not grap that fast, but loop such fast, that's why the fps looks so big value
        # print(fps)
        cv2.rectangle(myFrame3,(0,0),(140,40),(0,0,255),-1)
        cv2.putText(myFrame3,str(round(fps,1))+'fps:',(0,25),font, .75, (0,255,255),1)
        cv2.imshow('Combo', myFrame3)
        cv2.moveWindow('Combo',0,0)

    except:
        print('frame not available')

    if cv2.waitKey(1) == ord('q'):
        cam1.capture.release()
        cam2.capture.release()
        cv2.destroyAllWindows()
        exit(1)  # help to get out the thread
        break


import json
from typing import Tuple

from nonebot import get_loaded_plugins

from . import asset, render_by_browser, util

_help_assets_path = asset.get_assets_path('help')
_plugin_metadatas: list[dict[str, str]] = []
_help_text: str | None = None
_help_image: bytes | None = None

async def generate_help_message(with_image: bool = True) -> Tuple[str, bytes | None]:
    global _plugin_metadatas, _help_text, _help_image
    # 获取所有插件信息
    if not _plugin_metadatas:
        for plugin in get_loaded_plugins():
            if plugin.metadata:
                _plugin_metadatas.append({
                    'name': plugin.metadata.name,
                    'description': plugin.metadata.description,
                    'usage': plugin.metadata.usage
                })
    # 文本帮助信息
    if _help_text is None:
        _help_text = util.MESSAGE_SPLIT_LINE
        for plugin in _plugin_metadatas:
            _help_text += f'{plugin["name"]}:\n' \
                          f'描述:\n{plugin["description"]}\n' \
                          f'用法:\n{plugin["usage"]}\n' + \
                          util.MESSAGE_SPLIT_LINE + '\n'
        _help_text = _help_text.strip()
    # 图片帮助信息
    if with_image and _help_image is None:
        with (_help_assets_path / 'template.html').open(encoding='utf-8') as f:
            html = f.read()
        _help_image = await render_by_browser.render_html(
            html.replace("'{{DATA_HERE}}'", json.dumps(_plugin_metadatas, ensure_ascii=False)),
            _help_assets_path, viewport={'width': 1000, 'height': 1000})
    # 按需返回
    if with_image:
        return _help_text, _help_image
    return _help_text, None


# -*- coding: utf-8 -*-

from cachorro import cachorro
from ovelha import ovelha
from lobo import lobo
import pygame
from random import randint
from threading import Thread, Lock
from ThreadComRetorno import ThreadComRetorno
from buraco import buraco

x = 400
y = 300
speed = 10
timer = 0
tempo_segundo = 0
mutex = Lock()

pygame.init()

#Criação dos elementos do jogo -> Ovelhas, Lobos, elementos de cenário e outros
fundo = pygame.image.load('FUNDO.png')
cachorro1 = cachorro.spawn_dog(x,y,3)
tarefalobo = ThreadComRetorno(target = lobo.spawn_lobo, args = [1,150,4])
tarefalobo.start()
lobo1 = tarefalobo.join()
tarefalobo = ThreadComRetorno(target = lobo.spawn_lobo, args = [1,300,3])
tarefalobo.start()
lobo2 = tarefalobo.join()
tarefalobo = ThreadComRetorno(target = lobo.spawn_lobo, args = [1,450,3])
tarefalobo.start()
lobo3 = tarefalobo.join()
tarefalobo = ThreadComRetorno(target = lobo.spawn_lobo, args = [1,randint(150,450),10])
tarefalobo.start()
lobo4 = tarefalobo.join()
lobo4.tamanho_x, lobo4.tamanho_y = 90,90
lobo4.status = False

buraco1 = buraco( randint(100, 720) ,randint(150, 500))
buraco1.status = False

ovelha1 = ovelha.spawn_ovelha(620,530,4)
ovelha2 = ovelha.spawn_ovelha(360,530,3)
ovelha3 = ovelha.spawn_ovelha(140,530,1)

window = pygame.display.set_mode((800,600))
som_ponto = pygame.mixer.Sound('ponto.wav')

#criação dos elementos de texto - Score e Tempo
font = pygame.font.SysFont('arial black', 11)
texto = font.render(" Tempo: ", True, (0,0,0))
pos_texto = texto.get_rect()
pos_texto.center= (35,35)
Score = 0

fontScore = pygame.font.SysFont('arial black', 11)
textoScore = font.render(" Score ", True, (0,0,0))
pos_textoScore = textoScore.get_rect()
pos_textoScore.center= (30,50)

open_window = True
listaBuracos = []

while open_window:
    pygame.time.delay(50)

    for event in pygame.event.get():
        #Fechar a janela pelo "X" no canto superior
        if event.type == pygame.QUIT:
            open_window = False
    #recebe uma entrada do teclado

    comand = pygame.key.get_pressed()

    if comand[pygame.K_w]:
        movimentaCachorro = Thread(target = cachorro.dog_up, args =[speed, cachorro1])
        movimentaCachorro.start()

    if comand[pygame.K_s]:
        movimentaCachorro = Thread(target = cachorro.dog_down, args =[speed, cachorro1])
        movimentaCachorro.start()

    if comand[pygame.K_a]:
        movimentaCachorro = Thread(target = cachorro.dog_left, args =[speed, cachorro1])
        movimentaCachorro.start()
    if comand[pygame.K_d]:
        movimentaCachorro = Thread(target = cachorro.dog_right, args =[speed, cachorro1])
        movimentaCachorro.start()

    #Define a limitação de posição das ovelhas -> Se chegarem à 100, aumenta-se o score
    if ovelha1.pos_y>100:
        movimento_ovelha = Thread(target = ovelha.sheep_up, args = [ovelha1.velocidade,ovelha1])
        movimento_ovelha.start()

    else:
        som_ponto.play();
        Score+=1
        ovelha1 = ovelha.spawn_ovelha(620,530,2)

    if ovelha2.pos_y>100:
        movimento_ovelha2 = Thread(target = ovelha.sheep_up, args = [ovelha2.velocidade,ovelha2])
        movimento_ovelha2.start()
    else:
        som_ponto.play();
        Score+=1
        ovelha2 = ovelha.spawn_ovelha(360,530,3)

    if ovelha3.pos_y>100:
        movimento_ovelha3 = Thread(target = ovelha.sheep_up, args = [ovelha3.velocidade,ovelha3])
        movimento_ovelha3.start()

    else:
        som_ponto.play();
        Score+=1
        ovelha3 = ovelha.spawn_ovelha(140,530,1)

# Limita as posições dos lobos
    if (((lobo1.sentido == 0) and (lobo1.pos_x>=0 and lobo1.pos_x<=770))):
        movimentaLobo1 = Thread(target = lobo.wolf_right, args =[lobo1.velocidade, lobo1])
        movimentaLobo1.start()
        lobo1.sentido = 0
    elif lobo1.pos_x>0:
        movimentaLobo1 = Thread(target = lobo.wolf_left, args =[lobo1.velocidade, lobo1])
        movimentaLobo1.start()
        lobo1.sentido = 1
    else:
        movimentaLobo1 = Thread(target = lobo.wolf_right, args =[lobo1.velocidade, lobo1])
        movimentaLobo1.start()
        lobo1.sentido = 0

    if (((lobo2.sentido == 0) and (lobo2.pos_x>=0 and lobo2.pos_x<=770))):
        movimentaLobo2 = Thread(target = lobo.wolf_right, args =[lobo2.velocidade, lobo2])
        movimentaLobo2.start()
        lobo2.sentido = 0
    elif lobo2.pos_x>0:
        movimentaLobo2 = Thread(target = lobo.wolf_left, args =[lobo2.velocidade, lobo2])
        movimentaLobo2.start()
        lobo2.sentido = 1
    else:
        movimentaLobo2 = Thread(target = lobo.wolf_right, args =[lobo2.velocidade, lobo2])
        movimentaLobo2.start()
        lobo2.sentido = 0
    if (((lobo3.sentido == 0) and (lobo3.pos_x>=0 and lobo3.pos_x<=770))):
        movimentaLobo3 = Thread(target = lobo.wolf_right, args =[lobo3.velocidade, lobo3])
        movimentaLobo3.start()
        lobo3.sentido = 0
    elif lobo3.pos_x>0:
        movimentaLobo3 = Thread(target = lobo.wolf_left, args =[lobo3.velocidade, lobo3])
        movimentaLobo3.start()
        lobo3.sentido = 1
    else:
        movimentaLobo3 = Thread(target = lobo.wolf_left, args =[lobo3.velocidade, lobo3])
        movimentaLobo3.start()
        lobo3.sentido = 0

    if (((lobo4.sentido == 0) and (lobo4.pos_x>=0 and lobo4.pos_x<=770))):
        movimentaLobo4 = Thread(target = lobo.wolf_right, args =[lobo4.velocidade, lobo4])
        movimentaLobo4.start()
        lobo4.sentido = 0
    elif lobo4.pos_x>0:
        movimentaLobo4 = Thread(target = lobo.wolf_left, args =[lobo4.velocidade, lobo4])
        movimentaLobo4.start()
        lobo4.sentido = 1
    else:
        movimentaLobo4 = Thread(target = lobo.wolf_right, args =[lobo4.velocidade, lobo4])
        movimentaLobo4.start()
        lobo4.sentido = 0

    if (timer <20):
        timer +=1

    else:
        tempo_segundo += 1
        textoScore = font.render(" Score:"+str(Score), True, (0,0,0))
        texto = font.render(" Tempo:"+str(tempo_segundo), True, (0,0,0))
        timer = 0

    window.fill((0,0,0))
    window.blit(fundo, (0,0))
    window.blit(textoScore, pos_textoScore)
    window.blit(texto,pos_texto)

    #Limita a posição do cachorro
    if cachorro1.pos_x<=0:
        cachorro1.pos_x = 5
    if cachorro1.pos_x>=790:
        cachorro1.pos_x = 790
    if cachorro1.pos_y>=590:
        cachorro1.pos_y = 590
    if cachorro1.pos_y<=0:
        cachorro1.pos_y = 5

    #define o "hitbox" do cão
    if ((cachorro1.pos_x-cachorro1.tamanho_x>=lobo1.pos_x-lobo1.tamanho_x)and (cachorro1.pos_x+cachorro1.tamanho_x<=lobo1.pos_x+lobo1.tamanho_x)):
        if ((cachorro1.pos_y-cachorro1.tamanho_y>=lobo1.pos_y-lobo1.tamanho_y)and (cachorro1.pos_y+cachorro1.tamanho_y<=lobo1.pos_y+lobo1.tamanho_y)):
            Score+=1
            lobo1.status = False
    if ((cachorro1.pos_x-cachorro1.tamanho_x>=lobo2.pos_x-lobo2.tamanho_x)and(cachorro1.pos_x+cachorro1.tamanho_x<=lobo2.pos_x+lobo2.tamanho_x)):
        if ((cachorro1.pos_y-cachorro1.tamanho_y>=lobo2.pos_y-lobo2.tamanho_y)and (cachorro1.pos_y+cachorro1.tamanho_y<=lobo2.pos_y+lobo2.tamanho_y)):
            Score+=1
            lobo2.status = False
    if ((cachorro1.pos_x-cachorro1.tamanho_x>=lobo3.pos_x-lobo3.tamanho_x)and(cachorro1.pos_x+cachorro1.tamanho_x<=lobo3.pos_x+lobo3.tamanho_x)):
        if ((cachorro1.pos_y-cachorro1.tamanho_y>=lobo3.pos_y-lobo3.tamanho_y)and (cachorro1.pos_y+cachorro1.tamanho_y<=lobo3.pos_y+lobo3.tamanho_y)):
            lobo3.status = False
            Score+=1

    if lobo4.status == True:
        if ((cachorro1.pos_x-cachorro1.tamanho_x>=lobo4.pos_x-lobo4.tamanho_x)and(cachorro1.pos_x+cachorro1.tamanho_x<=lobo4.pos_x+lobo4.tamanho_x)):
            if ((cachorro1.pos_y-cachorro1.tamanho_y>=lobo4.pos_y-lobo4.tamanho_y)and (cachorro1.pos_y+cachorro1.tamanho_y<=lobo4.pos_y+lobo4.tamanho_y)):
                lobo4.status = False
                Score+=1

    ########### OVELHA 1 -> Hitbox
    if ((ovelha1.pos_x-ovelha1.tamanho_x>=lobo1.pos_x-lobo1.tamanho_x) and(ovelha1.pos_x+ovelha1.tamanho_x<=lobo1.pos_x+lobo1.tamanho_x)):
        if ((ovelha1.pos_y-ovelha1.tamanho_y>=lobo1.pos_y-lobo1.tamanho_y) and(ovelha1.pos_y+ovelha1.tamanho_y<=lobo1.pos_y+lobo1.tamanho_y)):
            ovelha1.status = False

    if ((ovelha1.pos_x-ovelha1.tamanho_x>=lobo2.pos_x-lobo2.tamanho_x) and(ovelha1.pos_x+ovelha1.tamanho_x<=lobo2.pos_x+lobo2.tamanho_x)):
        if ((ovelha1.pos_y-ovelha1.tamanho_y>=lobo2.pos_y-lobo2.tamanho_y) and(ovelha1.pos_y+ovelha1.tamanho_y<=lobo2.pos_y+lobo2.tamanho_y)):
            ovelha1.status = False

    if ((ovelha1.pos_x-ovelha1.tamanho_x>=lobo3.pos_x-lobo3.tamanho_x) and(ovelha1.pos_x+ovelha1.tamanho_x<=lobo3.pos_x+lobo3.tamanho_x)):
        if ((ovelha1.pos_y-ovelha1.tamanho_y>=lobo3.pos_y-lobo3.tamanho_y) and(ovelha1.pos_y+ovelha1.tamanho_y<=lobo3.pos_y+lobo3.tamanho_y)):
            ovelha1.status = False
    if (lobo4.status):
        if ((ovelha1.pos_x-ovelha1.tamanho_x>=lobo4.pos_x-lobo4.tamanho_x) and(ovelha1.pos_x+ovelha1.tamanho_x<=lobo4.pos_x+lobo4.tamanho_x)):
            if ((ovelha1.pos_y-ovelha1.tamanho_y>=lobo4.pos_y-lobo4.tamanho_y) and(ovelha1.pos_y+ovelha1.tamanho_y<=lobo4.pos_y+lobo4.tamanho_y)):
                ovelha1.status = False

    ########### OVELHA 2 -> Hitbox
    if ((ovelha2.pos_x-ovelha2.tamanho_x>=lobo1.pos_x-lobo1.tamanho_x) and(ovelha2.pos_x+ovelha2.tamanho_x<=lobo1.pos_x+lobo1.tamanho_x)):
        if ((ovelha2.pos_y-ovelha2.tamanho_y>=lobo1.pos_y-lobo1.tamanho_y) and(ovelha2.pos_y+ovelha2.tamanho_y<=lobo1.pos_y+lobo1.tamanho_y)):
            ovelha2.status = False

    if ((ovelha2.pos_x-ovelha2.tamanho_x>=lobo2.pos_x-lobo2.tamanho_x) and(ovelha2.pos_x+ovelha2.tamanho_x<=lobo2.pos_x+lobo2.tamanho_x)):
        if ((ovelha2.pos_y-ovelha2.tamanho_y>=lobo2.pos_y-lobo2.tamanho_y) and(ovelha2.pos_y+ovelha2.tamanho_y<=lobo2.pos_y+lobo2.tamanho_y)):
            ovelha2.status = False

    if ((ovelha2.pos_x-ovelha2.tamanho_x>=lobo3.pos_x-lobo3.tamanho_x) and(ovelha2.pos_x+ovelha2.tamanho_x<=lobo3.pos_x+lobo3.tamanho_x)):
        if ((ovelha2.pos_y-ovelha2.tamanho_y>=lobo3.pos_y-lobo3.tamanho_y) and(ovelha2.pos_y+ovelha2.tamanho_y<=lobo3.pos_y+lobo3.tamanho_y)):
            ovelha2.status = False

    if (lobo4.status):
        if ((ovelha2.pos_x-ovelha2.tamanho_x>=lobo4.pos_x-lobo4.tamanho_x) and(ovelha2.pos_x+ovelha2.tamanho_x<=lobo4.pos_x+lobo4.tamanho_x)):
            if ((ovelha2.pos_y-ovelha2.tamanho_y>=lobo4.pos_y-lobo4.tamanho_y) and(ovelha2.pos_y+ovelha2.tamanho_y<=lobo4.pos_y+lobo4.tamanho_y)):
                ovelha2.status = False

    ########## OVELHA 3 -> Hitbox
    if ((ovelha3.pos_x-ovelha3.tamanho_x>=lobo1.pos_x-lobo1.tamanho_x) and (ovelha3.pos_x+ovelha3.tamanho_x<=lobo1.pos_x+lobo1.tamanho_x)):
        if ((ovelha3.pos_y-ovelha3.tamanho_y>=lobo1.pos_y-lobo1.tamanho_y) and(ovelha3.pos_y+ovelha3.tamanho_y<=lobo1.pos_y+lobo1.tamanho_y)):
            ovelha3.status = False

    if ((ovelha3.pos_x-ovelha3.tamanho_x>=lobo2.pos_x-lobo2.tamanho_x) and(ovelha3.pos_x+ovelha3.tamanho_x<=lobo2.pos_x+lobo2.tamanho_x)):
        if ((ovelha3.pos_y-ovelha3.tamanho_y>=lobo2.pos_y-lobo2.tamanho_y) and(ovelha3.pos_y+ovelha3.tamanho_y<=lobo2.pos_y+lobo2.tamanho_y)):
            ovelha3.status = False

    if ((ovelha3.pos_x-ovelha3.tamanho_x>=lobo3.pos_x-lobo3.tamanho_x) and(ovelha3.pos_x+ovelha3.tamanho_x<=lobo3.pos_x+lobo3.tamanho_x)):
        if ((ovelha3.pos_y-ovelha3.tamanho_y>=lobo3.pos_y-lobo3.tamanho_y) and(ovelha3.pos_y+ovelha3.tamanho_y<=lobo3.pos_y+lobo3.tamanho_y)):
            ovelha3.status = False

    if (lobo4.status):
        if ((ovelha3.pos_x-ovelha3.tamanho_x>=lobo4.pos_x-lobo4.tamanho_x) and(ovelha3.pos_x+ovelha3.tamanho_x<=lobo4.pos_x+lobo4.tamanho_x)):
            if ((ovelha3.pos_y-ovelha3.tamanho_y>=lobo4.pos_y-lobo4.tamanho_y) and(ovelha3.pos_y+ovelha3.tamanho_y<=lobo4.pos_y+lobo4.tamanho_y)):
                ovelha3.status = False

   #renderização dos diversos elementos da tela (Ovelhas, cachorro, e outros)
    window.blit(cachorro1.imagem,(cachorro1.pos_x,cachorro1.pos_y))
################### Ovelhas -> Renascer
    if ovelha1.status:
        window.blit(ovelha1.imagem,(ovelha1.pos_x,ovelha1.pos_y))

    if ovelha2.status:
        window.blit(ovelha2.imagem,(ovelha2.pos_x,ovelha2.pos_y))

    if ovelha3.status:
        window.blit(ovelha3.imagem,(ovelha3.pos_x,ovelha3.pos_y))

############################# LOBOS -> Renascer
    if lobo1.status:
        window.blit(lobo1.imagem,(lobo1.pos_x,lobo1.pos_y))
    else:
        if tempo_segundo%3 == 0:
            tarefalobo = ThreadComRetorno(target = lobo.spawn_lobo, args=[1,randint(120,250),randint(1,5)])
            tarefalobo.start()
            lobo1 = tarefalobo.join()

    if lobo2.status:
        window.blit(lobo2.imagem,(lobo2.pos_x,lobo2.pos_y))

    else:
        if tempo_segundo%4 == 0:
            lobo2 = lobo.spawn_lobo(1,randint(251,430),randint(1,5))

    if lobo3.status:
        window.blit(lobo3.imagem,(lobo3.pos_x,lobo3.pos_y))
    else:
        if tempo_segundo%5 == 0:
            lobo3 = lobo.spawn_lobo(1,randint(431,580),randint(1,5))

    if lobo4.status:
        window.blit(lobo4.imagem,(lobo4.pos_x,lobo4.pos_y))
    else:
        if tempo_segundo%15 == 0:
            lobo4 = lobo.spawn_lobo(1,randint(150,580),8)
            lobo4.status = False

    if lobo4.status == False:
        if Score > 100 and tempo_segundo%15==0:
            lobo4.status = True
        else:
            lobo4.status = False

########################### BURACOS
    if (len(listaBuracos)>0):

        for item in listaBuracos:

            if ((cachorro1.pos_x-cachorro1.tamanho_x>=item.pos_x-item.tamanho_x)and(cachorro1.pos_x+cachorro1.tamanho_x<=item.pos_x+item.tamanho_x)):
                if ((cachorro1.pos_y-cachorro1.tamanho_y>=item.pos_y-item.tamanho_y)and (cachorro1.pos_y+cachorro1.tamanho_y<=item.pos_y+item.tamanho_y)):
                    Score -= 10

    if (Score>=10) and (tempo_segundo%10==0) and (buraco1.status == False):
        if timer ==0:
            buraco1.status = True
            listaBuracos.append(buraco1)
            buraco1 = buraco( randint(100, 720) ,randint(150, 500))
            buraco1.status = False

    if (len(listaBuracos) > 0):
            for item in listaBuracos:
                window.blit(item.imagem, (item.pos_x,item.pos_y))

    if Score<0:
            window.blit(pygame.image.load('game_over.png'), (400,300))
            mutex.acquire(25000)
            mutex.release()
    else:
        pygame.display.update()
pygame.quit()

def criar_ovelha(x,y,velocidade):
    objeto_ovelha = ovelha.spawn_ovelha(620,530,2)
    return objeto_ovelha


import numpy as np
from exec_backends.trt_loader import TrtOCRDecoder
import onnxruntime as rt
import torch
from torch.nn.functional import log_softmax, softmax
from vietocr.tool.config import Cfg
from vietocr.tool.predictor import Predictor
from torch import nn

class TorchDecoder(nn.Module):
    def __init__(self, model):

        super(TorchDecoder, self).__init__()

        self.model = model

    def forward(self, tgt_inp, memory):
        output, _ = self.model.transformer.forward_decoder(tgt_inp, memory)
        output = softmax(output, dim=-1)
        values, indices  = torch.topk(output, 5)
        return values, indices

config = Cfg.load_config_from_name('vgg_transformer')
dataset_params = {
    'name':'hw',
    'data_root':'./my_data/',
    'train_annotation':'train_line_annotation.txt',
    'valid_annotation':'test_line_annotation.txt'
}

params = {
         'print_every':200,
         'valid_every':15*200,
          'iters':20000,
          'checkpoint':'./checkpoint/transformerocr_checkpoint.pth',
          'export':'./weights/transformerocr.pth',
          'metrics': 10000
         }

config['trainer'].update(params)
config['dataset'].update(dataset_params)
config['device'] = 'cpu'

trainer = Predictor(config)

# tgt_inp = torch.randint(0, 232, (20, 1))
tgt_inp = np.random.randint(0, 232, (20, 3))
memory = np.random.randn(170, 3, 256)
# memory = torch.randn(170, 1, 256, requires_grad=True)

trt_model = TrtOCRDecoder('transformer_decoder.trt')
torch_model = TorchDecoder(trainer.model)
torch_model.eval()
onnx_model = rt.InferenceSession('transformer_decoder.onnx')

trt_values, trt_indices = trt_model.run(tgt_inp, memory)

with torch.no_grad():
    torch_values, torch_indices = torch_model(torch.LongTensor(tgt_inp.copy()), torch.Tensor(memory.copy()))
    torch_values = torch_values.detach().cpu().numpy()
    torch_indices = torch_indices.detach().cpu().numpy()

onnx_inp = {onnx_model.get_inputs()[0].name: tgt_inp.copy(), onnx_model.get_inputs()[1].name: memory.copy().astype('float32')}
onnx_values, onnx_indices = onnx_model.run(None, onnx_inp)

print(np.squeeze(torch_values))
print(np.squeeze(onnx_values))
print(np.squeeze(trt_values))

print(np.squeeze(torch_indices))
print(np.squeeze(onnx_indices))
print(np.squeeze(trt_indices))


"""Messing around with annotating the gyros data. These annotators are highly
ad-hoc and not what would eventually be used, in all likelihood. They're more
the sort of thing we want to avoid."""

import numpy as np
from artifice.utils import img, vis
from glob import glob
from skimage.feature import canny
from skimage.draw import circle
import matplotlib.pyplot as plt

class Annotator():
  sigma = 1.0
  def annotate_object(self, image, obj_label):
    """Annotate the object at index-space position.

    :param image: numpy image, float32
    :param obj_label: 1D object label with index-space position at obj_label[1:3]
    :returns: `(xs,ys)` lists of indices belonging to the object at position

    """
    raise NotImplementedError

  def annotate_image(self, image, label):
    """Annotate all the objects in the image.

    :param image: the numpy image
    :param label: `(num_objects, label_dim)` where `label_dim >= 3`
    :returns:
    :rtype:

    """
    annotation = np.zeros_like(image)
    edges = canny(image, sigma=self.sigma)
    for obj_label in label:
      xs, ys = self.annotate_object(image, obj_label, edges=edges)
      annotation[xs,ys] = obj_label[0]
    return annotation

  def __call__(self, *args, **kwargs):
    return self.annotate_image(*args, **kwargs)

class GyroAnnotator(Annotator):
  initial_radius = 10
  def annotate_object(self, image, obj_label, edges=None):
    """Annotate the gyro at `obj_label`.

    Run a canny edge detector on the image, if needed

    """
    if edges is None:
      edges = canny(image, sigma=self.sigma)

    """
    Grab the edge pixels within 10 pixels, calculate distance to center, take
    their median as the true radius and return pixels within that range.
    """

    rr, cc = circle(obj_label[1], obj_label[2], self.initial_radius,
                    shape=image.shape)

    mask = np.zeros_like(image, dtype=bool)
    mask[rr,cc] = True
    xs, ys = np.where(np.logical_and(edges, mask))
    distances = np.linalg.norm(
      np.stack((xs - obj_label[1], ys - obj_label[2]), axis=1), axis=1)
    r = np.median(distances) + 1.5
    return circle(obj_label[1], obj_label[2], r, shape=image.shape)

def main():
  labels = np.load('data/gyros/labels.npy')
  image_paths = sorted(glob('data/gyros/images/*.png'))
  annotator = GyroAnnotator()
  for i, (image_path, label) in enumerate(zip(image_paths, labels)):
    if i % 100 == 0:
      print(f"{i} / {labels.shape[0]}")
    image = img.open_as_float(image_path)
    annotation = annotator(image, labels[0])
    np.save(f'data/gyros/annotations/{str(i).zfill(4)}.npy', annotation)
    # fig, axes = vis.plot_image(image, scale=80)
    # xs, ys = np.where(annotation)
    # plt.plot(ys, xs, 'r.')
    # plt.show()
    # plt.savefig('docs/gyro_annotation.png')

if __name__ == "__main__":
  main()