Exemple #1
0
    def next_bus_for_matches(self, bus_stop_matches,
                             search_result: SearchResult):
        def show_arrival(info: CoddNextBus):
            routes = search_result.bus_routes
            return info.time_ > 0 and (not routes
                                       or info.rname_.strip() in routes)

        result = [f'Время: {self.now():%H:%M} (Рассчёт ЦОДД)']
        routes_set = set()
        if search_result.bus_routes:
            result.append(
                f"Фильтр по маршрутам: {' '.join(search_result.bus_routes)}")
        for item in bus_stop_matches:
            arrivals = self.next_bus_for_lat_lon(item.LAT_, item.LON_)
            if arrivals:
                header = arrivals[0]
                items = [x for x in arrivals[1:] if show_arrival(x)]
                routes_set.update([x.rname_.strip() for x in items])
                self.logger.info(items)
                items.sort(key=lambda s: natural_sort_key(s.rname_))
                if not items:
                    result.append(f'Остановка {header.rname_}: нет данных')
                    continue
                next_bus_info = f"Остановка {header.rname_}:\n"
                next_bus_info += '\n'.join(
                    (f"{x.rname_:>5} {x.time_:>2.0f} мин" for x in items))
                result.append(next_bus_info)
        routes_list = list(routes_set)
        routes_list.sort(key=natural_sort_key)
        result.append(
            f'Ожидаемые маршруты (но это не точно, проверьте список): {" ".join(routes_list)}'
        )
        return ('\n'.join(result), " ".join(routes_list))
Exemple #2
0
    def bus_request_as_list(self, bus_routes):
        def key_check(route: CdsRouteBus):
            return route.name_ and last_week < route.last_time_

        keys = set([
            x for x in self.cds_routes.keys() for r in bus_routes
            if x.upper() == r.upper()
        ])

        routes = self.load_cds_buses_from_db(tuple(keys))
        self.logger.debug(routes)
        if routes:
            last_week = self.now() - timedelta(days=7)
            short_result = sorted(
                [d for d in routes if key_check(d)],
                key=lambda s: natural_sort_key(s.route_name_))
            return short_result
        return []
Exemple #3
0
    def get_bus_statistics(self, full_info=False) -> Optional[StatsData]:
        def time_check(bus: CdsRouteBus, last_time):
            if not bus.last_time_ or bus.last_time_ < last_time:
                return False
            # if bus.last_station_time_ and bus.last_station_time_ < last_time:
            #     return False
            return True

        def count_buses(buses: Iterable[CdsRouteBus], time_interval):
            return sum(
                1 for i in buses
                if time_check(i, now - time_interval) and i.obj_output != 1)

        cds_buses = self.load_all_cds_buses_from_db()
        if not cds_buses:
            return

        now = self.now()
        hour_1 = count_buses(cds_buses, timedelta(hours=1))
        minutes_10 = count_buses(cds_buses, timedelta(minutes=10))
        minutes_30 = count_buses(cds_buses, timedelta(minutes=30))
        total = count_buses(cds_buses, timedelta(days=7))
        bus_stats_text = f"1 ч. 30 мин. 10 мин.\n{hour_1:<5} {minutes_30:^5} {minutes_10:5}\nВсего: {total}"
        self.logger.info(f"{hour_1: <5} {minutes_30:5} {minutes_10:5}")
        if hour_1 > 0:
            buses_list = [f'Время: {self.now():%H:%M:%S}']
            if full_info:
                short_result = [
                    d for d in cds_buses
                    if time_check(d, now - timedelta(minutes=10))
                ]
                sort_routes = sorted(
                    short_result,
                    key=lambda x: natural_sort_key(x.route_name_))
                grouped = [(k, len(list(g))) for k, g in groupby(
                    sort_routes,
                    lambda x: f'{x.route_name_:5s} ({x.proj_id_:3d})')]
                buses_list += (('{:10s} => {}'.format(i[0], i[1]))
                               for i in grouped)
            buses_list.append(bus_stats_text)
            text = '\n'.join(buses_list)
            text += f'\nНа линии: {self.bus_stats[-1][1]}'
            return StatsData(minutes_10, minutes_30, hour_1, len(cds_buses),
                             text)
