Example #1
0
class Downtime(SmsdkEntities, MaSession):

    # Decorator to register a function as utility
    # Only the registered utilites would be accessible
    # to outside world via client.get_data()
    mod_util = module_utility()

    def __init__(self, session, base_url) -> None:
        self.session = session
        self.base_url = base_url

    @mod_util
    def get_utilities(self, *args, **kwargs) -> List:
        """
        Get the list of registered utilites by name
        """
        return [*self.mod_util.all]

    @mod_util
    def get_downtime(self, *args, **kwargs):
        """
        Utility function to get the downtimes
        from the ma downtime API
        Recommend to use 'enable_pagination':True for larger datasets
        """
        url = "{}{}".format(self.base_url, ENDPOINTS["Downtime"]["url"])

        records = self._get_records(url, **kwargs)
        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records
Example #2
0
class DataViz(SmsdkEntities, MaSession):
    # Decorator to register a function as utility
    # Only the registered utilites would be accessible
    # to outside world via client.get_data()
    mod_util = module_utility()

    def __init__(self, session, base_url) -> None:
        self.session = session
        self.base_url = base_url

    @mod_util
    def get_utilities(self, *args, **kwargs) -> List:
        """
        Get the list of registered utilites by name
        """
        return [*self.mod_util.all]

    @mod_util
    def cycle_count(self, *args, **kwargs):
        url = "{}{}".format(self.base_url,
                            ENDPOINTS["DataViz"]["estimate_cycle"])

        records = self._get_records_v1(url, limit=1, **kwargs)

        return records[0]
Example #3
0
class Cycle(SmsdkEntities, MaSession):

    # Decorator to register a function as utility
    # Only the registered utilites would be accessible
    # to outside world via client.get_data()
    mod_util = module_utility()

    def __init__(self, session, base_url) -> None:
        self.session = session
        self.base_url = base_url

    @mod_util
    def get_utilities(self, *args, **kwargs) -> List:
        """
        Get the list of registered utilites by name
        """
        return [*self.mod_util.all]

    @mod_util
    def get_cycles(self, *args, **kwargs):
        """
        Utility function to get the cycles
        from MA API
        Recommend to use 'enable_pagination':True for larger datasets
        """
        url = "{}{}".format(self.base_url, ENDPOINTS["Cycle"]["alt_url"])

        if 'machine__source' not in kwargs and 'machine__source__in' not in kwargs:
            log.warn('Machine source not specified.')
            return []

        records = self._get_records(url, **kwargs)
        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records
Example #4
0
class Parts(SmsdkEntities, MaSession):
    # Decorator to register a function as utility
    # Only the registered utilites would be accessible
    # to outside world via client.get_data()
    mod_util = module_utility()

    def __init__(self, session, base_url) -> None:
        self.session = session
        self.base_url = base_url

    @mod_util
    def get_utilities(self, *args, **kwargs) -> List:
        return [*self.mod_util.all]

    @mod_util
    def get_parts(self, *args, **kwargs):
        """
        Utility function to get the parts
        from the ma machine API
        Recommend to use 'enable_pagination':True for larger datasets
        """
        url = "{}{}".format(self.base_url, ENDPOINTS["Parts"]["url"])

        records = self._get_records(url, **kwargs)
        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records

    @mod_util
    def get_part_schema(self, *args, **kwargs):
        """
        https://essex-torreon-spxim-97.sightmachine.io/v1/selector/datatab/part/pt_area_300/field?db_mode=sql&strip_aliases=false
        :return:
        """
        endpoint = f"/v1/selector/datatab/part/{kwargs.get('type__part_type')}/field?db_mode=sql&strip_aliases=false"
        url = "{}{}".format(self.base_url, endpoint)
        records = self._get_records(url, **kwargs)
        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records

    @mod_util
    def get_all_parts(self, **kwargs):
        endpoint = ENDPOINTS["Parts"]["part_schema"]
        url = "{}{}".format(self.base_url, endpoint)
        records = self._get_schema(url, **kwargs)

        # Adding new fields in response named column_count that will count all the columns associated with any part
        for each_part_type in records:
            stats = each_part_type['stats']
            stats_count = sum([len(each_part_type['stats'][i]) for i in stats])
            each_part_type.update({"column_count":stats_count})

        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records
