예제 #1
0
 def put(self):
     token = request.headers['Authorization']
     token = token.split(" ")[1]
     userid = oidc.user_getfield('sub', token)
     resp = Response({"Updated": "Nothing updated"})
     resp.headers["Access-Control-Expose-Headers"] = '*'
     return resp
예제 #2
0
 def post(self):
     args = file_upload.parse_args()
     # token = request.headers['Authorization']
     # userid = oidc.user_getfield('sub', token)
     # canpr = pyquots.can_user_proceed(userid=userid, usagetype='PREDICTION', usagesize="1")
     # if canpr.proceed is not True:
     #     abort(402, "Not enough credits available")
     if args['file'].mimetype == 'image/jpeg' or args[
             'file'].mimetype == 'image/png' or args[
                 'file'].mimetype == 'application/octet-stream':
         token = request.headers['Authorization']
         token = token.split(" ")[1]
         userid = oidc.user_getfield('sub', token)
         file = request.files['file']
         control = args['control']
         exposed = args['exposed']
         exposedAt = args['exposedAt']
         age = args['age']
         generation = args['generation']
         mm = args['mm']
         pixels = args['pixels']
         time_got = int(round(time.time() * 1000))
         filename = file.filename
         file.save(image_path['IMAGE_PATH'] + filename)
         # filename = image_path['IMAGE_PATH'] + filename
         # im = Image.open("./" + file.filename)
         # pyquots.can_user_proceed(userid=userid, usagetype='SAVEIMAGE', usagesize="-1")
         users_bucket = userid + "-deepdaph"
         photoid = randomString(12)
         image = models.Image(userId=userid,
                              photo=users_bucket + "/" + filename,
                              imageId=photoid,
                              control=control,
                              exposed=exposed,
                              exposedAt=exposedAt,
                              age=age,
                              generation=generation,
                              mm=mm,
                              pixels=pixels,
                              time=time_got)
         mongoClient['image'].insert_one(image._asdict())
         try:
             minioClient.make_bucket(users_bucket)
         except BucketAlreadyOwnedByYou as err:
             minioClient.fput_object(users_bucket, filename,
                                     image_path['IMAGE_PATH'] + filename)
             os.remove(image_path['IMAGE_PATH'] + filename)
         except BucketAlreadyExists as err:
             minioClient.fput_object(users_bucket, filename,
                                     image_path['IMAGE_PATH'] + filename)
             os.remove(image_path['IMAGE_PATH'] + filename)
         resp = Response(json.dumps(image._asdict()))
         resp.headers["Access-Control-Expose-Headers"] = '*'
         return resp
     else:
         abort(404)
예제 #3
0
 def delete(self):
     token = request.headers['Authorization']
     token = token.split(" ")[1]
     userid = oidc.user_getfield('sub', token)
     image = request.json
     delete = {"$and": [{"userId": userid}, {"imageId": image['photoId']}]}
     try:
         mongoClient['image'].delete_one(delete)
     except Exception as e:
         abort(404, "Could not delete image")
     resp = Response({"deleted": 1})
     resp.headers["Access-Control-Expose-Headers"] = '*'
     return resp
예제 #4
0
 def delete(self):
     args = parser.parse_args()
     id = args.get('id')
     token = request.headers['Authorization']
     token = token.split(" ")[1]
     userid = oidc.user_getfield('sub', token)
     pred = mongoClient['prediction'].find_one({'_id': ObjectId(id)})
     if pred is None:
         abort(400, 'Not found')
     if pred['userId'] == userid:
         mongoClient['prediction'].delete_one({'_id': ObjectId(id)})
         resp = Response({"deleted": 1})
         resp.headers["Access-Control-Expose-Headers"] = '*'
         return resp
     else:
         abort(403, 'No right to delete the prediction')
예제 #5
0
 def post(self):
     token = request.headers['Authorization']
     token = token.split(" ")[1]
     userid = oidc.user_getfield('sub', token)
     prediction = request.json
     newTask = models.PredictionTask(userId=userid)
     _predid = mongoClient['prediction'].insert_one(prediction).inserted_id
     _taskid = mongoClient['task'].insert_one(newTask._asdict()).inserted_id
     taskStored = models.PredictionTask(userId=userid,
                                        predictionId=_predid,
                                        id=_taskid)
     p = Process(target=async_handler.handle_predictions,
                 args=(prediction, taskStored))
     p.start()
     resp = Response(json_util.dumps(taskStored._asdict()))
     resp.headers["Access-Control-Expose-Headers"] = '*'
     return resp
예제 #6
0
 def put(self):
     token = request.headers['Authorization']
     token = token.split(" ")[1]
     userid = oidc.user_getfield('sub', token)
     image = request.json
     myquery = {"$and": [{"userId": userid}, {"imageId": image['photoId']}]}
     update = {
         "$set": {
             "exposed": image['exposed'],
             "exposedAt": image["exposedAt"],
             "age": image["age"],
             "generation": image["generation"],
             "mm": image["mm"],
             "pixels": image["pixels"]
         }
     }
     try:
         mongoClient['image'].update_one(myquery, update=update)
     except Exception as e:
         abort(404, "Could not update image")
     image_updated = mongoClient['image'].find_one(myquery)
     resp = Response(json_util.dumps(image_updated))
     resp.headers["Access-Control-Expose-Headers"] = '*'
     return resp
