Пример #1
0
def getBlueprint():
    gid = request.args.get('gid')
    blueprints_ref = db.collection('blueprints')
    docs = blueprints_ref.stream()
    blueprint = getBlueprintById(gid, docs).to_dict()
    scraped = runRoutine(blueprint["blue"])
    return jsonify(scraped["results"])
Пример #2
0
def get_recommendation(dinner_code):
    if len(dinner_code) != 6:
        return {
            'status': 'ERROR',
            'message': 'Dinner code not correct length (6)!'
        }

    # get matching preferences
    dinner_code_preferences = db.collection('dinner_sessions').document(
        dinner_code).get().to_dict()['preferences']
    if len(dinner_code_preferences) == 0:
        return {
            'status': 'ERROR',
            'message': 'There are no preferences saved for this dinner code!'
        }

    # vectorize and merge
    preferences_vectors = list(
        map(lambda x: [x['rating'], x['price'], x['cuisine'], x['distance']],
            dinner_code_preferences))
    print(preferences_vectors)
    merged_preference = preferences.merge_preferences(preferences_vectors)
    rec = recommendation.make_recommendation(merged_preference)
    similarity = recommendation.compute_similarity(preferences_vectors,
                                                   rec[1:])

    # make recommendation
    return {
        'status': 'OK',
        'result': {
            'resturant_name': rec[0],
            'similarity': round(similarity, 4)
        }
    }
Пример #3
0
def deploy(model_name):

    doc_ref = db.collection(u'Models').document(model_name)

    try:
        doc = doc_ref.get()
        labels = doc.to_dict()['labels']
    except:
        print(u'No such model exists!')
        return 'No such model exists!'

    if 'file' not in request.files:
        flash('No file part')
        return 'No File Sent'

    file = request.files['file']
    file.save("/home/bharathrajeevnair/dsfh-v2/api-backend/tmp/samp.jpeg")
    img = open_image(
        "/home/bharathrajeevnair/dsfh-v2/api-backend/tmp/samp.jpeg")

    learn = load_learner(
        '/home/bharathrajeevnair/dsfh-v2/api-backend/models/' + model_name)
    pred_class, _, _ = learn.predict(img)
    pred = int(pred_class)

    os.remove("/home/bharathrajeevnair/dsfh-v2/api-backend/tmp/samp.jpeg")
    data_foy = {
        u'prediction': labels[pred],
    }
    resy = json.dumps(data_foy)
    respons = json.loads(resy)
    return respons
Пример #4
0
def config():
    folder_name = request.json["data_for_config"]["Folder_Name"]
    fileType = request.json["data_for_config"]["fileType"]
    if folder_name == "" or fileType == "":
        return jsonify(message="No data was sent!", typ="error")
    path = UPLOAD_FOLDER + folder_name
    if (os.path.isdir(path)):
        if fileType == 'Image':
            files_list = []
            for _, _, files in os.walk(path):
                files_list = files

            image_ref = db.collection(u'Images').document(folder_name)
            data = {
                u'names': files_list,
                u'label': folder_name,
                u'isDicom': False
            }
            # Add a new doc in collection 'cities' with ID 'LA'
            image_ref.set(data)
            return jsonify(message="Success! The folder has been updated!",
                           typ="success")

        elif fileType == 'Dicom':
            args = (path, folder_name)
            res = q.enqueue_call(convertDicom, args=args, timeout=400)
            return jsonify(message="Success! The folder will be updated soon!",
                           typ="success")
        else:
            return jsonify(message="Something is wrong with file-type!!",
                           typ="error")
    else:
        return jsonify(
            message="Folder does not exist. Check Folder name carefully!!",
            typ="error")
    def post(self):
        try:
            body = json.loads(
                self.request.body)  # Try to load the body as a JSON object
        except:
            pass
        else:
            uname = body["uname"]
            location = body["location"]
            type_ = body["type"]

            doc_ref = db.collection("users").document(uname)

            if doc_ref.get().exists:
                self.set_status(500)
                self.write({"FAIL": "user already in DB", "Status": "500"})
            else:
                # users[uname] = {"location": location, "type": type_}
                isdriver = True
                if type_ == "passenger":
                    isdriver = False

                doc_ref.set({
                    u'uname': uname,
                    u'location': location,
                    u'isdriver': isdriver
                })

                self.write({
                    "Success": "User saved to database",
                    "Status": "200"
                })
