def get(self): op = self.request.get('op') if op == 'test': for m in Message.all(): m.delete() elif op == 'request_channel': channelName = self.request.get('instance_id') channelToken = channel.create_channel(channelName) ret = {} ret['channel_token'] = channelToken self.out(BaseUtils.asJson(ret)) elif op == 'recent_instances': recentInstances = [] for instance in ApiMethodsHandler.recentInstances(): recentInstances.append(instance.jsonForm()) self.out(BaseUtils.asJson(recentInstances)) elif op == 'instance_by_id': instanceId = self.request.get('id') if instanceId != '': instance = ApiMethodsHandler.recentInstancesList().recentInstanceById(instanceId) if instance != None: self.out(BaseUtils.asJson(instance.jsonForm())) return self.out(BaseUtils.asJson({'id':''})) elif op == 'check_channel': self.notifyUser(self.request.get('channel'), 'event', {'data':self.request.get('val')}) self.out('done')
def show_archive(self, channel, ts): ts_start = BaseUtils.ts_to_dt(int(ts)) - timedelta(seconds=2) ts_end = BaseUtils.ts_to_dt(int(ts)) + timedelta(seconds=10) start_str = ts_start.strftime("%Y-%m-%d %H:%M:%S") end_str = ts_end.strftime("%Y-%m-%d %H:%M:%S") logger.debug( "open archive, for channel: %s, mon: %s, start: %s, end: %s" % (channel, self.display_number, start_str, end_str)) self._gui.show_archive(channel, self.display_number, start_str, end_str)
def event_handler(self, event): try: logger.debug("event type: %s", event.type) if event.type == "Left Object Detected": channel = getattr(event.origin_object, "associated_channel", None) else: channel = event.origin logger.debug("channel: %s", channel) channel = channel.split("_")[0] if not self.check_channel(channel): logger.debug("channel %s not in channels list, return", channel) return channel_obj = self.obj_storage.channels.get(channel) if not channel_obj: logger.debug("channel object not found: %s, return", channel) return channel_full = channel_obj.full_guid server_guid = channel_obj.server ts = event.ts - utc_offset(server_guid) * 60 * 1e6 dt = BaseUtils.ts_to_dt(ts) logger.debug( "Trassir timestamp: %s, Trassir dt is : %s, corrected dt: %s", event.ts, BaseUtils.ts_to_dt(event.ts), dt, ) alarm_messages = None if getattr(event, "data", None): alarm_messages = json.loads(getattr( event, "data")).get("alarm_messages") logger.debug("alarm message in data") if not alarm_messages: alarm_messages = make_alarm_message(channel_obj.name, dt, event.type) if event.type == "Plate detected": ts = event.ts if self.callback: self.callback(channel_full, ts, alarm_messages) except Exception as err: logger.exception("simple_events_handler: error occurred: %s", err)
def make_file_name(chan_name, tmstmp, plate): event_time = BaseUtils.ts_to_dt(tmstmp) plate = plate.replace("?", "_") plate = plate.upper() return r"{} ({})({}).jpg".format( chan_name, event_time.strftime("%Y.%m.%d %H-%M-%S"), plate )
def make_alarm_message(channel_name, event_type, tmstmp): ev_translation = EVENTS_TRANSLATION.get(event_type, "Unknown") event_time = BaseUtils.ts_to_dt(tmstmp) alarm_messages = { "alert_message": "<b><font color='red'>{text_1}: '{ev_translation}'</font></b><br>{text2}: {channel_name}" .format( event_time=event_time, text_1=loc.main.alarm, ev_translation=ev_translation, text2=loc.main.channel, channel_name=channel_name, ), "sms_message": "{event_time}.{text_1}: '{ev_translation}'. {text2}: {channel_name}". format( event_time=event_time, text_1=loc.main.alarm, ev_translation=ev_translation, text2=loc.main.channel, channel_name=channel_name, ), "mail_message": "{event_time}.{text_1}: '{ev_translation}'. {text2}: {channel_name}". format( event_time=event_time, text_1=loc.main.alarm, ev_translation=ev_translation, text2=loc.main.channel, channel_name=channel_name, ), } return alarm_messages
def event_handler(self, event): channel_full = "{channel}_{server}".format(channel=event.channel_guid, server=event.server_guid) channel = event.channel_guid channel_obj = self.obj_storage.channels.get(event.channel_guid) if not channel_obj: logger.debug("channel object not found: %s, return", event.channel_guid) return exceed = self._search_exceeding(self._objects_sum(event.zones)) events = [] for zone_id, exceed_by_type in exceed.iteritems(): for _type, count in exceed_by_type.iteritems(): event_data = {channel_full: {zone_id: {_type: count}}} if not self.same_event_filter.is_same(event_data): event_type = EVENTS_TRANSLATION.get( EVENTS_TYPES.get(_type), "Unknown") alarm_messages = make_alarm_message( channel_obj.name, BaseUtils.ts_to_dt(event.event_ts), event_type, zone_id) events.append((channel_full, event.event_ts, alarm_messages, zone_id)) if self.callback: for event in events: channel_full, event_ts, alarm_messages, zone_name = event self.callback(channel_full, event_ts, alarm_messages, zone_name=zone_name)
def get_alarm_message(chan_name, tmstmp): event_time = BaseUtils.ts_to_dt(tmstmp) alarm_messages = { "alert_message": ("<br><b><font color='red'>{event_time} {event_type}</font></b>" "<br>{on_channel}: {chan_name}").format( event_time=event_time.strftime("%H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ), "sms_message": ("{event_time}.{event_type}. {on_channel}:{chan_name}").format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ), "mail_message": ("{event_time}. {event_type}. {on_channel}: {chan_name}").format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Номер не распознан"), on_channel=host.tr("Канал"), chan_name=chan_name, ) } return alarm_messages
def _get_html_img(image_base64, **kwargs): """Returns html img Args: image_base64 (str): Base64 image """ return BaseUtils.base64_to_html_img(image_base64, **kwargs)
def open_archive(self, channel, tmstmp): logger.debug("Start show archive, channel is: %s, tmstmp: %s", channel, tmstmp) ts_start = BaseUtils.ts_to_dt(tmstmp) - timedelta(seconds=5) ts_end = BaseUtils.ts_to_dt(tmstmp) start_str = ts_start.strftime("%Y%m%d_%H%M%S") end_str = ts_end.strftime("%Y%m%d_%H%M%S") logger.debug("open_arhive - chan: %s, mon: %s, start: %s, end: %s", channel, self.monitor_to_show_archive_from_popup, start_str, end_str) try: self._gui.show_archive( # pylint:disable=E1101 channel, self.monitor_to_show_archive_from_popup, start_str, end_str) except EnvironmentError as err: logger.debug("Can't show archive. Error occur: %s", err)
def send(self, status, shot_path, alarm_messages, *args, **kwargs): """ Args: status (str): one of "saving", "error", "success", "in_queue" shot_path (List['str']): ['Shot path 1', 'Shot path 2'] alarm_messages (dict): Returns: """ self.contents = [ { "type": "html", "html": ("<!doctype html><head><meta charset='utf-8'></head><body>" "" "{message}" "" "</body></html>").format( message=alarm_messages.get('mail_message', 'No text')), }, ] if kwargs.get("channel") and self.add_video: try: full_channel = kwargs.get("channel") channel, server = full_channel.split("_") self.contents.append({ "type": "trassir_channel", "channel_guid": channel, "name": host.object(channel).name, "server_guid": server, }) except IndexError: logger.debug( "Can't get server name to make video content for alarm") if status == STATUS.success: logger.debug('try to send alarm') self.contents.append({ "type": "image", "format": "jpg", "image_base64": BaseUtils.image_to_base64(shot_path[0]), }) self.description = alarm_messages.get('mail_message', 'No text') super(FireAlarm, self).fire() elif status == STATUS.error: logger.debug('image not saved, try to send text alarm') self.description = alarm_messages.get('mail_message', 'No text') super(FireAlarm, self).fire()
def check_path(path): """Проверка существования папки для временных изображений""" path = BaseUtils.win_encode_path(path) if not os.path.isdir(path): try: os.makedirs(path) except OSError as err: logger.error("Can't make dir '%s': %s", path, err) raise OSError("Can't make dir '{}': {}".format(path, err)) return path
def _get_base64(image_path): """Returns base64 image Args: image_path (str): Image full path """ base64_image = "" image_path = BaseUtils.win_encode_path(image_path) if os.path.isfile(image_path): with open(image_path, "rb") as image_file: base64_image = base64.b64encode(image_file.read()) return base64_image
def make_alarm_message(channel_name, tmstmp, event_type): event_name = "{}".format(event_type) event_time = BaseUtils.ts_to_dt(tmstmp) dt = event_time.strftime("%d-%m-%Y %H:%M:%S") alarm_messages = { name: _frmt.format( event_time=dt, text_1=loc.gate.pacs_gate_event, event_name=event_name, text2=loc.gate.channel, channel_name=channel_name, ) for name, _frmt in all_formats.iteritems() } return alarm_messages
def event_handler(self, event): plate = event.plate tmstmp = event.time_bestview channel = event.channel event_flag = event.flags dt_bw = BaseUtils.ts_to_dt(tmstmp) logger.debug("Plate in event: %s, time best_view: %s", plate, dt_bw) if channel not in self.channels: logger.debug("channel %s not in channels list", channel) return if time.time() - tmstmp / 1e6 > 60: logger.debug("Event ignoring, because it too old") return if len(plate) > 1: logger.debug("plate recognized") return if self.is_similar_event(plate, tmstmp): return if not self.is_direction_right(event_flag): logger.debug("Wrong direction, break. Event flag: %s", event_flag) return channel_full_guid = None if self.channels.get(channel): channel_full_guid = getattr(self.channels.get(channel), "full_guid") logger.debug("full guid %s", channel_full_guid) alarm_message = get_alarm_message( chan_name=getattr(self.channels.get(channel), "name"), tmstmp=tmstmp, ) shot_name = make_file_name(getattr(self.channels.get(channel), "name"), tmstmp) logger.debug("shot_name: %s", shot_name) self.make_reactions(self.channels.get(channel), tmstmp, alarm_message, shot_name=shot_name)
def make_alarm_message(self, channel_name, input_guid, event_type, tmstmp): input_name = BaseUtils.get_object_name_by_guid(input_guid) alarm_messages = {} event_time = datetime.fromtimestamp(tmstmp/1e6) ev_translation = self.events_translation.get(event_type, "Unknown") alarm_messages["alert_message"] = ( "<br><b><font color='red'>{event_type}</font></b><br>{event_time}" "<br>{input_name_text}:<br>{input_name}. <br>{on_channel}: {chan_name}" ).format( event_time=event_time, event_type=ev_translation, input_name_text=loc.gpio.input_name, input_name=input_name, on_channel=loc.gpio.associated_channel, chan_name=channel_name, ) alarm_messages["sms_message"] = ( "{event_type}: {input_name}. {on_channel}: {chan_name}" ).format( event_type=ev_translation, input_name=input_name, on_channel=loc.gpio.associated_channel, chan_name=channel_name, ) alarm_messages["mail_message"] = ( "{event_time}. {event_type}: {input_name}." " {on_channel}: {channel_name}.".format( event_time=event_time, input_name=input_name, event_type=ev_translation, on_channel=loc.gpio.associated_channel, channel_name=channel_name, ) ) return alarm_messages
def make_alarm_message(channel_name, event_type, tmstmp, code): event_translation = "{event_name}: {code}".format( event_name=EVENTS_TRANSLATION.get(event_type, "Unknown"), code=code) event_time = BaseUtils.ts_to_dt(tmstmp) dt = event_time.strftime("%d-%m-%Y %H:%M:%S") alarm_messages = { "alert_message": "{event_time}<br><b><font color='red'>{text_1}: {event_name}" "</font></b><br>{text2}: {channel_name}".format( event_time=dt, text_1=loc.main.alarm, event_name=event_translation, text2=loc.main.channel, channel_name=channel_name, ), "sms_message": "{event_time}.{text_1}: {event_name}" ". {text2}: {channel_name}".format( event_time=dt, text_1=loc.main.alarm, event_name=event_translation, text2=loc.main.channel, channel_name=channel_name, ), "mail_message": "{event_time}.{text_1}: {event_name}" ". {text2}: {channel_name}".format( event_time=dt, text_1=loc.main.alarm, event_name=event_translation, text2=loc.main.channel, channel_name=channel_name, ), } return alarm_messages
def make_file_name(chan_name, tmstmp): event_time = BaseUtils.ts_to_dt(tmstmp) return r"{} ({}).jpg".format( chan_name, event_time.strftime("%Y.%m.%d %H-%M-%S"), )
def event_handler(self, event): channel_full = "{channel}_{server}".format(channel=event.channel_guid, server=event.server_guid) channel = event.channel_guid channel_obj = self.obj_storage.channels.get(event.channel_guid) if not channel_obj: logger.debug("channel object not found: %s, return", event.channel_guid) return events = [] for zone in event.zones: if zone.zone_type != 1: continue border_name = getattr(zone, "zone_name", getattr(zone, "name", None)) if self.ab_borders: a_to_b = zone.tracking_state.a_to_b_unique_count_by_classes _types_a_b = self.ab_handler(a_to_b, channel, border_name) if _types_a_b: for _type in _types_a_b: event_data = {channel_full: {border_name: {_type: 0}}} if not self.same_event_filter.is_same(event_data): event_type = "{direction}: {object_type}".format( direction=EVENTS_TRANSLATION.get( "Border Crossed A -> B"), object_type=OBJECT_TYPES_TRANSLATION.get( _type), ) alarm_messages = make_alarm_message( channel_obj.name, BaseUtils.ts_to_dt(event.event_ts), event_type, border_name, ) events.append( (channel_full, event.event_ts, alarm_messages)) if self.ba_borders: b_to_a = zone.tracking_state.b_to_a_unique_count_by_classes _types_b_a = self.ba_handler(b_to_a, channel, border_name) if _types_b_a: for _type in _types_b_a: event_data = {channel_full: {border_name: {_type: 0}}} if not self.same_event_filter.is_same(event_data): event_type = "{direction}: {object_type}".format( direction=EVENTS_TRANSLATION.get( "Border Crossed B -> A"), object_type=OBJECT_TYPES_TRANSLATION.get( _type), ) alarm_messages = make_alarm_message( channel_obj.name, BaseUtils.ts_to_dt(event.event_ts), event_type, border_name, ) events.append( (channel_full, event.event_ts, alarm_messages)) if self.callback and events: for event in events: self.callback(*event)
def event_handler(self, event): plate = event.plate tmstmp = event.time_bestview channel = event.channel event_flag = event.flags dt_bw = BaseUtils.ts_to_dt(tmstmp) logger.debug("Plate in event: %s, time best_view: %s", plate, dt_bw) if channel not in self.channels: logger.debug("channel %s not in channels list", channel) return if time.time() - tmstmp / 1e6 > 60: logger.debug("Event ignoring, because it too old") return if len(plate) <= 3: logger.debug("plate to short, break") return if self.is_similar_event(plate, tmstmp): return if not self.is_direction_right(event_flag): logger.debug("Wrong direction, break. Event flag: %s", event_flag) return channel_full_guid = None if self.channels.get(channel): channel_full_guid = getattr(self.channels.get(channel), "full_guid") logger.debug("full guid %s", channel_full_guid) found, reaction, comment, list_name = self.which_list(event) if found == search_result.NOT_FOUND_IN_ANY_LIST and self.list_type[0] == -1: """Не найдено в списках, так и надо. Вызываем реакцию""" alarm_message = get_alarm_message( chan_name=getattr(self.channels.get(channel), "name"), tmstmp=tmstmp, plate=plate, plate_comment="", list_name="", ) elif found == search_result.FOUND_IN_THE_DESIRED_LIST: """ Найден в списке который удовлетворяет заданному""" alarm_message = get_alarm_message( chan_name=getattr(self.channels.get(channel), "name"), tmstmp=tmstmp, plate=plate, plate_comment=comment, list_name=list_name, ) elif self.list_type == [-1, 0, 1, 2]: alarm_message = get_alarm_message( chan_name=getattr(self.channels.get(channel), "name"), tmstmp=tmstmp, plate=plate, plate_comment=comment, list_name=list_name, ) else: logger.debug("found result: %s, break", found) return shot_name = make_file_name( getattr(self.channels.get(channel), "name"), tmstmp, plate ) logger.debug("shot_name: %s", shot_name) self.make_reactions( self.channels.get(channel), tmstmp, alarm_message, shot_name=shot_name )
def get_alarm_message(chan_name, tmstmp, plate, plate_comment, list_name): """ Args: chan_name (str): channel name tmstmp (long): Trassir timestamp plate (str): plate from event or recognized plate plate_comment (str): plate comment list_name (str): list_name Returns: 'dict' """ alarm_messages = {} event_time = BaseUtils.ts_to_dt(tmstmp) plate = plate.upper() if plate_comment: plate_comment_alarm_message = "<br>Комментарий: {}.".format(plate_comment) plate_comment_mail_message = " Комментарий: {}.".format(plate_comment) else: plate_comment_alarm_message = "" plate_comment_mail_message = "" if list_name: list_name_alarm_message = "<br>Имя списка: {list_name}.".format( list_name=list_name ) list_name_mail_message = " Имя списка: {list_name}.".format(list_name=list_name) else: list_name_alarm_message = "" list_name_mail_message = "" alarm_messages["alert_message"] = ( "<br><b><font color='red'>{event_time} {event_type}</font></b>" "<br>{plate}{plate_comment}{list_name}" "<br>{on_channel}: {chan_name}" ).format( event_time=event_time.strftime("%H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment_alarm_message, on_channel=host.tr("Канал"), chan_name=chan_name, list_name=list_name_alarm_message, ) alarm_messages["sms_message"] = ( "{event_time}.{event_type}:{plate}{plate_comment}.{on_channel}:{chan_name}" ).format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment, on_channel=host.tr("Канал"), chan_name=chan_name, ) alarm_messages["mail_message"] = ( "{event_time}. {event_type}: {plate}.{plate_comment}{list_name} {on_channel}: {chan_name}" ).format( event_time=event_time.strftime("%d-%m-%Y %H:%M:%S"), event_type=host.tr("Распознан номер"), plate=plate, plate_comment=plate_comment_mail_message, on_channel=host.tr("Канал"), chan_name=chan_name, list_name=list_name_mail_message, ) return alarm_messages
def execute(self, channel, ts, alarm_messages, *args, **kwargs): """ При распознавании лица на сервере фото из БД и фото распознанного лица из трека лежат в kwargs.get("images") в виде kwargs.get("images") = { "db_image": [bytes_1, bytes_2], "track_image": [bytes_3] } Args: channel (str): channel full guid ts (int): (Trassir 16 digit timestamp) alarm_messages (dict): *args: **kwargs: Returns: """ if self.shot_spam_filter and self.shot_spam_filter.is_same(channel): logger.debug("shot spam filter enabled, break for channel: %s", channel) return ts = int(ts) + int(self.delta * 1e3) if self.online_shot: ts = None if self.save_substream: ts = datetime.now() + timedelta(days=7) channel_name = re.sub( self.spec_symbols, "_", BaseUtils.get_object_name_by_guid(channel), ) zone_name = kwargs.get("zone_name") if zone_name: file_name = "{channel_name}({zone_name}) (%Y.%m.%d %H-%M-%S.%f).jpg".format( channel_name=channel_name, zone_name=zone_name) else: file_name = "{channel_name} (%Y.%m.%d %H-%M-%S.%f).jpg".format( channel_name=channel_name) if self.save_screen: file_path = os.path.join(datetime.now().date().isoformat(), channel_name) full_path = os.path.normpath( os.path.join(self.base_folder, file_path)) else: full_path = self.temp_folder logger.debug("file path for screen: %s", full_path) # shot_saver.ShotSaver task_guid, file_path = self.shot_saver_obj.save( channel, ts, figures=self.figures, file_path=full_path, file_name=file_name, callback=self.send_shots) self._working[task_guid] = { "alarm_messages": alarm_messages, "state": "just_created", "created_ts": int(time.time()), "file_path": file_path, "images": kwargs.get("images"), "channel": channel, }
def event_handler(self, event): """ Args: event (obj): Returns: """ if event.type != "Face Recognized": logger.debug("Event is not Face Recognized, break") return event_data = json.loads(event.data) channel = event_data["channel_guid"] server_guid = event_data["server_guid"] channel_full = "{channel}_{server_guid}".format( channel=channel, server_guid=server_guid) channel_obj = self.obj_storage.channels.get(channel) if not channel_obj: logger.info( "Channel %s not in channel list", channel, ) return # ts_best_view локальное время сервера, корректировать не нужно ts = event_data.get("ts_best_view", 0) if not self.fr_filter: logger.info("No event filter, break") # logger.debug("event data: %s", event_data) person_info = self.fr_filter.handle(event_data) logger.debug("person info: %s, is isdict: %s", person_info, isinstance(person_info, dict)) if not person_info: logger.debug("Not suitable person") return if isinstance(person_info, dict): logger.debug("person_info: %s", person_info) if self.same_event_ignoring and se.is_same( channel, person_info.get("person_guid", ""), self.same_event_ignoring): return if isinstance(self.all_fr_folders, dict): _folder_name = self.all_fr_folders.get( person_info.get("folder_guid", ""), person_info.get("folder_guid", ""), ) else: _folder_name = person_info.get("folder_guid", "") alarm_messages = make_alarm_message( channel_name=channel_obj.name, dt=BaseUtils.ts_to_dt(ts), person_name=person_info.get("name", ""), folder_name=_folder_name, score=person_info.get("score", 0), ) images = None if self.callback: if (not ERR_FLAG and host.settings("").guid != "client" and person_info.get("person_guid")): pi = person_image(person_info.get("person_guid")) # logger.debug("pi is: %s", pi) images = { "db_image": pi, "track_image": self.get_track_image(channel, person_info.get("person_guid")), } # from datetime import datetime # import time # # logger.debug( # "chann: %s, trassir ts: %s, trassir dt (%s)," # " time now: %s, dt now: %s, after correction trassir dt is: %s\n", # channel, # event_data["ts_best_view"], # datetime.fromtimestamp(int(event_data["ts_best_view"]) / 1e6), # time.time(), # datetime.now(), # BaseUtils.ts_to_dt(ts), # ) self.callback(channel_full, ts, alarm_messages, images=images) else: logger.debug("Unknown face.") if self.fr_filter.__class__.__name__ in [ "AnyFace", "Unrecognized" ]: alarm_messages = make_alarm_message( channel_name=channel_obj.name, dt=BaseUtils.ts_to_dt(ts), person_name=loc.fr.unrecognized_person, ) if self.callback: self.callback(channel_full, ts, alarm_messages)