示例#1
0
文件: serve.py 项目: vmlaker/wabbit
def getNearestTime(time_query):
    """Given a datetime object, return the nearest time in 
    the database (in string format), or None if empty."""

    # Convert datetime object to string, for lookup in database.
    tstamp_query = coils.time2string(time_query)

    # Retrieve image timestamps.
    try:
        tstamp_left = db.session.query(mapping.Image.time).\
            filter(mapping.Image.time <= tstamp_query).\
            order_by(mapping.Image.time.desc()).limit(1)
        tstamp_left = tstamp_left[0].time
        delta_left = abs(coils.string2time(tstamp_left) - time_query)
    except:
        tstamp_left = None
        delta_left = dt.timedelta.max
        
    try:
        tstamp_right = db.session.query(mapping.Image.time).\
            filter(mapping.Image.time >= tstamp_query).\
            order_by(mapping.Image.time).limit(1)
        tstamp_right = tstamp_right[0].time
        delta_right = abs(coils.string2time(tstamp_right) - time_query)
    except:
        tstamp_right = None
        delta_right = dt.timedelta.max
        
    # The nearest value has the smallest delta from the query.
    result = tstamp_left if (delta_left < delta_right) else tstamp_right
    return result
示例#2
0
文件: serve.py 项目: vmlaker/wabbit
def slide():
    """Return image of given slider time."""
    
    # Time this functions.
    timer = coils.Timer()

    # Parse the URL parameter "time".
    errors = list()
    try:
        query = flask.request.args.get('time1')
        tstamp1 = coils.string2time(query)
        assert tstamp1 != None
    except:
        errors.append('Failed to parse "time1" parameter.')

    try:
        query = flask.request.args.get('time2')
        tstamp2 = coils.string2time(query)
        assert tstamp2 != None
    except:
        errors.append('Failed to parse "time2" parameter.')

    try:
        query = flask.request.args.get('amount')
        amount = float(query)
    except:
        errors.append('Failed to parse "amount" parameter.')

    # Bail on any errors.
    if errors:
        return flask.jsonify(errors=errors)

    # Compute target time.
    diff = (tstamp2 - tstamp1).total_seconds()
    delta = dt.timedelta(seconds=diff*amount)
    tstamp3 = tstamp1 + delta

    # Get time closest to target time.
    result_time = getNearestTime(tstamp3)

    # Convert time to url.
    if result_time:
        result_url = coils.time2fname(coils.string2time(result_time), full=True)
        result_url = 'pics/{}.jpg'.format(result_url)
    else:
        result_url = None

    return flask.jsonify(
        result_time=result_time,
        result_url=result_url,
        elapsed=timer.get().total_seconds(),
        )
示例#3
0
文件: serve.py 项目: vmlaker/wabbit
def tstamps():
    """Return timestamps within given range."""

    # Parse the URL parameters "begin" and "length".
    errors = list()
    try:
        begin = flask.request.args.get('begin')
        t_begin = coils.string2time(begin)
        assert t_begin != None
    except:
        errors.append('Failed to parse "begin" parameter.')
    try:
        length = int(flask.request.args.get('length'))
    except:
        errors.append('Failed to parse "length" parameter.')

    # Bail on any errors.
    if errors:
        return flask.jsonify(errors=errors)

    # Compute the end time.
    t_end = t_begin + dt.timedelta(seconds=length) if length > 0 else dt.datetime.now()

    # Retrieve image timestamps.
    images = db.session.query(mapping.Image.time).\
        filter(mapping.Image.time > t_begin).\
        filter(mapping.Image.time < t_end).\
        group_by(mapping.Image.time).all()
    images = [ii[0] for ii in images]

    return flask.jsonify(
        size=len(images),
        images=images,
        )
示例#4
0
文件: serve.py 项目: vmlaker/wabbit
def range():
    """Return timestamp range of given amount (since latest.)"""

    # Time this functions.
    timer = coils.Timer()

    # Parse the URL parameter "amount".
    errors = list()
    try:
        amount = flask.request.args.get('amount')
        amount = float(amount)
    except:
        errors.append('Failed to parse "amount" parameter.')

    # Bail on any errors.
    if errors:
        return flask.jsonify(errors=errors)


    latest_tstring = db.session.query(mapping.Datum).\
        filter(mapping.Datum.name=='latest_tstamp')[0].value
    latest_time = coils.string2time(latest_tstring)
    start_time = latest_time - dt.timedelta(seconds=amount)
    start_tstring = getNearestTime(start_time)
    
    return flask.jsonify(
        begin_time=start_tstring,
        end_time=latest_tstring,
        )
