In [16]:
%matplotlib inline
In [97]:
import os
import sys
import json
sys.path.append('..')
import time
import pylab
import numpy as np
from pprint import pprint
from IPython.display import Image
from matplotlib.dates import date2num, num2date
from datetime import datetime, timedelta
from pysurvey.plot import setup, icolorbar, dateticks, minmax
In [ ]:
json.dump()
In [4]:
import numerousobject.api
reload(numerousobject.api)
Out[4]:
In [5]:
username, password = numerousobject.api.credentials()
In [94]:
api = numerousobject.api.API(username, password)
api.login()
device = api.deviceinfo(1)
alerts = api.alert(device)
clips = api.listclips(device)
print datetime.fromtimestamp(api.logininfo['time']/1000)
print datetime.now()
In [83]:
# Figure out start time from boost exp
tmp = datetime.fromtimestamp(api.logininfo['accountInfo']['boost']['expires']/1000)
tmp - timedelta(days=30)
Out[83]:
In [84]:
# This is how we do the time shuffle... err ok
a = int(round(api.logininfo['time']/1000.0))
tmp = datetime.fromtimestamp(api.logininfo['time']/1000)
b = time.mktime(tmp.timetuple())
tmp2 = datetime.fromtimestamp(int(b))
print a, b, a-b
print api.logininfo['time'], tmp, tmp2
In [85]:
# pprint(api.livesession(device))
alerts = api.alert(device)
alert = alerts[0]
# pprint(alert)
print api.video(device, session=alert['alert'],
starttime=alert['startt']/1000,
endtime=alert['endt']/1000)
motion = api.get(device, alert['startt']/1000)
print motion.keys()
In [86]:
print datetime.fromtimestamp(motion['msg'][0])
print datetime.fromtimestamp(motion['msg'][1])
In [17]:
def plot_motion(motion):
audio = motion['result']['audio']
video = motion['result']['video']
start,end = date2num(map(datetime.fromtimestamp, motion['msg']))
times = np.linspace(start, end, len(audio))
setup(figsize=(12,6), xlabel='time', ylabel='Motion intensity')
pylab.plot(times, audio, label='audio')
pylab.plot(times, video, label='video')
dateticks('%Y-%m-%d %H:%M:%S', rotation=90)
plot_motion(motion)
In [87]:
def getalerts(self, device):
done = False
out = []
offset = 0
while not done:
print len(out),
try:
alerts = self.alert(device, offset=offset)
if len(alerts) == 0:
done = True
out.extend(alerts)
offset += 20
except Exception as e:
print e
break
for alert in out:
alert['datestr'] = str(datetime.fromtimestamp(alert['alert']))
return out
allalerts = getalerts(api, device)
In [88]:
smx = [int(str(alert['smx']), 16) for alert in allalerts]
tmp = [datetime.fromtimestamp(alert['alert']) for alert in allalerts]
setup(figsize=(12,6), yr=[0,11], xr=minmax(tmp), embiggenx=0.1)
pylab.plot(tmp, smx, 's', alpha=0.5, lw=0)
dateticks('%Y-%m-%d %H:%M', rotation=90)
In [89]:
def getmotion(self, device):
start = time.mktime(datetime(2015, 12, 19).timetuple())
current = time.mktime(datetime.now().timetuple())
# delta = timedelta(days=1).total_seconds()
delta = timedelta(hours=12).total_seconds()
done = False
out = {}
while not done:
print '.',
tmp = self.get(device, current)
# print tmp
tmp['current'] = current
tmp['requested'] = str(datetime.now())
out[current] = tmp
current -= delta
if current < start:
break
# if len(out) > 2:
# break
return out
motion = getmotion(api, device)
In [90]:
x,y,z = [],[],[]
for current,info in motion.iteritems():
if 'err' in info:
continue
video = [(t if isinstance(t,int) else 0)
for t in info['result']['video']]
start,end = date2num(map(datetime.fromtimestamp, info['msg']))
x.extend(np.linspace(start, end, len(video)))
y.extend(video)
print len(x), len(video), info.keys()
x,y,z = map(np.array, (x,y,z))
In [91]:
setup(figsize=(12,6), xlabel='Date', ylabel='intensity')
pylab.scatter(x,y, c=np.arange(len(x)), lw=0, alpha=0.6)
dateticks('%Y-%m-%d %H:%M', rotation=90)
In [108]:
setup(figsize=(12,6),
xr=[0,24], xlabel='Hour of the day',
yr=[-1,256], ylabel='intensity')
pylab.scatter((x%1.0)*24, y, c=np.arange(len(x)), lw=0, alpha=0.2)
# dateticks('%Y-%m-%d %H:%M', rotation=90)
Out[108]:
In [23]:
_ = pylab.hist(x, weights=y, bins=100)
dateticks('%Y-%m-%d %H:%M', rotation=90)
In [24]:
ii = np.where(x >= date2num(datetime(2015,12,23)))[0]
print len(ii)
setup(figsize=(12,6), xr=[0,24], xlabel='Hour of the Day')
_ = pylab.hist((np.array(x)[ii]%1.0)*24, weights=np.clip(y, 0,50)[ii],
bins=48, lw=0, alpha=0.7)
In [93]:
OUTDIR = '/Volumes/video/backup_manything/alerts'
# def saveimage(self, filename, image):
# open(filename, 'w').write(image)
def getalertstills(self, device, alerts):
for i, alert in enumerate(alerts):
print i,
# print 'working on: {}'.format(alert['alert'])
outdir = os.path.join(OUTDIR, '{}'.format(alert['alert']))
if not os.path.exists(outdir):
os.makedirs(outdir)
stills = self.liststills(device, alert['alert'],
starttime=alert['startt']/1000,
endtime=alert['endt']/1000)
for still in stills:
filename = os.path.join(outdir, '{}.jpg'.format(still))
if os.path.exists(filename):
# print '.',
continue
img = api.getstill(device, still)
saveimage(self, filename, img)
# break
getalertstills(api, device, allalerts)
In [95]:
sessions = api.session(device)
In [92]:
def saveimage(self, filename, image):
try:
with open(filename, 'w') as f:
f.write(image)
except Exception as e:
os.remove(filename)
raise
In [ ]:
OUTDIR = '/Volumes/video/backup_manything/sessions'
endtime = time.mktime(datetime.now().timetuple())
for session in sessions:
outdir = os.path.join(OUTDIR, '{}'.format(session['session']))
if not os.path.exists(outdir):
os.makedirs(outdir)
infofile = os.path.join(outdir, 'list.npy')
if os.path.exists(infofile):
stills = np.load(infofile)
else:
stills = api.liststills(device, session['session'],
starttime=session['startt']/1000,
endtime=endtime)
np.save(infofile, stills)
print 'Session {} [{}] has {:,d} stills'.format(session['session'],
datetime.fromtimestamp(session['session']),
len(stills))
endtime = np.min(stills)
for j, still in enumerate(stills):
nicetime = int(np.floor(still/1000.0)*1000.0)
filename = os.path.join(outdir,
'{0:d}_{1:%Y}.{1:%m}.{1:%d}_{1:%H}.{1:%M}'.format(nicetime, datetime.fromtimestamp(nicetime)),
'{}.jpg'.format(still))
basedir = os.path.dirname(filename)
if not os.path.exists(basedir):
os.makedirs(basedir)
if os.path.exists(filename):
continue
img = api.getstill(device, still)
if 'invalid token' in img:
print img
raise ValueError('Issue!')
saveimage(api, filename, img)
if (j%1000) == 0:
print j/1000,
# break
# print len(stils)
# break
In [103]:
tmp = os.stat(filename)
tmp.st_mtime
Out[103]:
In [74]:
'{0:d}_{1:%Y}.{1:%m}.{1:%d}_{1:%H}.{1:%M}'.format(int(np.round(1451008217,-3)), datetime.fromtimestamp(1451008217))
Out[74]:
In [60]:
datetime.fromtimestamp(1450923014),datetime.fromtimestamp(1451315986),
Out[60]:
In [134]:
stills = api.liststills(device, alert['alert'],
alert['startt']/1000, alert['endt']/1000)
In [135]:
still = stills[0]
filename = '/Users/ajmendez/tmp/image.jpg'
open(filename, 'w').write(api.getstill(device, still))
Image(filename)
Out[135]:
In [84]:
for alert in alerts:
print api.liststills(device, session=alert['alert'],
starttime=alert['startt'],
endtime=alert['endt'], iscomplex=False)
break
In [126]:
for clip in clips:
# print clip['startt'], clip['id'], clip['type'], clip['endt']-clip['startt'], clip['finished']-clip['created'], clip['description']
print api.video(device, clip['startt'], clip['endt'])
break
In [58]:
# http://clips.manything.com/clips/xxx/clip.mp4
# http://clips.manything.com/clips/xxx/clip.mp4
Out[58]:
In [72]:
import requests
In [101]:
# application/x-fcs
headers = {
'Content-Type':'application/x-fcs',
'Origin':'https://manything.com',
'Referer':'https://manything.com/manything/',
'User-Agent':'Shockwave Flash',
'X-Requested-With':'ShockwaveFlash/20.0.0.228',
}
response = requests.post('https://{}/open/1'.format(device['wowza']), headers=headers)
a=response.content.strip()
# response = requests.post('https://{}.manything.com/idle/{}/0'.format(device['wowza'],a), headers=headers)
print a, response.content
# response = requests.post('https://useast1-wowza-xxx.manything.com/send/1116577027/1')
# print response.content