Exemple #4
0
    def bus_request(self,
                    search_result: SearchResult,
                    user_loc: UserLoc = None,
                    short_format=False):
        if search_result.all_buses:
            keys = set(self.codd_routes.keys())
        else:
            keys = set([
                x for x in self.codd_routes.keys()
                for r in search_result.bus_routes if x.upper() == r.upper()
            ])

        if not keys and search_result.bus_filter == '':
            return 'Не заданы маршруты', []
        short_result = self.bus_request_as_list(tuple(keys))
        if short_result:
            stations_filtered = self.filter_bus_list(short_result,
                                                     search_result)
            if stations_filtered:
                stations_filtered.sort(
                    key=lambda x: natural_sort_key(x[0].route_name_))
                if short_format:
                    lines = []
                    cur_route = ''
                    for (k, v) in stations_filtered:
                        if cur_route != k.route_name_:
                            cur_route = k.route_name_
                            lines.append("")
                            lines.append(cur_route)
                        lines.append(
                            self.station(k, user_loc, search_result.full_info,
                                         False))
                    text = ' \n'.join(lines)
                else:
                    text = ' \n'.join((self.station(d[0], user_loc,
                                                    search_result.full_info)
                                       for d in stations_filtered))
                return text, stations_filtered

        return 'Ничего не нашлось', []
Exemple #5
0
    def get_bus_statistics(self, full_info=False):
        def time_check(bus: CdsRouteBus, last_time):
            if not bus.last_time_ or bus.last_time_ < last_time:
                return False
            # if bus.last_station_time_ and bus.last_station_time_ < last_time:
            #     return False
            return True

        def count_buses(buses: Iterable[CdsRouteBus], time_interval):
            return sum(1 for i in buses if time_check(i, now - time_interval))

        cds_buses = self.load_all_cds_buses_from_db()
        if not cds_buses:
            return 'Ничего не нашлось'

        now = self.now()
        short_result = [
            d for d in cds_buses if time_check(d, now - timedelta(hours=1))
        ]
        last_hour = len(short_result)
        short_result = sorted(short_result,
                              key=lambda x: natural_sort_key(x.route_name_))
        grouped = [(k, len(list(g))) for k, g in groupby(
            short_result, lambda x: f'{x.route_name_:5s} ({x.proj_id_:3d})')]
        minutes_10 = count_buses(short_result, timedelta(minutes=10))
        minutes_30 = count_buses(short_result, timedelta(minutes=30))
        bus_stats_text = f"1 h. 30 min. 10 min.\n{last_hour:5d} {minutes_30:5d} {minutes_10:5d}\nTotal: {len(cds_buses)}"
        self.logger.info(f"{last_hour:5d} {minutes_30:5d} {minutes_10:5d}")
        if short_result:
            buses = []
            if full_info:
                buses += (('{:10s} => {}'.format(i[0], i[1])) for i in grouped)
            buses.append(bus_stats_text)
            return '\n'.join(buses)

        return 'Ничего не нашлось'
Exemple #6
0
    def get_all_buses(self):
        def key_check(x: CdsBus):
            return x.name_ and x.last_time_ and (now - x.last_time_) < hour

        cds_buses = self.load_all_cds_buses_from_db()
        if not cds_buses:
            return 'Ничего не нашлось'

        now = self.now()
        hour = timedelta(hours=1)
        short_result = [(d.name_, d.last_time_, d.route_name_, d.proj_id_)
                        for d in cds_buses if key_check(d)]
        short_result = sorted(short_result,
                              key=lambda x: natural_sort_key(x[2]))
        grouped = [
            (k, len(list(g)))
            for k, g in groupby(short_result, lambda x: f'{x[2]} ({x[3]})')
        ]
        if short_result:
            buses = ' \n'.join(
                (('{} => {}'.format(i[0], i[1])) for i in grouped))
            return buses

        return 'Ничего не нашлось'