示例#5
0
 def doTask(self, tstamp):
     """Read image from disk and propagate it downstream."""
     tstamp = coils.string2time(tstamp)
     fname = coils.time2fname(tstamp, full=True) + '.jpg'
     fname = os.path.join(self._config['pics_dir'], fname)
     image = cv2.imread(fname)
     return tstamp, image
示例#6
0
    def doTask(self, tstamp):
        """Download image."""
        tstamp = coils.string2time(tstamp)
        fname = coils.time2fname(tstamp) + '.jpg'
        dest_dir = os.path.join(self._config['pics_dir'], coils.time2dir(tstamp))
        dest_fname = os.path.join(
            dest_dir,
            fname,
            )
        if os.path.exists(dest_fname):
            print('Skipping {}'.format(dest_fname))
            return    
        try:
            os.makedirs(dest_dir)
        except os.error:
            pass
        saved = os.getcwd()
        os.chdir(dest_dir)
        url = '{}/pics/{}.jpg'.format(
            self._url,
            coils.time2fname(tstamp, full=True),
            )
        print(url)
        wget.download(url, bar=None)
        os.chdir(saved)

        # Propagate timestamp downstream.
        return tstamp
示例#7
0
文件: serve.py 项目: vmlaker/wabbit
def info():
    """Return system information."""
    now = dt.datetime.now()
    now = coils.time2string(now)
    size = db.session.query(mapping.Datum).\
        filter(mapping.Datum.name=='size')[0]
    latest_tstamp = db.session.query(mapping.Datum).\
        filter(mapping.Datum.name=='latest_tstamp')[0]
    latest_url = coils.time2fname(
        coils.string2time(
            latest_tstamp.value), full=True)
    latest_url = 'pics/{}.jpg'.format(latest_url)
    load_avg = os.getloadavg()
    return flask.jsonify(
        server_time=now, 
        db_size=size.value, 
        latest_tstamp=latest_tstamp.value,
        latest_url=latest_url,
        load_avg='{:.2f}, {:.2f}, {:.2f}'.format(*load_avg),
        )
示例#8
0
文件: serve.py 项目: vmlaker/wabbit
def nearest():
    """Return timestamp nearest to given time."""

    # Time this functions.
    timer = coils.Timer()

    # Parse the URL parameter "time".
    errors = list()
    try:
        tstamp_query = flask.request.args.get('time')
        time_query = coils.string2time(tstamp_query)
        assert time_query != None
    except:
        errors.append('Failed to parse "time" parameter.')

    # Bail on any errors.
    if errors:
        return flask.jsonify(errors=errors)
        
    return flask.jsonify(
        result=getNearestTime(time_query),
        elapsed=timer.get().total_seconds(),
        )
示例#9
0
文件: movie.py 项目: vmlaker/wabbit
try:
    conn = engine.connect()
except sa.exc.OperationalError:
    print('Failed to connect.')
    sys.exit(1)
Session = sa.orm.sessionmaker(bind=engine)
session = Session()

# Assemble the pipeline.
pipe = mpipe.Pipeline(
    mpipe.Stage(DiskReader, 8, config=config).link(
        mpipe.Stage(Viewer, speedup=SPEEDUP)))

# Compute the end time.
delta = dt.timedelta(seconds=LENGTH)
begin = coils.string2time(BEGIN)
end = begin + delta if LENGTH > 0 else dt.datetime.now()

# Retrieve image timestamps.
images = session.query(mapping.Image.time).\
    filter(mapping.Image.time > begin).\
    filter(mapping.Image.time < end).\
    group_by(mapping.Image.time).all()
times = [ii[0] for ii in images]
print('Playing {} images.'.format(len(times)))

# Process timestamps in the pipeline.
for time in times:
    pipe.put(time)

# Stop the pipeline.