Пример #6
0
 def test_writer(self):
     data = {
         'id': 'test',
         'path': 'test',
         'content': 'test',
         'readed': True
     }
     self.assertEqual(True, self.writer.save(Document(**data), 'test'))
     doc = db.collection('test').document(str(data['id'])).get()
     self.assertEqual(data, doc.to_dict())
Пример #7
0
def get_user_perferences(dinner_code):
    if len(dinner_code) != 6:
        return {
            'status': 'ERROR',
            'message': 'Dinner code not correct length (6)!'
        }

    dinner_code_preferences = db.collection('dinner_sessions').document(
        dinner_code).get().to_dict()['preferences']
    return {'status': 'OK', 'result': dinner_code_preferences}
    def get(self):
        city = self.get_argument('city')
        result = []
        doc_ref = db.collection("users").get()
        for u in doc_ref:
            if u.get("isdriver") and u.get("location") == city:
                result.append(u.get("uname"))

        # for u in users:
        #     if users[u]["type"] == "driver" and users[u]["location"] == city:
        #         result.append(u)

        self.set_header("Content-Type", "text/plain")
        self.finish(json.dumps(result))
Пример #9
0
def record_user_preference(dinner_code):
    if len(dinner_code) != 6:
        return {
            'status': 'ERROR',
            'message': 'Dinner code not correct length (6)!'
        }

    preference = PreferenceModel(
        request.args.get('name', 'Person'),
        float(request.args.get('price', '0')) / 4,
        utilities.convert_pretty_cuisine(request.args.get('cuisine', '')),
        utilities.convert_pretty_distance(request.args.get('distance', '')),
        float(request.args.get('rating', '0')) / 5)

    doc_ref = db.collection('dinner_sessions').document(dinner_code)
    doc_ref.update(
        {'preferences': firestore.ArrayUnion([preference.to_dict()])})

    return {'status': 'OK', 'result': preference.to_dict()}
Пример #10
0
def train(model):
    if request.json:
        labels = request.json["data_for_training"]["labels"]
        description = request.json["data_for_training"]["description"]
        to = request.json["data_for_training"]["toEmail"]
    if (len(labels) < 2):
        err = {
            u'message': "Minimum of 2 labels is required",
        }
        r = json.dumps(err)
        re = json.loads(r)

        return re
    else:
        # Making sure the labels sent exists.
        isuff_labels = []
        for label in labels:
            try:
                doc_ref = db.collection(u'Images').document(label)
                doc = doc_ref.get()
                if (len(doc.to_dict()['names']) < 20):
                    isuff_labels.append(label)
            except:
                return 'No such label exists'

        if (len(isuff_labels) > 0):
            error = {
                "message":
                "These labels dont have enough images (Minimum 20 required)",
            }
            resp = json.dumps(error)
            ress = json.loads(resp)

            return ress
        else:

            args = (labels, description, model, to)
            result = q.enqueue_call(train_model, args=args, timeout=1000)
            return "Success"
Пример #11
0
def sendfile(name):
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            flash('No file part')
            return 'No File Sent'

        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            return 'No File Selected'

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            path = os.path.join(app.config['UPLOAD_FOLDER'], name)
            # The folder is created if it does'nt exist.
            if not os.path.exists(path):
                os.makedirs(path)

            # Pushing name of files to firebase db
            image_ref = db.collection(u'Images').document(name)
            if image_ref.get().exists:
                image_ref.update({u'names': firestore.ArrayUnion([filename])})
            else:
                data = {
                    u'names': [filename],
                    u'label': name,
                }
                # Add a new doc in collection 'cities' with ID 'LA'
                image_ref.set(data)

            file.save(os.path.join(app.config['UPLOAD_FOLDER'], name,
                                   filename))

            return 'File added'

    return 'error'
Пример #12
0
def create_dinner_session():
    dinner_code = utilities.generate_dinner_code(6)
    db.collection('dinner_sessions').document(dinner_code).set(
        {'preferences': []})

    return {'status': 'OK', 'result': {'dinner_code': dinner_code}}