Example #5
0
class Downtime(SmsdkEntities, MaSession):
    # Decorator to register a function as utility
    # Only the registered utilites would be accessible
    # to outside world via client.get_data()
    mod_util = module_utility()

    def __init__(self, session, base_url) -> None:
        self.session = session
        self.base_url = base_url

    @mod_util
    def get_utilities(self, *args, **kwargs) -> List:
        """
        Get the list of registered utilites by name
        """
        return [*self.mod_util.all]

    @mod_util
    def get_downtime(self, *args, **kwargs):
        """
        Utility function to get the downtimes
        from the ma downtime API
        Recommend to use 'enable_pagination':True for larger datasets
        """
        url = "{}{}".format(self.base_url, ENDPOINTS["Downtime"]["url_v1"])

        if '/api/downtime' in url:
            records = self._get_records(url, **kwargs)
        else:
            kwargs = self.modify_input_params(**kwargs)
            records = self._get_records_v1(url, **kwargs)

        if not isinstance(records, List):
            raise ValueError("Error - {}".format(records))
        return records

    def modify_input_params(self, **kwargs):

        new_kwargs = {}
        etime = datetime.now()
        stime = etime - timedelta(days=1)
        new_kwargs['asset_selection'] = {
            "machine_source": kwargs.get('machine__source', ''),
            "machine_type": kwargs.get('machine_type', '')
        }

        start_key, end_key = self.get_starttime_endtime_keys(**kwargs)
        # https://37-60546292-gh.circle-artifacts.com/0/build/html/web_api/v1/datatab/index.html#get--v1-datatab-cycle
        where = []
        if start_key:
            starttime = kwargs.get(start_key, "") if start_key else stime
            where.append({
                'name': start_key.split('__')[0],
                'op': start_key.split('__')[-1],
                'value': starttime.isoformat()
            })

        if end_key:
            endtime = kwargs.get(end_key, "") if end_key else stime
            where.append({
                'name': end_key.split('__')[0],
                'op': end_key.split('__')[-1],
                'value': endtime.isoformat()
            })

        for kw in kwargs:
            if kw[0] != '_' and 'machine_type' not in kw and 'Machine' not in kw and 'machine__source' not in kw and 'End Time' not in kw and 'endtime' not in kw and 'Start Time' not in kw and 'starttime' not in kw:
                if '__' not in kw:
                    where.append({'name': kw, 'op': 'eq', 'value': kwargs[kw]})
                else:
                    key = '__'.join(kw.split('__')[:-1])
                    op = kw.split('__')[-1]

                    if op == 'val':
                        op = 'eq'
                        key += '__val'

                    if op != 'exists':
                        where.append({
                            'name': key,
                            'op': op,
                            'value': kwargs[kw]
                        })
                    else:
                        if kwargs[kw]:
                            where.append({
                                'name': key,
                                'op': 'ne',
                                'value': None
                            })
                        else:
                            where.append({
                                'name': key,
                                'op': 'eq',
                                'value': None
                            })

        new_kwargs['where'] = where

        if kwargs.get("_order_by", ""):
            order_key = kwargs["_order_by"].replace("_epoch", "")
            if order_key.startswith('-'):
                order_type = 'desc'
                order_key = order_key[1:]
            else:
                order_type = 'asc'
            new_kwargs['order_by'] = [{'name': order_key, 'order': order_type}]

        new_kwargs['select'] = [{'name': i} for i in kwargs['_only']]
        new_kwargs['offset'] = kwargs.get('_offset', 0)
        new_kwargs['limit'] = kwargs.get('_limit', np.Inf)

        return new_kwargs