def filter_images(self, images): """Filter false positives based Structural similarity index to avoid false alerts.""" status = self.day_or_night(images[0][1], self.gray_refs['day'][0], self.gray_refs['night'][0]) print status exclusions = self.gray_refs[status] threshold = 0.7 last_ref = None result = [] for filename, gray_img, raw_img in images: skip = False if last_ref: dist = ssim(gray_img, exclusions[last_ref], multichannel=False) if dist > threshold: skip = True if not skip: for i, gray_ref in enumerate(exclusions): if i == last_ref: continue dist = ssim(gray_img, gray_ref, multichannel=False) if dist > threshold: skip = True last_ref = i break if not skip: if (time.time() - self.last_notify) > notify_thresh: send_alert('Alert! Motion detected near front door.') self.last_notify = time.time() result.append((filename, gray_img, raw_img)) return result
def track_expenses(): r = redis.StrictRedis(host='localhost', port=6379, db=0) plaid = PlaidHandler() transactions = plaid.get_transactions(7) new_txns = [] set_cnt = r.scard(REDIS_KEY) for tx in transactions: if tx['amount'] < 0: continue if not r.sismember(REDIS_KEY, tx['transaction_id']): new_txns.append(tx) r.sadd(REDIS_KEY, tx['transaction_id']) expenses_dict, total = plaid.categorize_txns(transactions) template = "The expense {name} ${amount} exceeds your weekly budget for {category}" if set_cnt > 0: for tx in new_txns: ct = plaid.find_category(tx['name']) if ct == 'Atm': continue if expenses_dict[ct] > budget_dict.get(ct, 100): msg = template.format(name=tx['name'].title(), amount=tx['amount'], category=ct) send_alert(msg, False) print msg
def craft_and_send_email(t1, t2, config, volcano, d_Azimuth, velocity, mx_pressure, filename): from pandas import Timestamp # create the subject line subject = '{} Airwave Detection'.format(volcano['volcano']) # create the test for the message you want to send message = '{} alarm:\n'.format(config.alarm_name) message = '{}{} detection!\n\n'.format(message, volcano['volcano']) message = '{}Start: {} (UTC)\nEnd: {} (UTC)\n\n'.format( message, t1.strftime('%Y-%m-%d %H:%M'), t2.strftime('%Y-%m-%d %H:%M')) t1_local = Timestamp(t1.datetime, tz='UTC') t2_local = Timestamp(t2.datetime, tz='UTC') t1_local = t1_local.tz_convert('US/Alaska') t2_local = t2_local.tz_convert('US/Alaska') message = '{}Start: {} ({})'.format(message, t1_local.strftime('%Y-%m-%d %H:%M'), t1_local.tzname()) message = '{}\nEnd: {} ({})\n\n'.format( message, t2_local.strftime('%Y-%m-%d %H:%M'), t2_local.tzname()) message = '{}d_Azimuth: {:+.1f} degrees\n'.format(message, d_Azimuth) message = '{}Velocity: {:.0f} m/s\n'.format(message, velocity * 1000) message = '{}Max Pressure: {:.1f} Pa'.format(message, mx_pressure) utils.send_alert(config.alarm_name, subject, message, filename) utils.post_mattermost(subject, message, config.alarm_name, filename) # delete the file you just sent if filename: remove(filename)
def filter_images(files, false_positives): global last_notify, notify_thresh if len(files) <= 0: return false_positives print 'Filtering similar adjacent images...' files = sorted(files, key=lambda x: formatter(x['title'])) prev = None is_person = False for file1 in files: image = cv2.imread(img_path + file1['title']) gray = get_gray(image) is_similar = False if prev is not None: is_similar = check_similar(prev, gray) if is_similar: if not is_person: prev = gray false_positives.append(file1['id']) else: is_person = use_clarifai(model, img_path + file1['title']) if is_person: if (time.time() - last_notify) > notify_thresh: send_alert('Alert! Person detected near front door.') last_notify = time.time() else: prev = gray false_positives.append(file1['id']) print '#false positives = {0}'.format(len(false_positives)) return false_positives
def plug_handler(state, appliance): obj = PlugHandler() if state == 'on': msg = obj.switch_on() elif state == 'off': msg = obj.switch_off() send_alert(appliance + ' ' + msg, True)
def status_change(place, user, status): user = user.title() msg = '' if status == STATUS_REACHED: msg = user + ' reached ' + place + '.' if status == STATUS_AWAY: msg = user + ' left ' + place + '.' send_alert(msg, False)
def route_notifier(destination): obj = GmapsHandler() if destination == 'office': msg = obj.get_route(destination='office') elif destination == 'home': msg = obj.get_route(source='office', destination='home') send_alert(msg, True)
def craft_and_send_email(t1, t2, stations, rms, lvlv, alarm_name, filename): from pandas import Timestamp # create the subject line subject = '--- {} ---'.format(alarm_name) # create the text for the message you want to send message = 'Start: {} (UTC)\nEnd: {} (UTC)\n\n'.format( t1.strftime('%Y-%m-%d %H:%M'), t2.strftime('%Y-%m-%d %H:%M')) t1_local = Timestamp(t1.datetime, tz='UTC') t2_local = Timestamp(t2.datetime, tz='UTC') t1_local = t1_local.tz_convert('US/Alaska') t2_local = t2_local.tz_convert('US/Alaska') message = '{}Start: {} ({})'.format(message, t1_local.strftime('%Y-%m-%d %H:%M'), t1_local.tzname()) message = '{}\nEnd: {} ({})\n\n'.format( message, t2_local.strftime('%Y-%m-%d %H:%M'), t2_local.tzname()) a = np.array([''] * len(rms[:-1])) a[np.where(rms > lvlv)] = '*' sta_message = ''.join( '{}{}: {:.0f}/{}\n'.format(sta, a[i], rms[i], lvlv[i]) for i, sta in enumerate(stations[:-1])) sta_message = ''.join([ sta_message, '\nArrestor: {} {:.0f}/{}'.format(stations[-1], rms[-1], lvlv[-1]) ]) message = ''.join([message, sta_message]) utils.send_alert(alarm_name, subject, message, filename) # utils.post_mattermost(subject,message,filename) utils.post_mattermost(subject, message, alarm_name, filename) # delete the file you just sent if filename: remove(filename)
def stove_button_callback(event): global stove_status global stove_cube global stove_light global stove_text if event.event_type == arena.EventType.mousedown: if stove_status: stove_status = False stove_light.update(color=(0, 0, 0)) stove_cube.update(data='{"material": {"opacity": 0.25}}') stove_cube.update( data= '{"animation": { "property": "scale", "to": "1 1 1", "loop": false, "dur": 0}}' ) else: stove_status = True stove_light.update(color=(100, 0, 0)) stove_cube.update(data='{"material": {"opacity": 0.80}}') stove_cube.update( data= '{"animation": { "property": "scale", "to": "3 3 3", "loop": true, "dur": 1000}}' ) send_alert( ) # Comment this out when testing so you don't get spammed by emails
def process_item(self, item, spider): decisionAlertItems = [] otherAlertItems = [] if 'newIssuances' in item: print ("Alerting on %s issuances" % (len(item['newIssuances']))) for issuance in item['newIssuances']: if (issuance['type'] == 'Decision'): if (len(decisionAlertItems) == 0): decisionAlertItems.append("Daily Decision Issuance for %s, URL: %s" % (issuance['announceDate'], issuance['announceURL'])) urls = issuance['urls'][0] url = urls['url'] alertHeader = "*************** New Certificate Pipeline Decision: %s: %s" % (issuance['docket'], url) print (alertHeader) alertText = "%s\n%s" % (alertHeader, issuance['description']) decisionAlertItems.append(alertText) if (issuance['type'] in ['Notice', 'DelegatedOrder']): if (len(otherAlertItems) == 0): otherAlertItems.append("Daily %s Issuance for %s, URL: %s" % (issuance['announceDate'], issuance['type'], issuance['announceURL'])) urls = issuance['urls'] urlText = "" for url in urls: urlText = urlText + "\n\t%s: %s" % (url['type'], url['url']) alertText = "*************** FERC %s alert on docket %s\n%s%s" % (issuance['type'], issuance['docket'], issuance['description'], urlText) print (alertText) otherAlertItems.append(alertText) if (len(decisionAlertItems) > 0): utils.send_alert(fp.props['to'], "Ferkee Alert! Certificate Pipeline Decision(s) Published for %s" % (issuance['announceDate']), '\n\n'.join (decisionAlertItems)) if (len(otherAlertItems) > 0): utils.send_alert(fp.props['noticeto'], "Ferkee Alert! FERC %s(s) Published for %s" % (issuance['type'], issuance['announceDate']), '\n\n'.join (otherAlertItems)) elif 'newsItems' in item: newsAlertItems = [] print ("Alerting on %s news items" % (len(item['newsItems']))) for news in item['newsItems']: alertHeader = "*************** %s %s" % (news['issuanceDate'], news['description']) urls = news['urls'] urlText = "" for url in urls: urlText = urlText + "\n\t%s: %s" % (url['text'], url['url']) alertText = "%s%s" % (alertHeader, urlText) print (alertText) newsAlertItems.append(alertText) if (len(newsAlertItems) > 0): utils.send_alert(fp.props['noticeto'], "Ferkee Alert! FERC News published to site", '\n\n'.join (newsAlertItems)) else: print ("WARNING: No alerts found in %s" % item.keys()) return item
def main(): landmarks = LIFE360_PARAMS['landmarks'] obj = Life360Handler() adt_handler = ADTHandler() users = ['user1', 'user2'] state = defaultdict(lambda: defaultdict(str)) state_change = False old_d = defaultdict(lambda: defaultdict(str)) prev_d = defaultdict(lambda: defaultdict(str)) try: x = obj.get_location() for user in users: p1 = (x[user]['latitude'], x[user]['longitude']) for place, coords in landmarks.iteritems(): d1 = vincenty(p1, coords).miles prev_d[place][user] = d1 old_d[place][user] = d1 if d1 < 0.15: state[place][user] = STATUS_REACHED if d1 > 0.15: state[place][user] = STATUS_AWAY print 'Init' while True: adt_status = 'disarmed' x = obj.get_location() for user in users: p1 = (x[user]['latitude'], x[user]['longitude']) for place, coords in landmarks.iteritems(): d1 = vincenty(p1, coords).miles print user, str(d1) if d1 < 1 and state[place][user] != STATUS_REACHED and (0.5 < old_d[place][user] - d1): state[place][user] = STATUS_REACHED status_change(place, user, STATUS_REACHED) if place == HOME: state_change = True elif d1 > 0.15 and state[place][user] != STATUS_AWAY and \ d1 > old_d[place][user] and old_d[place][user] < 0.1: state[place][user] = STATUS_AWAY status_change(place, user, STATUS_AWAY) if place == HOME: state_change = True if d1 != prev_d[place][user]: old_d[place][user] = prev_d[place][user] prev_d[place][user] = d1 if state_change: adt_status = adt_handler.get_status() # both left if state[HOME]['user1'] == STATUS_AWAY and state[HOME]['user2'] == STATUS_AWAY: if adt_status == 'Disarmed': # arm_away() send_alert('Both of you guys are out. So I am setting to arm away.') response = adt_handler.arm_away() send_alert(response) print state_change state_change = False time.sleep(60) print state except Exception as e: del obj del adt_handler return
def weather_notifier(cityname): obj = WeatherHandler() msg = obj.get_temperature(city=cityname) send_alert(msg, True)
def email_notifier(): obj = GmailHandler() msg = obj.get_unread(recent=True) send_alert(msg, True)