예제 #7
0
    def get(self):
        args = parser.parse_args()
        id = args.get('id')
        skip = args.get('skip')
        maximum = args.get('maximum')
        control = args.get('control')
        exposed = args.get('exposed')
        exposedAt = args.get('exposedAt')
        generation = args.get('generation')
        age = args.get('age')
        from_d = args.get('from')
        to_d = args.get('to')
        if id is None:
            if skip is None:
                skip = 0
            if maximum is None:
                maximum = 20
            token = request.headers['Authorization']
            token = token.split(" ")[1]
            userid = oidc.user_getfield('sub', token)
            query_u = {"userId": str(userid)}
            q_ar = []
            if age != 'undefined' and age is not None:
                a = {'age': age}
                q_ar.append(a)
            if generation != 'undefined' and generation is not None:
                g = {'generation': generation}
                q_ar.append(g)
            if exposed != 'false' and exposed is not None and exposed != 'undefined':
                ex = {'exposed': 'true'}
                q_ar.append(ex)
            if control != 'false' and control is not None and control != 'undefined':
                co = {'control': 'true'}
                q_ar.append(co)
            if exposedAt != 'undefined' and exposedAt is not None:
                co = {'exposedAt': exposedAt}
                q_ar.append(co)
            if from_d is not None:
                from_d = base64.b64decode(from_d).decode('utf-8')
                if from_d != 'undefined' and from_d is not None:
                    from_d = unix_time_millis(
                        utc_to_local(
                            datetime.strptime(from_d,
                                              '%a %b %d %Y %H:%M:%S %Z%z')))
                    # from_d = unix_time_millis(datetime.strptime(from_d, "%a %b %d %H:%M:%S %Y (%Z)"))
                    f_d = {'date': {'$gt': from_d}}
                    q_ar.append(f_d)
            if to_d is not None:
                to_d = base64.b64decode(to_d).decode('utf-8')
                if to_d != 'undefined' and to_d is not None:
                    to_d = unix_time_millis(
                        utc_to_local(
                            datetime.strptime(to_d,
                                              '%a %b %d %Y %H:%M:%S %Z%z')))
                    # to_d = unix_time_millis(datetime.strptime(to_d, "%a %b %d %H:%M:%S %Y (%Z)"))
                    t_d = {'date': {'$lt': to_d}}
                    q_ar.append(t_d)
            q_ar.append(query_u)
            query = {"$and": q_ar}
            # query = {"$and": [{"userId": userid}, {"imageId": image_id}]}

            found = mongoClient['prediction'].find(query).skip(skip).limit(
                maximum)
            total = mongoClient['prediction'].count(query)
            f_ar = []
            for f in found:
                f_ar.append(json_util.dumps(f))
            resp = Response(json.dumps(f_ar))
            resp.headers['total'] = total
            resp.headers["Access-Control-Expose-Headers"] = '*'

            # found = mongoClient['prediction'].find(query_u).skip(skip).limit(maximum)
            # total = mongoClient['prediction'].count(query_u)
            # found_j = []
            # for f in found:
            #     found_j.append(json_util.dumps(f))
            # resp = Response(json.dumps(found_j), mimetype='application/json')
            # resp.headers["Access-Control-Expose-Headers"] = '*'
            # resp.headers["Access-Control-Allow-Headers"] = '*'
            resp.headers["total"] = total
            return resp
        elif id is not None:
            query = {"_id": ObjectId(id)}
            found = mongoClient['prediction'].find_one(query)
            resp = Response(json_util.dumps(found))
            resp.headers["Access-Control-Expose-Headers"] = '*'
            # resp.headers["Access-Control-Allow-Headers"] = '*'
            return resp
예제 #8
0
    def get(self):
        args = parser.parse_args()
        image_id = args.get('id')
        skip = args.get('skip')
        maximum = args.get('maximum')
        thumb = args.get('thumbnail')
        token = request.headers['Authorization']
        token = token.split(" ")[1]
        userid = oidc.user_getfield('sub', token)
        if request.headers.get('accept') == 'application/json':
            if skip is None:
                skip = 0
            if maximum is None:
                max = 20
            if image_id is None:
                myquery = {"userId": userid}
                found = []
                try:
                    cursor = mongoClient['image'].find(myquery).skip(
                        skip).limit(maximum)
                    for f in cursor:
                        found.append(json_util.dumps(f))
                    resp = Response(json_util.dumps(found))
                    resp.headers["Access-Control-Expose-Headers"] = '*'
                    return resp
                except Exception as e:
                    abort(404, "Could not get images")
            if image_id is not None:
                myquery = {"$and": [{"userId": userid}, {"imageId": image_id}]}
                found = mongoClient['image'].find_one(myquery)
                resp = Response(json_util.dumps(found))
                resp.headers["Access-Control-Expose-Headers"] = '*'
                return resp
        if request.headers.get('accept') == 'application/octet-stream':

            query = {"$and": [{"userId": userid}, {"imageId": image_id}]}
            found = mongoClient['image'].find_one(query)
            if found:
                photo = found['photo']
                bucket = photo.split("/")[0]
                name = photo.split("/")[1]

                @after_this_request
                def save_or_delete_file(response):
                    try:
                        if os.path.exists(image_path['IMAGE_PATH'] + name):
                            os.remove(image_path['IMAGE_PATH'] + name)
                        return response
                    except Exception:
                        return response

                try:
                    minioClient.fget_object(bucket, name,
                                            image_path['IMAGE_PATH'] + name)
                except Exception:
                    abort(500, "Could not find image")
                if thumb is not None:
                    im = Image.open(image_path['IMAGE_PATH'] + name)
                    size = 128, 128
                    im.thumbnail(size)
                    im.save(image_path['IMAGE_PATH'] + name, "JPEG")
                    try:
                        return send_file(image_path['IMAGE_PATH'] + name)
                    except Exception:
                        abort(404)
                else:
                    return send_file(image_path['IMAGE_PATH'] + name)