from flask import request,Flask, jsonify
from checkobject import get_object_location
import numpy as np
import cv2, os, requests, urllib, sys,json, time
from datetime import datetime

app = Flask(__name__)
def _progress(block_num, block_size, total_size):
    '''回调函数
       @block_num: 已经下载的数据块
       @block_size: 数据块的大小
       @total_size: 远程文件的大小
    '''
    sys.stdout.write('\r>> Downloading %.1f%%' % (float(block_num * block_size) / float(total_size) * 100.0))
    sys.stdout.flush()

@app.route('/filtervideo', methods=['POST'])
def filtervideo():
    #videourls = request.form.get('videoUrls')
    dicdatas = request.get_json()
    results = []
    if not os.path.exists('data/'):
        os.mkdir('data/')
    for dicdata in dicdatas:
        date = datetime.today()
        videourl = dicdata["videoUrls"]  
        videoid = dicdata['id']
        videopath = os.sep.join(['data', videoid+'.mp4'])
        barcode = dicdata['barcode']
        
        urllib.request.urlretrieve(videourl, videopath, _progress)

        flag = get_object_location(videopath)
        results.append({'id':videoid, 'result':flag})
        os.remove(videopath)
    print('{} >>>>{}'.format((date),(results)))
    return json.dumps(results)
            
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8085)
